Roll src/third_party/WebKit a3b4a2e:7441784 (svn 202551:202552)
[chromium-blink-merge.git] / third_party / sqlite / amalgamation / sqlite3.c
blob80d4c2232eaa10111ff79ad79f7952b11e74e106
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 virtual table patch for Chromium */
7541 /* Our patches don't conform to SQLite's amalgamation processing. Hack it. */
7542 #ifndef CHROMIUM_SQLITE_API
7543 #define CHROMIUM_SQLITE_API SQLITE_API
7544 #endif
7546 ** Call to initialize the recover virtual-table modules (see recover.c).
7548 ** This could be loaded by default in main.c, but that would make the
7549 ** virtual table available to Web SQL. Breaking it out allows only
7550 ** selected users to enable it (currently sql/recovery.cc).
7552 CHROMIUM_SQLITE_API
7553 int recoverVtableInit(sqlite3 *db);
7554 /* End recover virtual table patch for Chromium */
7556 /* Begin WebDatabase patch for Chromium */
7557 /* Expose some SQLite internals for the WebDatabase vfs.
7558 ** DO NOT EXTEND THE USE OF THIS.
7560 #ifndef CHROMIUM_SQLITE_API
7561 #define CHROMIUM_SQLITE_API SQLITE_API
7562 #endif
7563 #if defined(CHROMIUM_SQLITE_INTERNALS)
7564 #ifdef _WIN32
7565 CHROMIUM_SQLITE_API
7566 void chromium_sqlite3_initialize_win_sqlite3_file(sqlite3_file* file, HANDLE handle);
7567 #else /* _WIN32 */
7568 CHROMIUM_SQLITE_API
7569 void chromium_sqlite3_initialize_unix_sqlite3_file(sqlite3_file* file);
7570 CHROMIUM_SQLITE_API
7571 int chromium_sqlite3_fill_in_unix_sqlite3_file(sqlite3_vfs* vfs,
7572 int fd,
7573 int dirfd,
7574 sqlite3_file* file,
7575 const char* fileName,
7576 int noLock);
7577 CHROMIUM_SQLITE_API
7578 int chromium_sqlite3_get_reusable_file_handle(sqlite3_file* file,
7579 const char* fileName,
7580 int flags,
7581 int* fd);
7582 CHROMIUM_SQLITE_API
7583 void chromium_sqlite3_update_reusable_file_handle(sqlite3_file* file,
7584 int fd,
7585 int flags);
7586 CHROMIUM_SQLITE_API
7587 void chromium_sqlite3_destroy_reusable_file_handle(sqlite3_file* file);
7588 #endif /* _WIN32 */
7589 #endif /* CHROMIUM_SQLITE_INTERNALS */
7590 /* End WebDatabase patch for Chromium */
7593 ** Undo the hack that converts floating point types to integer for
7594 ** builds on processors without floating point support.
7596 #ifdef SQLITE_OMIT_FLOATING_POINT
7597 # undef double
7598 #endif
7600 #if 0
7601 } /* End of the 'extern "C"' block */
7602 #endif
7603 #endif /* _SQLITE3_H_ */
7606 ** 2010 August 30
7608 ** The author disclaims copyright to this source code. In place of
7609 ** a legal notice, here is a blessing:
7611 ** May you do good and not evil.
7612 ** May you find forgiveness for yourself and forgive others.
7613 ** May you share freely, never taking more than you give.
7615 *************************************************************************
7618 #ifndef _SQLITE3RTREE_H_
7619 #define _SQLITE3RTREE_H_
7622 #if 0
7623 extern "C" {
7624 #endif
7626 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7627 typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
7629 /* The double-precision datatype used by RTree depends on the
7630 ** SQLITE_RTREE_INT_ONLY compile-time option.
7632 #ifdef SQLITE_RTREE_INT_ONLY
7633 typedef sqlite3_int64 sqlite3_rtree_dbl;
7634 #else
7635 typedef double sqlite3_rtree_dbl;
7636 #endif
7639 ** Register a geometry callback named zGeom that can be used as part of an
7640 ** R-Tree geometry query as follows:
7642 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7644 SQLITE_API int sqlite3_rtree_geometry_callback(
7645 sqlite3 *db,
7646 const char *zGeom,
7647 int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
7648 void *pContext
7653 ** A pointer to a structure of the following type is passed as the first
7654 ** argument to callbacks registered using rtree_geometry_callback().
7656 struct sqlite3_rtree_geometry {
7657 void *pContext; /* Copy of pContext passed to s_r_g_c() */
7658 int nParam; /* Size of array aParam[] */
7659 sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
7660 void *pUser; /* Callback implementation user data */
7661 void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
7665 ** Register a 2nd-generation geometry callback named zScore that can be
7666 ** used as part of an R-Tree geometry query as follows:
7668 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
7670 SQLITE_API int sqlite3_rtree_query_callback(
7671 sqlite3 *db,
7672 const char *zQueryFunc,
7673 int (*xQueryFunc)(sqlite3_rtree_query_info*),
7674 void *pContext,
7675 void (*xDestructor)(void*)
7680 ** A pointer to a structure of the following type is passed as the
7681 ** argument to scored geometry callback registered using
7682 ** sqlite3_rtree_query_callback().
7684 ** Note that the first 5 fields of this structure are identical to
7685 ** sqlite3_rtree_geometry. This structure is a subclass of
7686 ** sqlite3_rtree_geometry.
7688 struct sqlite3_rtree_query_info {
7689 void *pContext; /* pContext from when function registered */
7690 int nParam; /* Number of function parameters */
7691 sqlite3_rtree_dbl *aParam; /* value of function parameters */
7692 void *pUser; /* callback can use this, if desired */
7693 void (*xDelUser)(void*); /* function to free pUser */
7694 sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
7695 unsigned int *anQueue; /* Number of pending entries in the queue */
7696 int nCoord; /* Number of coordinates */
7697 int iLevel; /* Level of current node or entry */
7698 int mxLevel; /* The largest iLevel value in the tree */
7699 sqlite3_int64 iRowid; /* Rowid for current entry */
7700 sqlite3_rtree_dbl rParentScore; /* Score of parent node */
7701 int eParentWithin; /* Visibility of parent node */
7702 int eWithin; /* OUT: Visiblity */
7703 sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
7707 ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
7709 #define NOT_WITHIN 0 /* Object completely outside of query region */
7710 #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
7711 #define FULLY_WITHIN 2 /* Object fully contained within query region */
7714 #if 0
7715 } /* end of the 'extern "C"' block */
7716 #endif
7718 #endif /* ifndef _SQLITE3RTREE_H_ */
7721 /************** End of sqlite3.h *********************************************/
7722 /************** Continuing where we left off in sqliteInt.h ******************/
7725 ** Include the configuration header output by 'configure' if we're using the
7726 ** autoconf-based build
7728 #ifdef _HAVE_SQLITE_CONFIG_H
7729 #include "config.h"
7730 #endif
7732 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
7733 /************** Begin file sqliteLimit.h *************************************/
7735 ** 2007 May 7
7737 ** The author disclaims copyright to this source code. In place of
7738 ** a legal notice, here is a blessing:
7740 ** May you do good and not evil.
7741 ** May you find forgiveness for yourself and forgive others.
7742 ** May you share freely, never taking more than you give.
7744 *************************************************************************
7746 ** This file defines various limits of what SQLite can process.
7750 ** The maximum length of a TEXT or BLOB in bytes. This also
7751 ** limits the size of a row in a table or index.
7753 ** The hard limit is the ability of a 32-bit signed integer
7754 ** to count the size: 2^31-1 or 2147483647.
7756 #ifndef SQLITE_MAX_LENGTH
7757 # define SQLITE_MAX_LENGTH 1000000000
7758 #endif
7761 ** This is the maximum number of
7763 ** * Columns in a table
7764 ** * Columns in an index
7765 ** * Columns in a view
7766 ** * Terms in the SET clause of an UPDATE statement
7767 ** * Terms in the result set of a SELECT statement
7768 ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
7769 ** * Terms in the VALUES clause of an INSERT statement
7771 ** The hard upper limit here is 32676. Most database people will
7772 ** tell you that in a well-normalized database, you usually should
7773 ** not have more than a dozen or so columns in any table. And if
7774 ** that is the case, there is no point in having more than a few
7775 ** dozen values in any of the other situations described above.
7777 #ifndef SQLITE_MAX_COLUMN
7778 # define SQLITE_MAX_COLUMN 2000
7779 #endif
7782 ** The maximum length of a single SQL statement in bytes.
7784 ** It used to be the case that setting this value to zero would
7785 ** turn the limit off. That is no longer true. It is not possible
7786 ** to turn this limit off.
7788 #ifndef SQLITE_MAX_SQL_LENGTH
7789 # define SQLITE_MAX_SQL_LENGTH 1000000000
7790 #endif
7793 ** The maximum depth of an expression tree. This is limited to
7794 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
7795 ** want to place more severe limits on the complexity of an
7796 ** expression.
7798 ** A value of 0 used to mean that the limit was not enforced.
7799 ** But that is no longer true. The limit is now strictly enforced
7800 ** at all times.
7802 #ifndef SQLITE_MAX_EXPR_DEPTH
7803 # define SQLITE_MAX_EXPR_DEPTH 1000
7804 #endif
7807 ** The maximum number of terms in a compound SELECT statement.
7808 ** The code generator for compound SELECT statements does one
7809 ** level of recursion for each term. A stack overflow can result
7810 ** if the number of terms is too large. In practice, most SQL
7811 ** never has more than 3 or 4 terms. Use a value of 0 to disable
7812 ** any limit on the number of terms in a compount SELECT.
7814 #ifndef SQLITE_MAX_COMPOUND_SELECT
7815 # define SQLITE_MAX_COMPOUND_SELECT 500
7816 #endif
7819 ** The maximum number of opcodes in a VDBE program.
7820 ** Not currently enforced.
7822 #ifndef SQLITE_MAX_VDBE_OP
7823 # define SQLITE_MAX_VDBE_OP 25000
7824 #endif
7827 ** The maximum number of arguments to an SQL function.
7829 #ifndef SQLITE_MAX_FUNCTION_ARG
7830 # define SQLITE_MAX_FUNCTION_ARG 127
7831 #endif
7834 ** The maximum number of in-memory pages to use for the main database
7835 ** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE
7837 #ifndef SQLITE_DEFAULT_CACHE_SIZE
7838 # define SQLITE_DEFAULT_CACHE_SIZE 2000
7839 #endif
7840 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
7841 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500
7842 #endif
7845 ** The default number of frames to accumulate in the log file before
7846 ** checkpointing the database in WAL mode.
7848 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
7849 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
7850 #endif
7853 ** The maximum number of attached databases. This must be between 0
7854 ** and 62. The upper bound on 62 is because a 64-bit integer bitmap
7855 ** is used internally to track attached databases.
7857 #ifndef SQLITE_MAX_ATTACHED
7858 # define SQLITE_MAX_ATTACHED 10
7859 #endif
7863 ** The maximum value of a ?nnn wildcard that the parser will accept.
7865 #ifndef SQLITE_MAX_VARIABLE_NUMBER
7866 # define SQLITE_MAX_VARIABLE_NUMBER 999
7867 #endif
7869 /* Maximum page size. The upper bound on this value is 65536. This a limit
7870 ** imposed by the use of 16-bit offsets within each page.
7872 ** Earlier versions of SQLite allowed the user to change this value at
7873 ** compile time. This is no longer permitted, on the grounds that it creates
7874 ** a library that is technically incompatible with an SQLite library
7875 ** compiled with a different limit. If a process operating on a database
7876 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
7877 ** compiled with the default page-size limit will not be able to rollback
7878 ** the aborted transaction. This could lead to database corruption.
7880 #ifdef SQLITE_MAX_PAGE_SIZE
7881 # undef SQLITE_MAX_PAGE_SIZE
7882 #endif
7883 #define SQLITE_MAX_PAGE_SIZE 65536
7887 ** The default size of a database page.
7889 #ifndef SQLITE_DEFAULT_PAGE_SIZE
7890 # define SQLITE_DEFAULT_PAGE_SIZE 1024
7891 #endif
7892 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
7893 # undef SQLITE_DEFAULT_PAGE_SIZE
7894 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
7895 #endif
7898 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
7899 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
7900 ** device characteristics (sector-size and atomic write() support),
7901 ** SQLite may choose a larger value. This constant is the maximum value
7902 ** SQLite will choose on its own.
7904 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
7905 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
7906 #endif
7907 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
7908 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
7909 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
7910 #endif
7914 ** Maximum number of pages in one database file.
7916 ** This is really just the default value for the max_page_count pragma.
7917 ** This value can be lowered (or raised) at run-time using that the
7918 ** max_page_count macro.
7920 #ifndef SQLITE_MAX_PAGE_COUNT
7921 # define SQLITE_MAX_PAGE_COUNT 1073741823
7922 #endif
7925 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
7926 ** operator.
7928 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
7929 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
7930 #endif
7933 ** Maximum depth of recursion for triggers.
7935 ** A value of 1 means that a trigger program will not be able to itself
7936 ** fire any triggers. A value of 0 means that no trigger programs at all
7937 ** may be executed.
7939 #ifndef SQLITE_MAX_TRIGGER_DEPTH
7940 # define SQLITE_MAX_TRIGGER_DEPTH 1000
7941 #endif
7943 /************** End of sqliteLimit.h *****************************************/
7944 /************** Continuing where we left off in sqliteInt.h ******************/
7946 /* Disable nuisance warnings on Borland compilers */
7947 #if defined(__BORLANDC__)
7948 #pragma warn -rch /* unreachable code */
7949 #pragma warn -ccc /* Condition is always true or false */
7950 #pragma warn -aus /* Assigned value is never used */
7951 #pragma warn -csu /* Comparing signed and unsigned */
7952 #pragma warn -spa /* Suspicious pointer arithmetic */
7953 #endif
7956 ** Include standard header files as necessary
7958 #ifdef HAVE_STDINT_H
7959 #include <stdint.h>
7960 #endif
7961 #ifdef HAVE_INTTYPES_H
7962 #include <inttypes.h>
7963 #endif
7966 ** The following macros are used to cast pointers to integers and
7967 ** integers to pointers. The way you do this varies from one compiler
7968 ** to the next, so we have developed the following set of #if statements
7969 ** to generate appropriate macros for a wide range of compilers.
7971 ** The correct "ANSI" way to do this is to use the intptr_t type.
7972 ** Unfortunately, that typedef is not available on all compilers, or
7973 ** if it is available, it requires an #include of specific headers
7974 ** that vary from one machine to the next.
7976 ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
7977 ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
7978 ** So we have to define the macros in different ways depending on the
7979 ** compiler.
7981 #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
7982 # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
7983 # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
7984 #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
7985 # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
7986 # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
7987 #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
7988 # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
7989 # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
7990 #else /* Generates a warning - but it always works */
7991 # define SQLITE_INT_TO_PTR(X) ((void*)(X))
7992 # define SQLITE_PTR_TO_INT(X) ((int)(X))
7993 #endif
7996 ** A macro to hint to the compiler that a function should not be
7997 ** inlined.
7999 #if defined(__GNUC__)
8000 # define SQLITE_NOINLINE __attribute__((noinline))
8001 #elif defined(_MSC_VER) && _MSC_VER>=1310
8002 # define SQLITE_NOINLINE __declspec(noinline)
8003 #else
8004 # define SQLITE_NOINLINE
8005 #endif
8008 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
8009 ** 0 means mutexes are permanently disable and the library is never
8010 ** threadsafe. 1 means the library is serialized which is the highest
8011 ** level of threadsafety. 2 means the library is multithreaded - multiple
8012 ** threads can use SQLite as long as no two threads try to use the same
8013 ** database connection at the same time.
8015 ** Older versions of SQLite used an optional THREADSAFE macro.
8016 ** We support that for legacy.
8018 #if !defined(SQLITE_THREADSAFE)
8019 # if defined(THREADSAFE)
8020 # define SQLITE_THREADSAFE THREADSAFE
8021 # else
8022 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
8023 # endif
8024 #endif
8027 ** Powersafe overwrite is on by default. But can be turned off using
8028 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
8030 #ifndef SQLITE_POWERSAFE_OVERWRITE
8031 # define SQLITE_POWERSAFE_OVERWRITE 1
8032 #endif
8035 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
8036 ** It determines whether or not the features related to
8037 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
8038 ** be overridden at runtime using the sqlite3_config() API.
8040 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
8041 # define SQLITE_DEFAULT_MEMSTATUS 1
8042 #endif
8045 ** Exactly one of the following macros must be defined in order to
8046 ** specify which memory allocation subsystem to use.
8048 ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
8049 ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
8050 ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
8051 ** SQLITE_MEMDEBUG // Debugging version of system malloc()
8053 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
8054 ** assert() macro is enabled, each call into the Win32 native heap subsystem
8055 ** will cause HeapValidate to be called. If heap validation should fail, an
8056 ** assertion will be triggered.
8058 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
8059 ** the default.
8061 #if defined(SQLITE_SYSTEM_MALLOC) \
8062 + defined(SQLITE_WIN32_MALLOC) \
8063 + defined(SQLITE_ZERO_MALLOC) \
8064 + defined(SQLITE_MEMDEBUG)>1
8065 # error "Two or more of the following compile-time configuration options\
8066 are defined but at most one is allowed:\
8067 SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
8068 SQLITE_ZERO_MALLOC"
8069 #endif
8070 #if defined(SQLITE_SYSTEM_MALLOC) \
8071 + defined(SQLITE_WIN32_MALLOC) \
8072 + defined(SQLITE_ZERO_MALLOC) \
8073 + defined(SQLITE_MEMDEBUG)==0
8074 # define SQLITE_SYSTEM_MALLOC 1
8075 #endif
8078 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
8079 ** sizes of memory allocations below this value where possible.
8081 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
8082 # define SQLITE_MALLOC_SOFT_LIMIT 1024
8083 #endif
8086 ** We need to define _XOPEN_SOURCE as follows in order to enable
8087 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
8088 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
8089 ** it.
8091 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
8092 # define _XOPEN_SOURCE 600
8093 #endif
8096 ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
8097 ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
8098 ** make it true by defining or undefining NDEBUG.
8100 ** Setting NDEBUG makes the code smaller and faster by disabling the
8101 ** assert() statements in the code. So we want the default action
8102 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
8103 ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
8104 ** feature.
8106 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
8107 # define NDEBUG 1
8108 #endif
8109 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
8110 # undef NDEBUG
8111 #endif
8114 ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
8116 #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
8117 # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
8118 #endif
8121 ** The testcase() macro is used to aid in coverage testing. When
8122 ** doing coverage testing, the condition inside the argument to
8123 ** testcase() must be evaluated both true and false in order to
8124 ** get full branch coverage. The testcase() macro is inserted
8125 ** to help ensure adequate test coverage in places where simple
8126 ** condition/decision coverage is inadequate. For example, testcase()
8127 ** can be used to make sure boundary values are tested. For
8128 ** bitmask tests, testcase() can be used to make sure each bit
8129 ** is significant and used at least once. On switch statements
8130 ** where multiple cases go to the same block of code, testcase()
8131 ** can insure that all cases are evaluated.
8134 #ifdef SQLITE_COVERAGE_TEST
8135 SQLITE_PRIVATE void sqlite3Coverage(int);
8136 # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
8137 #else
8138 # define testcase(X)
8139 #endif
8142 ** The TESTONLY macro is used to enclose variable declarations or
8143 ** other bits of code that are needed to support the arguments
8144 ** within testcase() and assert() macros.
8146 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
8147 # define TESTONLY(X) X
8148 #else
8149 # define TESTONLY(X)
8150 #endif
8153 ** Sometimes we need a small amount of code such as a variable initialization
8154 ** to setup for a later assert() statement. We do not want this code to
8155 ** appear when assert() is disabled. The following macro is therefore
8156 ** used to contain that setup code. The "VVA" acronym stands for
8157 ** "Verification, Validation, and Accreditation". In other words, the
8158 ** code within VVA_ONLY() will only run during verification processes.
8160 #ifndef NDEBUG
8161 # define VVA_ONLY(X) X
8162 #else
8163 # define VVA_ONLY(X)
8164 #endif
8167 ** The ALWAYS and NEVER macros surround boolean expressions which
8168 ** are intended to always be true or false, respectively. Such
8169 ** expressions could be omitted from the code completely. But they
8170 ** are included in a few cases in order to enhance the resilience
8171 ** of SQLite to unexpected behavior - to make the code "self-healing"
8172 ** or "ductile" rather than being "brittle" and crashing at the first
8173 ** hint of unplanned behavior.
8175 ** In other words, ALWAYS and NEVER are added for defensive code.
8177 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
8178 ** be true and false so that the unreachable code they specify will
8179 ** not be counted as untested code.
8181 #if defined(SQLITE_COVERAGE_TEST)
8182 # define ALWAYS(X) (1)
8183 # define NEVER(X) (0)
8184 #elif !defined(NDEBUG)
8185 # define ALWAYS(X) ((X)?1:(assert(0),0))
8186 # define NEVER(X) ((X)?(assert(0),1):0)
8187 #else
8188 # define ALWAYS(X) (X)
8189 # define NEVER(X) (X)
8190 #endif
8193 ** Return true (non-zero) if the input is an integer that is too large
8194 ** to fit in 32-bits. This macro is used inside of various testcase()
8195 ** macros to verify that we have tested SQLite for large-file support.
8197 #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
8200 ** The macro unlikely() is a hint that surrounds a boolean
8201 ** expression that is usually false. Macro likely() surrounds
8202 ** a boolean expression that is usually true. These hints could,
8203 ** in theory, be used by the compiler to generate better code, but
8204 ** currently they are just comments for human readers.
8206 #define likely(X) (X)
8207 #define unlikely(X) (X)
8209 /************** Include hash.h in the middle of sqliteInt.h ******************/
8210 /************** Begin file hash.h ********************************************/
8212 ** 2001 September 22
8214 ** The author disclaims copyright to this source code. In place of
8215 ** a legal notice, here is a blessing:
8217 ** May you do good and not evil.
8218 ** May you find forgiveness for yourself and forgive others.
8219 ** May you share freely, never taking more than you give.
8221 *************************************************************************
8222 ** This is the header file for the generic hash-table implementation
8223 ** used in SQLite.
8225 #ifndef _SQLITE_HASH_H_
8226 #define _SQLITE_HASH_H_
8228 /* Forward declarations of structures. */
8229 typedef struct Hash Hash;
8230 typedef struct HashElem HashElem;
8232 /* A complete hash table is an instance of the following structure.
8233 ** The internals of this structure are intended to be opaque -- client
8234 ** code should not attempt to access or modify the fields of this structure
8235 ** directly. Change this structure only by using the routines below.
8236 ** However, some of the "procedures" and "functions" for modifying and
8237 ** accessing this structure are really macros, so we can't really make
8238 ** this structure opaque.
8240 ** All elements of the hash table are on a single doubly-linked list.
8241 ** Hash.first points to the head of this list.
8243 ** There are Hash.htsize buckets. Each bucket points to a spot in
8244 ** the global doubly-linked list. The contents of the bucket are the
8245 ** element pointed to plus the next _ht.count-1 elements in the list.
8247 ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
8248 ** by a linear search of the global list. For small tables, the
8249 ** Hash.ht table is never allocated because if there are few elements
8250 ** in the table, it is faster to do a linear search than to manage
8251 ** the hash table.
8253 struct Hash {
8254 unsigned int htsize; /* Number of buckets in the hash table */
8255 unsigned int count; /* Number of entries in this table */
8256 HashElem *first; /* The first element of the array */
8257 struct _ht { /* the hash table */
8258 int count; /* Number of entries with this hash */
8259 HashElem *chain; /* Pointer to first entry with this hash */
8260 } *ht;
8263 /* Each element in the hash table is an instance of the following
8264 ** structure. All elements are stored on a single doubly-linked list.
8266 ** Again, this structure is intended to be opaque, but it can't really
8267 ** be opaque because it is used by macros.
8269 struct HashElem {
8270 HashElem *next, *prev; /* Next and previous elements in the table */
8271 void *data; /* Data associated with this element */
8272 const char *pKey; /* Key associated with this element */
8276 ** Access routines. To delete, insert a NULL pointer.
8278 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
8279 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
8280 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
8281 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
8284 ** Macros for looping over all elements of a hash table. The idiom is
8285 ** like this:
8287 ** Hash h;
8288 ** HashElem *p;
8289 ** ...
8290 ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
8291 ** SomeStructure *pData = sqliteHashData(p);
8292 ** // do something with pData
8293 ** }
8295 #define sqliteHashFirst(H) ((H)->first)
8296 #define sqliteHashNext(E) ((E)->next)
8297 #define sqliteHashData(E) ((E)->data)
8298 /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
8299 /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
8302 ** Number of entries in a hash table
8304 /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
8306 #endif /* _SQLITE_HASH_H_ */
8308 /************** End of hash.h ************************************************/
8309 /************** Continuing where we left off in sqliteInt.h ******************/
8310 /************** Include parse.h in the middle of sqliteInt.h *****************/
8311 /************** Begin file parse.h *******************************************/
8312 #define TK_SEMI 1
8313 #define TK_EXPLAIN 2
8314 #define TK_QUERY 3
8315 #define TK_PLAN 4
8316 #define TK_BEGIN 5
8317 #define TK_TRANSACTION 6
8318 #define TK_DEFERRED 7
8319 #define TK_IMMEDIATE 8
8320 #define TK_EXCLUSIVE 9
8321 #define TK_COMMIT 10
8322 #define TK_END 11
8323 #define TK_ROLLBACK 12
8324 #define TK_SAVEPOINT 13
8325 #define TK_RELEASE 14
8326 #define TK_TO 15
8327 #define TK_TABLE 16
8328 #define TK_CREATE 17
8329 #define TK_IF 18
8330 #define TK_NOT 19
8331 #define TK_EXISTS 20
8332 #define TK_TEMP 21
8333 #define TK_LP 22
8334 #define TK_RP 23
8335 #define TK_AS 24
8336 #define TK_WITHOUT 25
8337 #define TK_COMMA 26
8338 #define TK_ID 27
8339 #define TK_INDEXED 28
8340 #define TK_ABORT 29
8341 #define TK_ACTION 30
8342 #define TK_AFTER 31
8343 #define TK_ANALYZE 32
8344 #define TK_ASC 33
8345 #define TK_ATTACH 34
8346 #define TK_BEFORE 35
8347 #define TK_BY 36
8348 #define TK_CASCADE 37
8349 #define TK_CAST 38
8350 #define TK_COLUMNKW 39
8351 #define TK_CONFLICT 40
8352 #define TK_DATABASE 41
8353 #define TK_DESC 42
8354 #define TK_DETACH 43
8355 #define TK_EACH 44
8356 #define TK_FAIL 45
8357 #define TK_FOR 46
8358 #define TK_IGNORE 47
8359 #define TK_INITIALLY 48
8360 #define TK_INSTEAD 49
8361 #define TK_LIKE_KW 50
8362 #define TK_MATCH 51
8363 #define TK_NO 52
8364 #define TK_KEY 53
8365 #define TK_OF 54
8366 #define TK_OFFSET 55
8367 #define TK_PRAGMA 56
8368 #define TK_RAISE 57
8369 #define TK_RECURSIVE 58
8370 #define TK_REPLACE 59
8371 #define TK_RESTRICT 60
8372 #define TK_ROW 61
8373 #define TK_TRIGGER 62
8374 #define TK_VACUUM 63
8375 #define TK_VIEW 64
8376 #define TK_VIRTUAL 65
8377 #define TK_WITH 66
8378 #define TK_REINDEX 67
8379 #define TK_RENAME 68
8380 #define TK_CTIME_KW 69
8381 #define TK_ANY 70
8382 #define TK_OR 71
8383 #define TK_AND 72
8384 #define TK_IS 73
8385 #define TK_BETWEEN 74
8386 #define TK_IN 75
8387 #define TK_ISNULL 76
8388 #define TK_NOTNULL 77
8389 #define TK_NE 78
8390 #define TK_EQ 79
8391 #define TK_GT 80
8392 #define TK_LE 81
8393 #define TK_LT 82
8394 #define TK_GE 83
8395 #define TK_ESCAPE 84
8396 #define TK_BITAND 85
8397 #define TK_BITOR 86
8398 #define TK_LSHIFT 87
8399 #define TK_RSHIFT 88
8400 #define TK_PLUS 89
8401 #define TK_MINUS 90
8402 #define TK_STAR 91
8403 #define TK_SLASH 92
8404 #define TK_REM 93
8405 #define TK_CONCAT 94
8406 #define TK_COLLATE 95
8407 #define TK_BITNOT 96
8408 #define TK_STRING 97
8409 #define TK_JOIN_KW 98
8410 #define TK_CONSTRAINT 99
8411 #define TK_DEFAULT 100
8412 #define TK_NULL 101
8413 #define TK_PRIMARY 102
8414 #define TK_UNIQUE 103
8415 #define TK_CHECK 104
8416 #define TK_REFERENCES 105
8417 #define TK_AUTOINCR 106
8418 #define TK_ON 107
8419 #define TK_INSERT 108
8420 #define TK_DELETE 109
8421 #define TK_UPDATE 110
8422 #define TK_SET 111
8423 #define TK_DEFERRABLE 112
8424 #define TK_FOREIGN 113
8425 #define TK_DROP 114
8426 #define TK_UNION 115
8427 #define TK_ALL 116
8428 #define TK_EXCEPT 117
8429 #define TK_INTERSECT 118
8430 #define TK_SELECT 119
8431 #define TK_VALUES 120
8432 #define TK_DISTINCT 121
8433 #define TK_DOT 122
8434 #define TK_FROM 123
8435 #define TK_JOIN 124
8436 #define TK_USING 125
8437 #define TK_ORDER 126
8438 #define TK_GROUP 127
8439 #define TK_HAVING 128
8440 #define TK_LIMIT 129
8441 #define TK_WHERE 130
8442 #define TK_INTO 131
8443 #define TK_INTEGER 132
8444 #define TK_FLOAT 133
8445 #define TK_BLOB 134
8446 #define TK_VARIABLE 135
8447 #define TK_CASE 136
8448 #define TK_WHEN 137
8449 #define TK_THEN 138
8450 #define TK_ELSE 139
8451 #define TK_INDEX 140
8452 #define TK_ALTER 141
8453 #define TK_ADD 142
8454 #define TK_TO_TEXT 143
8455 #define TK_TO_BLOB 144
8456 #define TK_TO_NUMERIC 145
8457 #define TK_TO_INT 146
8458 #define TK_TO_REAL 147
8459 #define TK_ISNOT 148
8460 #define TK_END_OF_FILE 149
8461 #define TK_ILLEGAL 150
8462 #define TK_SPACE 151
8463 #define TK_UNCLOSED_STRING 152
8464 #define TK_FUNCTION 153
8465 #define TK_COLUMN 154
8466 #define TK_AGG_FUNCTION 155
8467 #define TK_AGG_COLUMN 156
8468 #define TK_UMINUS 157
8469 #define TK_UPLUS 158
8470 #define TK_REGISTER 159
8472 /************** End of parse.h ***********************************************/
8473 /************** Continuing where we left off in sqliteInt.h ******************/
8474 #include <stdio.h>
8475 #include <stdlib.h>
8476 #include <string.h>
8477 #include <assert.h>
8478 #include <stddef.h>
8481 ** If compiling for a processor that lacks floating point support,
8482 ** substitute integer for floating-point
8484 #ifdef SQLITE_OMIT_FLOATING_POINT
8485 # define double sqlite_int64
8486 # define float sqlite_int64
8487 # define LONGDOUBLE_TYPE sqlite_int64
8488 # ifndef SQLITE_BIG_DBL
8489 # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
8490 # endif
8491 # define SQLITE_OMIT_DATETIME_FUNCS 1
8492 # define SQLITE_OMIT_TRACE 1
8493 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
8494 # undef SQLITE_HAVE_ISNAN
8495 #endif
8496 #ifndef SQLITE_BIG_DBL
8497 # define SQLITE_BIG_DBL (1e99)
8498 #endif
8501 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
8502 ** afterward. Having this macro allows us to cause the C compiler
8503 ** to omit code used by TEMP tables without messy #ifndef statements.
8505 #ifdef SQLITE_OMIT_TEMPDB
8506 #define OMIT_TEMPDB 1
8507 #else
8508 #define OMIT_TEMPDB 0
8509 #endif
8512 ** The "file format" number is an integer that is incremented whenever
8513 ** the VDBE-level file format changes. The following macros define the
8514 ** the default file format for new databases and the maximum file format
8515 ** that the library can read.
8517 #define SQLITE_MAX_FILE_FORMAT 4
8518 #ifndef SQLITE_DEFAULT_FILE_FORMAT
8519 # define SQLITE_DEFAULT_FILE_FORMAT 4
8520 #endif
8523 ** Determine whether triggers are recursive by default. This can be
8524 ** changed at run-time using a pragma.
8526 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
8527 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
8528 #endif
8531 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
8532 ** on the command-line
8534 #ifndef SQLITE_TEMP_STORE
8535 # define SQLITE_TEMP_STORE 1
8536 # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
8537 #endif
8540 ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
8541 ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
8542 ** to zero.
8544 #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
8545 # undef SQLITE_MAX_WORKER_THREADS
8546 # define SQLITE_MAX_WORKER_THREADS 0
8547 #endif
8548 #ifndef SQLITE_MAX_WORKER_THREADS
8549 # define SQLITE_MAX_WORKER_THREADS 8
8550 #endif
8551 #ifndef SQLITE_DEFAULT_WORKER_THREADS
8552 # define SQLITE_DEFAULT_WORKER_THREADS 0
8553 #endif
8554 #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
8555 # undef SQLITE_MAX_WORKER_THREADS
8556 # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
8557 #endif
8561 ** GCC does not define the offsetof() macro so we'll have to do it
8562 ** ourselves.
8564 #ifndef offsetof
8565 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
8566 #endif
8569 ** Macros to compute minimum and maximum of two numbers.
8571 #define MIN(A,B) ((A)<(B)?(A):(B))
8572 #define MAX(A,B) ((A)>(B)?(A):(B))
8575 ** Swap two objects of type TYPE.
8577 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
8580 ** Check to see if this machine uses EBCDIC. (Yes, believe it or
8581 ** not, there are still machines out there that use EBCDIC.)
8583 #if 'A' == '\301'
8584 # define SQLITE_EBCDIC 1
8585 #else
8586 # define SQLITE_ASCII 1
8587 #endif
8590 ** Integers of known sizes. These typedefs might change for architectures
8591 ** where the sizes very. Preprocessor macros are available so that the
8592 ** types can be conveniently redefined at compile-type. Like this:
8594 ** cc '-DUINTPTR_TYPE=long long int' ...
8596 #ifndef UINT32_TYPE
8597 # ifdef HAVE_UINT32_T
8598 # define UINT32_TYPE uint32_t
8599 # else
8600 # define UINT32_TYPE unsigned int
8601 # endif
8602 #endif
8603 #ifndef UINT16_TYPE
8604 # ifdef HAVE_UINT16_T
8605 # define UINT16_TYPE uint16_t
8606 # else
8607 # define UINT16_TYPE unsigned short int
8608 # endif
8609 #endif
8610 #ifndef INT16_TYPE
8611 # ifdef HAVE_INT16_T
8612 # define INT16_TYPE int16_t
8613 # else
8614 # define INT16_TYPE short int
8615 # endif
8616 #endif
8617 #ifndef UINT8_TYPE
8618 # ifdef HAVE_UINT8_T
8619 # define UINT8_TYPE uint8_t
8620 # else
8621 # define UINT8_TYPE unsigned char
8622 # endif
8623 #endif
8624 #ifndef INT8_TYPE
8625 # ifdef HAVE_INT8_T
8626 # define INT8_TYPE int8_t
8627 # else
8628 # define INT8_TYPE signed char
8629 # endif
8630 #endif
8631 #ifndef LONGDOUBLE_TYPE
8632 # define LONGDOUBLE_TYPE long double
8633 #endif
8634 typedef sqlite_int64 i64; /* 8-byte signed integer */
8635 typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
8636 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
8637 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
8638 typedef INT16_TYPE i16; /* 2-byte signed integer */
8639 typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
8640 typedef INT8_TYPE i8; /* 1-byte signed integer */
8643 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
8644 ** that can be stored in a u32 without loss of data. The value
8645 ** is 0x00000000ffffffff. But because of quirks of some compilers, we
8646 ** have to specify the value in the less intuitive manner shown:
8648 #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
8651 ** The datatype used to store estimates of the number of rows in a
8652 ** table or index. This is an unsigned integer type. For 99.9% of
8653 ** the world, a 32-bit integer is sufficient. But a 64-bit integer
8654 ** can be used at compile-time if desired.
8656 #ifdef SQLITE_64BIT_STATS
8657 typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
8658 #else
8659 typedef u32 tRowcnt; /* 32-bit is the default */
8660 #endif
8663 ** Estimated quantities used for query planning are stored as 16-bit
8664 ** logarithms. For quantity X, the value stored is 10*log2(X). This
8665 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
8666 ** But the allowed values are "grainy". Not every value is representable.
8667 ** For example, quantities 16 and 17 are both represented by a LogEst
8668 ** of 40. However, since LogEst quantaties are suppose to be estimates,
8669 ** not exact values, this imprecision is not a problem.
8671 ** "LogEst" is short for "Logarithmic Estimate".
8673 ** Examples:
8674 ** 1 -> 0 20 -> 43 10000 -> 132
8675 ** 2 -> 10 25 -> 46 25000 -> 146
8676 ** 3 -> 16 100 -> 66 1000000 -> 199
8677 ** 4 -> 20 1000 -> 99 1048576 -> 200
8678 ** 10 -> 33 1024 -> 100 4294967296 -> 320
8680 ** The LogEst can be negative to indicate fractional values.
8681 ** Examples:
8683 ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
8685 typedef INT16_TYPE LogEst;
8688 ** Macros to determine whether the machine is big or little endian,
8689 ** and whether or not that determination is run-time or compile-time.
8691 ** For best performance, an attempt is made to guess at the byte-order
8692 ** using C-preprocessor macros. If that is unsuccessful, or if
8693 ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
8694 ** at run-time.
8696 #ifdef SQLITE_AMALGAMATION
8697 SQLITE_PRIVATE const int sqlite3one = 1;
8698 #else
8699 SQLITE_PRIVATE const int sqlite3one;
8700 #endif
8701 #if (defined(i386) || defined(__i386__) || defined(_M_IX86) || \
8702 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
8703 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
8704 defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
8705 # define SQLITE_BYTEORDER 1234
8706 # define SQLITE_BIGENDIAN 0
8707 # define SQLITE_LITTLEENDIAN 1
8708 # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
8709 #endif
8710 #if (defined(sparc) || defined(__ppc__)) \
8711 && !defined(SQLITE_RUNTIME_BYTEORDER)
8712 # define SQLITE_BYTEORDER 4321
8713 # define SQLITE_BIGENDIAN 1
8714 # define SQLITE_LITTLEENDIAN 0
8715 # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
8716 #endif
8717 #if !defined(SQLITE_BYTEORDER)
8718 # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
8719 # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
8720 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
8721 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
8722 #endif
8725 ** Constants for the largest and smallest possible 64-bit signed integers.
8726 ** These macros are designed to work correctly on both 32-bit and 64-bit
8727 ** compilers.
8729 #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
8730 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
8733 ** Round up a number to the next larger multiple of 8. This is used
8734 ** to force 8-byte alignment on 64-bit architectures.
8736 #define ROUND8(x) (((x)+7)&~7)
8739 ** Round down to the nearest multiple of 8
8741 #define ROUNDDOWN8(x) ((x)&~7)
8744 ** Assert that the pointer X is aligned to an 8-byte boundary. This
8745 ** macro is used only within assert() to verify that the code gets
8746 ** all alignment restrictions correct.
8748 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
8749 ** underlying malloc() implementation might return us 4-byte aligned
8750 ** pointers. In that case, only verify 4-byte alignment.
8752 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
8753 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
8754 #else
8755 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
8756 #endif
8759 ** Disable MMAP on platforms where it is known to not work
8761 #if defined(__OpenBSD__) || defined(__QNXNTO__)
8762 # undef SQLITE_MAX_MMAP_SIZE
8763 # define SQLITE_MAX_MMAP_SIZE 0
8764 #endif
8767 ** Default maximum size of memory used by memory-mapped I/O in the VFS
8769 #ifdef __APPLE__
8770 # include <TargetConditionals.h>
8771 # if TARGET_OS_IPHONE
8772 # undef SQLITE_MAX_MMAP_SIZE
8773 # define SQLITE_MAX_MMAP_SIZE 0
8774 # endif
8775 #endif
8776 #ifndef SQLITE_MAX_MMAP_SIZE
8777 # if defined(__linux__) \
8778 || defined(_WIN32) \
8779 || (defined(__APPLE__) && defined(__MACH__)) \
8780 || defined(__sun)
8781 # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
8782 # else
8783 # define SQLITE_MAX_MMAP_SIZE 0
8784 # endif
8785 # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
8786 #endif
8789 ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
8790 ** default MMAP_SIZE is specified at compile-time, make sure that it does
8791 ** not exceed the maximum mmap size.
8793 #ifndef SQLITE_DEFAULT_MMAP_SIZE
8794 # define SQLITE_DEFAULT_MMAP_SIZE 0
8795 # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
8796 #endif
8797 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
8798 # undef SQLITE_DEFAULT_MMAP_SIZE
8799 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
8800 #endif
8803 ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
8804 ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
8805 ** define SQLITE_ENABLE_STAT3_OR_STAT4
8807 #ifdef SQLITE_ENABLE_STAT4
8808 # undef SQLITE_ENABLE_STAT3
8809 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
8810 #elif SQLITE_ENABLE_STAT3
8811 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
8812 #elif SQLITE_ENABLE_STAT3_OR_STAT4
8813 # undef SQLITE_ENABLE_STAT3_OR_STAT4
8814 #endif
8817 ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
8818 ** the Select query generator tracing logic is turned on.
8820 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
8821 # define SELECTTRACE_ENABLED 1
8822 #else
8823 # define SELECTTRACE_ENABLED 0
8824 #endif
8827 ** An instance of the following structure is used to store the busy-handler
8828 ** callback for a given sqlite handle.
8830 ** The sqlite.busyHandler member of the sqlite struct contains the busy
8831 ** callback for the database handle. Each pager opened via the sqlite
8832 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
8833 ** callback is currently invoked only from within pager.c.
8835 typedef struct BusyHandler BusyHandler;
8836 struct BusyHandler {
8837 int (*xFunc)(void *,int); /* The busy callback */
8838 void *pArg; /* First arg to busy callback */
8839 int nBusy; /* Incremented with each busy call */
8843 ** Name of the master database table. The master database table
8844 ** is a special table that holds the names and attributes of all
8845 ** user tables and indices.
8847 #define MASTER_NAME "sqlite_master"
8848 #define TEMP_MASTER_NAME "sqlite_temp_master"
8851 ** The root-page of the master database table.
8853 #define MASTER_ROOT 1
8856 ** The name of the schema table.
8858 #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
8861 ** A convenience macro that returns the number of elements in
8862 ** an array.
8864 #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
8867 ** Determine if the argument is a power of two
8869 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
8872 ** The following value as a destructor means to use sqlite3DbFree().
8873 ** The sqlite3DbFree() routine requires two parameters instead of the
8874 ** one parameter that destructors normally want. So we have to introduce
8875 ** this magic value that the code knows to handle differently. Any
8876 ** pointer will work here as long as it is distinct from SQLITE_STATIC
8877 ** and SQLITE_TRANSIENT.
8879 #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
8882 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
8883 ** not support Writable Static Data (WSD) such as global and static variables.
8884 ** All variables must either be on the stack or dynamically allocated from
8885 ** the heap. When WSD is unsupported, the variable declarations scattered
8886 ** throughout the SQLite code must become constants instead. The SQLITE_WSD
8887 ** macro is used for this purpose. And instead of referencing the variable
8888 ** directly, we use its constant as a key to lookup the run-time allocated
8889 ** buffer that holds real variable. The constant is also the initializer
8890 ** for the run-time allocated buffer.
8892 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
8893 ** macros become no-ops and have zero performance impact.
8895 #ifdef SQLITE_OMIT_WSD
8896 #define SQLITE_WSD const
8897 #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
8898 #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
8899 SQLITE_API int sqlite3_wsd_init(int N, int J);
8900 SQLITE_API void *sqlite3_wsd_find(void *K, int L);
8901 #else
8902 #define SQLITE_WSD
8903 #define GLOBAL(t,v) v
8904 #define sqlite3GlobalConfig sqlite3Config
8905 #endif
8908 ** The following macros are used to suppress compiler warnings and to
8909 ** make it clear to human readers when a function parameter is deliberately
8910 ** left unused within the body of a function. This usually happens when
8911 ** a function is called via a function pointer. For example the
8912 ** implementation of an SQL aggregate step callback may not use the
8913 ** parameter indicating the number of arguments passed to the aggregate,
8914 ** if it knows that this is enforced elsewhere.
8916 ** When a function parameter is not used at all within the body of a function,
8917 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
8918 ** However, these macros may also be used to suppress warnings related to
8919 ** parameters that may or may not be used depending on compilation options.
8920 ** For example those parameters only used in assert() statements. In these
8921 ** cases the parameters are named as per the usual conventions.
8923 #define UNUSED_PARAMETER(x) (void)(x)
8924 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
8927 ** Forward references to structures
8929 typedef struct AggInfo AggInfo;
8930 typedef struct AuthContext AuthContext;
8931 typedef struct AutoincInfo AutoincInfo;
8932 typedef struct Bitvec Bitvec;
8933 typedef struct CollSeq CollSeq;
8934 typedef struct Column Column;
8935 typedef struct Db Db;
8936 typedef struct Schema Schema;
8937 typedef struct Expr Expr;
8938 typedef struct ExprList ExprList;
8939 typedef struct ExprSpan ExprSpan;
8940 typedef struct FKey FKey;
8941 typedef struct FuncDestructor FuncDestructor;
8942 typedef struct FuncDef FuncDef;
8943 typedef struct FuncDefHash FuncDefHash;
8944 typedef struct IdList IdList;
8945 typedef struct Index Index;
8946 typedef struct IndexSample IndexSample;
8947 typedef struct KeyClass KeyClass;
8948 typedef struct KeyInfo KeyInfo;
8949 typedef struct Lookaside Lookaside;
8950 typedef struct LookasideSlot LookasideSlot;
8951 typedef struct Module Module;
8952 typedef struct NameContext NameContext;
8953 typedef struct Parse Parse;
8954 typedef struct PrintfArguments PrintfArguments;
8955 typedef struct RowSet RowSet;
8956 typedef struct Savepoint Savepoint;
8957 typedef struct Select Select;
8958 typedef struct SQLiteThread SQLiteThread;
8959 typedef struct SelectDest SelectDest;
8960 typedef struct SrcList SrcList;
8961 typedef struct StrAccum StrAccum;
8962 typedef struct Table Table;
8963 typedef struct TableLock TableLock;
8964 typedef struct Token Token;
8965 typedef struct TreeView TreeView;
8966 typedef struct Trigger Trigger;
8967 typedef struct TriggerPrg TriggerPrg;
8968 typedef struct TriggerStep TriggerStep;
8969 typedef struct UnpackedRecord UnpackedRecord;
8970 typedef struct VTable VTable;
8971 typedef struct VtabCtx VtabCtx;
8972 typedef struct Walker Walker;
8973 typedef struct WhereInfo WhereInfo;
8974 typedef struct With With;
8977 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
8978 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
8979 ** pointer types (i.e. FuncDef) defined above.
8981 /************** Include btree.h in the middle of sqliteInt.h *****************/
8982 /************** Begin file btree.h *******************************************/
8984 ** 2001 September 15
8986 ** The author disclaims copyright to this source code. In place of
8987 ** a legal notice, here is a blessing:
8989 ** May you do good and not evil.
8990 ** May you find forgiveness for yourself and forgive others.
8991 ** May you share freely, never taking more than you give.
8993 *************************************************************************
8994 ** This header file defines the interface that the sqlite B-Tree file
8995 ** subsystem. See comments in the source code for a detailed description
8996 ** of what each interface routine does.
8998 #ifndef _BTREE_H_
8999 #define _BTREE_H_
9001 /* TODO: This definition is just included so other modules compile. It
9002 ** needs to be revisited.
9004 #define SQLITE_N_BTREE_META 10
9007 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
9008 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
9010 #ifndef SQLITE_DEFAULT_AUTOVACUUM
9011 #define SQLITE_DEFAULT_AUTOVACUUM 0
9012 #endif
9014 #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
9015 #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
9016 #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
9019 ** Forward declarations of structure
9021 typedef struct Btree Btree;
9022 typedef struct BtCursor BtCursor;
9023 typedef struct BtShared BtShared;
9026 SQLITE_PRIVATE int sqlite3BtreeOpen(
9027 sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
9028 const char *zFilename, /* Name of database file to open */
9029 sqlite3 *db, /* Associated database connection */
9030 Btree **ppBtree, /* Return open Btree* here */
9031 int flags, /* Flags */
9032 int vfsFlags /* Flags passed through to VFS open */
9035 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
9036 ** following values.
9038 ** NOTE: These values must match the corresponding PAGER_ values in
9039 ** pager.h.
9041 #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
9042 #define BTREE_MEMORY 2 /* This is an in-memory DB */
9043 #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
9044 #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
9046 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
9047 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
9048 #if SQLITE_MAX_MMAP_SIZE>0
9049 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
9050 #endif
9051 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
9052 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
9053 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
9054 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
9055 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
9056 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
9057 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
9058 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
9059 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
9060 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
9061 #endif
9062 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
9063 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
9064 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
9065 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
9066 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
9067 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
9068 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
9069 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
9070 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
9071 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
9072 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
9073 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
9074 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
9075 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
9076 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
9077 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
9079 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
9080 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
9081 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
9083 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
9085 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
9086 ** of the flags shown below.
9088 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
9089 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
9090 ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
9091 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
9092 ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
9093 ** indices.)
9095 #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
9096 #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
9098 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
9099 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
9100 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
9101 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
9103 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
9104 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
9106 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
9109 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
9110 ** should be one of the following values. The integer values are assigned
9111 ** to constants so that the offset of the corresponding field in an
9112 ** SQLite database header may be found using the following formula:
9114 ** offset = 36 + (idx * 4)
9116 ** For example, the free-page-count field is located at byte offset 36 of
9117 ** the database file header. The incr-vacuum-flag field is located at
9118 ** byte offset 64 (== 36+4*7).
9120 #define BTREE_FREE_PAGE_COUNT 0
9121 #define BTREE_SCHEMA_VERSION 1
9122 #define BTREE_FILE_FORMAT 2
9123 #define BTREE_DEFAULT_CACHE_SIZE 3
9124 #define BTREE_LARGEST_ROOT_PAGE 4
9125 #define BTREE_TEXT_ENCODING 5
9126 #define BTREE_USER_VERSION 6
9127 #define BTREE_INCR_VACUUM 7
9128 #define BTREE_APPLICATION_ID 8
9131 ** Values that may be OR'd together to form the second argument of an
9132 ** sqlite3BtreeCursorHints() call.
9134 #define BTREE_BULKLOAD 0x00000001
9136 SQLITE_PRIVATE int sqlite3BtreeCursor(
9137 Btree*, /* BTree containing table to open */
9138 int iTable, /* Index of root page */
9139 int wrFlag, /* 1 for writing. 0 for read-only */
9140 struct KeyInfo*, /* First argument to compare function */
9141 BtCursor *pCursor /* Space to write cursor structure */
9143 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
9144 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
9146 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
9147 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
9148 BtCursor*,
9149 UnpackedRecord *pUnKey,
9150 i64 intKey,
9151 int bias,
9152 int *pRes
9154 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
9155 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
9156 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
9157 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
9158 const void *pData, int nData,
9159 int nZero, int bias, int seekResult);
9160 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
9161 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
9162 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
9163 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
9164 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
9165 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
9166 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
9167 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
9168 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
9169 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
9170 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
9172 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
9173 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
9175 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
9176 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
9177 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
9178 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
9179 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
9180 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
9182 #ifndef NDEBUG
9183 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
9184 #endif
9186 #ifndef SQLITE_OMIT_BTREECOUNT
9187 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
9188 #endif
9190 #ifdef SQLITE_TEST
9191 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
9192 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
9193 #endif
9195 #ifndef SQLITE_OMIT_WAL
9196 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
9197 #endif
9200 ** If we are not using shared cache, then there is no need to
9201 ** use mutexes to access the BtShared structures. So make the
9202 ** Enter and Leave procedures no-ops.
9204 #ifndef SQLITE_OMIT_SHARED_CACHE
9205 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
9206 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
9207 #else
9208 # define sqlite3BtreeEnter(X)
9209 # define sqlite3BtreeEnterAll(X)
9210 #endif
9212 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
9213 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
9214 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
9215 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
9216 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
9217 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
9218 #ifndef NDEBUG
9219 /* These routines are used inside assert() statements only. */
9220 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
9221 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
9222 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
9223 #endif
9224 #else
9226 # define sqlite3BtreeSharable(X) 0
9227 # define sqlite3BtreeLeave(X)
9228 # define sqlite3BtreeEnterCursor(X)
9229 # define sqlite3BtreeLeaveCursor(X)
9230 # define sqlite3BtreeLeaveAll(X)
9232 # define sqlite3BtreeHoldsMutex(X) 1
9233 # define sqlite3BtreeHoldsAllMutexes(X) 1
9234 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
9235 #endif
9238 #endif /* _BTREE_H_ */
9240 /************** End of btree.h ***********************************************/
9241 /************** Continuing where we left off in sqliteInt.h ******************/
9242 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
9243 /************** Begin file vdbe.h ********************************************/
9245 ** 2001 September 15
9247 ** The author disclaims copyright to this source code. In place of
9248 ** a legal notice, here is a blessing:
9250 ** May you do good and not evil.
9251 ** May you find forgiveness for yourself and forgive others.
9252 ** May you share freely, never taking more than you give.
9254 *************************************************************************
9255 ** Header file for the Virtual DataBase Engine (VDBE)
9257 ** This header defines the interface to the virtual database engine
9258 ** or VDBE. The VDBE implements an abstract machine that runs a
9259 ** simple program to access and modify the underlying database.
9261 #ifndef _SQLITE_VDBE_H_
9262 #define _SQLITE_VDBE_H_
9263 /* #include <stdio.h> */
9266 ** A single VDBE is an opaque structure named "Vdbe". Only routines
9267 ** in the source file sqliteVdbe.c are allowed to see the insides
9268 ** of this structure.
9270 typedef struct Vdbe Vdbe;
9273 ** The names of the following types declared in vdbeInt.h are required
9274 ** for the VdbeOp definition.
9276 typedef struct Mem Mem;
9277 typedef struct SubProgram SubProgram;
9280 ** A single instruction of the virtual machine has an opcode
9281 ** and as many as three operands. The instruction is recorded
9282 ** as an instance of the following structure:
9284 struct VdbeOp {
9285 u8 opcode; /* What operation to perform */
9286 signed char p4type; /* One of the P4_xxx constants for p4 */
9287 u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
9288 u8 p5; /* Fifth parameter is an unsigned character */
9289 int p1; /* First operand */
9290 int p2; /* Second parameter (often the jump destination) */
9291 int p3; /* The third parameter */
9292 union { /* fourth parameter */
9293 int i; /* Integer value if p4type==P4_INT32 */
9294 void *p; /* Generic pointer */
9295 char *z; /* Pointer to data for string (char array) types */
9296 i64 *pI64; /* Used when p4type is P4_INT64 */
9297 double *pReal; /* Used when p4type is P4_REAL */
9298 FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
9299 CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
9300 Mem *pMem; /* Used when p4type is P4_MEM */
9301 VTable *pVtab; /* Used when p4type is P4_VTAB */
9302 KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
9303 int *ai; /* Used when p4type is P4_INTARRAY */
9304 SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
9305 int (*xAdvance)(BtCursor *, int *);
9306 } p4;
9307 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
9308 char *zComment; /* Comment to improve readability */
9309 #endif
9310 #ifdef VDBE_PROFILE
9311 u32 cnt; /* Number of times this instruction was executed */
9312 u64 cycles; /* Total time spent executing this instruction */
9313 #endif
9314 #ifdef SQLITE_VDBE_COVERAGE
9315 int iSrcLine; /* Source-code line that generated this opcode */
9316 #endif
9318 typedef struct VdbeOp VdbeOp;
9322 ** A sub-routine used to implement a trigger program.
9324 struct SubProgram {
9325 VdbeOp *aOp; /* Array of opcodes for sub-program */
9326 int nOp; /* Elements in aOp[] */
9327 int nMem; /* Number of memory cells required */
9328 int nCsr; /* Number of cursors required */
9329 int nOnce; /* Number of OP_Once instructions */
9330 void *token; /* id that may be used to recursive triggers */
9331 SubProgram *pNext; /* Next sub-program already visited */
9335 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
9336 ** it takes up less space.
9338 struct VdbeOpList {
9339 u8 opcode; /* What operation to perform */
9340 signed char p1; /* First operand */
9341 signed char p2; /* Second parameter (often the jump destination) */
9342 signed char p3; /* Third parameter */
9344 typedef struct VdbeOpList VdbeOpList;
9347 ** Allowed values of VdbeOp.p4type
9349 #define P4_NOTUSED 0 /* The P4 parameter is not used */
9350 #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
9351 #define P4_STATIC (-2) /* Pointer to a static string */
9352 #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
9353 #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
9354 #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
9355 #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
9356 #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
9357 #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
9358 #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
9359 #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
9360 #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
9361 #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
9362 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
9363 #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
9364 #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
9366 /* Error message codes for OP_Halt */
9367 #define P5_ConstraintNotNull 1
9368 #define P5_ConstraintUnique 2
9369 #define P5_ConstraintCheck 3
9370 #define P5_ConstraintFK 4
9373 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
9374 ** number of columns of data returned by the statement.
9376 #define COLNAME_NAME 0
9377 #define COLNAME_DECLTYPE 1
9378 #define COLNAME_DATABASE 2
9379 #define COLNAME_TABLE 3
9380 #define COLNAME_COLUMN 4
9381 #ifdef SQLITE_ENABLE_COLUMN_METADATA
9382 # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
9383 #else
9384 # ifdef SQLITE_OMIT_DECLTYPE
9385 # define COLNAME_N 1 /* Store only the name */
9386 # else
9387 # define COLNAME_N 2 /* Store the name and decltype */
9388 # endif
9389 #endif
9392 ** The following macro converts a relative address in the p2 field
9393 ** of a VdbeOp structure into a negative number so that
9394 ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
9395 ** the macro again restores the address.
9397 #define ADDR(X) (-1-(X))
9400 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
9401 ** header file that defines a number for each opcode used by the VDBE.
9403 /************** Include opcodes.h in the middle of vdbe.h ********************/
9404 /************** Begin file opcodes.h *****************************************/
9405 /* Automatically generated. Do not edit */
9406 /* See the mkopcodeh.awk script for details */
9407 #define OP_Function 1 /* synopsis: r[P3]=func(r[P2@P5]) */
9408 #define OP_Savepoint 2
9409 #define OP_AutoCommit 3
9410 #define OP_Transaction 4
9411 #define OP_SorterNext 5
9412 #define OP_PrevIfOpen 6
9413 #define OP_NextIfOpen 7
9414 #define OP_Prev 8
9415 #define OP_Next 9
9416 #define OP_AggStep 10 /* synopsis: accum=r[P3] step(r[P2@P5]) */
9417 #define OP_Checkpoint 11
9418 #define OP_JournalMode 12
9419 #define OP_Vacuum 13
9420 #define OP_VFilter 14 /* synopsis: iplan=r[P3] zplan='P4' */
9421 #define OP_VUpdate 15 /* synopsis: data=r[P3@P2] */
9422 #define OP_Goto 16
9423 #define OP_Gosub 17
9424 #define OP_Return 18
9425 #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
9426 #define OP_InitCoroutine 20
9427 #define OP_EndCoroutine 21
9428 #define OP_Yield 22
9429 #define OP_HaltIfNull 23 /* synopsis: if r[P3]=null halt */
9430 #define OP_Halt 24
9431 #define OP_Integer 25 /* synopsis: r[P2]=P1 */
9432 #define OP_Int64 26 /* synopsis: r[P2]=P4 */
9433 #define OP_String 27 /* synopsis: r[P2]='P4' (len=P1) */
9434 #define OP_Null 28 /* synopsis: r[P2..P3]=NULL */
9435 #define OP_SoftNull 29 /* synopsis: r[P1]=NULL */
9436 #define OP_Blob 30 /* synopsis: r[P2]=P4 (len=P1) */
9437 #define OP_Variable 31 /* synopsis: r[P2]=parameter(P1,P4) */
9438 #define OP_Move 32 /* synopsis: r[P2@P3]=r[P1@P3] */
9439 #define OP_Copy 33 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
9440 #define OP_SCopy 34 /* synopsis: r[P2]=r[P1] */
9441 #define OP_ResultRow 35 /* synopsis: output=r[P1@P2] */
9442 #define OP_CollSeq 36
9443 #define OP_AddImm 37 /* synopsis: r[P1]=r[P1]+P2 */
9444 #define OP_MustBeInt 38
9445 #define OP_RealAffinity 39
9446 #define OP_Cast 40 /* synopsis: affinity(r[P1]) */
9447 #define OP_Permutation 41
9448 #define OP_Compare 42 /* synopsis: r[P1@P3] <-> r[P2@P3] */
9449 #define OP_Jump 43
9450 #define OP_Once 44
9451 #define OP_If 45
9452 #define OP_IfNot 46
9453 #define OP_Column 47 /* synopsis: r[P3]=PX */
9454 #define OP_Affinity 48 /* synopsis: affinity(r[P1@P2]) */
9455 #define OP_MakeRecord 49 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
9456 #define OP_Count 50 /* synopsis: r[P2]=count() */
9457 #define OP_ReadCookie 51
9458 #define OP_SetCookie 52
9459 #define OP_ReopenIdx 53 /* synopsis: root=P2 iDb=P3 */
9460 #define OP_OpenRead 54 /* synopsis: root=P2 iDb=P3 */
9461 #define OP_OpenWrite 55 /* synopsis: root=P2 iDb=P3 */
9462 #define OP_OpenAutoindex 56 /* synopsis: nColumn=P2 */
9463 #define OP_OpenEphemeral 57 /* synopsis: nColumn=P2 */
9464 #define OP_SorterOpen 58
9465 #define OP_SequenceTest 59 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
9466 #define OP_OpenPseudo 60 /* synopsis: P3 columns in r[P2] */
9467 #define OP_Close 61
9468 #define OP_SeekLT 62 /* synopsis: key=r[P3@P4] */
9469 #define OP_SeekLE 63 /* synopsis: key=r[P3@P4] */
9470 #define OP_SeekGE 64 /* synopsis: key=r[P3@P4] */
9471 #define OP_SeekGT 65 /* synopsis: key=r[P3@P4] */
9472 #define OP_Seek 66 /* synopsis: intkey=r[P2] */
9473 #define OP_NoConflict 67 /* synopsis: key=r[P3@P4] */
9474 #define OP_NotFound 68 /* synopsis: key=r[P3@P4] */
9475 #define OP_Found 69 /* synopsis: key=r[P3@P4] */
9476 #define OP_NotExists 70 /* synopsis: intkey=r[P3] */
9477 #define OP_Or 71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
9478 #define OP_And 72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
9479 #define OP_Sequence 73 /* synopsis: r[P2]=cursor[P1].ctr++ */
9480 #define OP_NewRowid 74 /* synopsis: r[P2]=rowid */
9481 #define OP_Insert 75 /* synopsis: intkey=r[P3] data=r[P2] */
9482 #define OP_IsNull 76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
9483 #define OP_NotNull 77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
9484 #define OP_Ne 78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
9485 #define OP_Eq 79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
9486 #define OP_Gt 80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
9487 #define OP_Le 81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
9488 #define OP_Lt 82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
9489 #define OP_Ge 83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
9490 #define OP_InsertInt 84 /* synopsis: intkey=P3 data=r[P2] */
9491 #define OP_BitAnd 85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
9492 #define OP_BitOr 86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
9493 #define OP_ShiftLeft 87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
9494 #define OP_ShiftRight 88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
9495 #define OP_Add 89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
9496 #define OP_Subtract 90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
9497 #define OP_Multiply 91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
9498 #define OP_Divide 92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
9499 #define OP_Remainder 93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
9500 #define OP_Concat 94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
9501 #define OP_Delete 95
9502 #define OP_BitNot 96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
9503 #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
9504 #define OP_ResetCount 98
9505 #define OP_SorterCompare 99 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
9506 #define OP_SorterData 100 /* synopsis: r[P2]=data */
9507 #define OP_RowKey 101 /* synopsis: r[P2]=key */
9508 #define OP_RowData 102 /* synopsis: r[P2]=data */
9509 #define OP_Rowid 103 /* synopsis: r[P2]=rowid */
9510 #define OP_NullRow 104
9511 #define OP_Last 105
9512 #define OP_SorterSort 106
9513 #define OP_Sort 107
9514 #define OP_Rewind 108
9515 #define OP_SorterInsert 109
9516 #define OP_IdxInsert 110 /* synopsis: key=r[P2] */
9517 #define OP_IdxDelete 111 /* synopsis: key=r[P2@P3] */
9518 #define OP_IdxRowid 112 /* synopsis: r[P2]=rowid */
9519 #define OP_IdxLE 113 /* synopsis: key=r[P3@P4] */
9520 #define OP_IdxGT 114 /* synopsis: key=r[P3@P4] */
9521 #define OP_IdxLT 115 /* synopsis: key=r[P3@P4] */
9522 #define OP_IdxGE 116 /* synopsis: key=r[P3@P4] */
9523 #define OP_Destroy 117
9524 #define OP_Clear 118
9525 #define OP_ResetSorter 119
9526 #define OP_CreateIndex 120 /* synopsis: r[P2]=root iDb=P1 */
9527 #define OP_CreateTable 121 /* synopsis: r[P2]=root iDb=P1 */
9528 #define OP_ParseSchema 122
9529 #define OP_LoadAnalysis 123
9530 #define OP_DropTable 124
9531 #define OP_DropIndex 125
9532 #define OP_DropTrigger 126
9533 #define OP_IntegrityCk 127
9534 #define OP_RowSetAdd 128 /* synopsis: rowset(P1)=r[P2] */
9535 #define OP_RowSetRead 129 /* synopsis: r[P3]=rowset(P1) */
9536 #define OP_RowSetTest 130 /* synopsis: if r[P3] in rowset(P1) goto P2 */
9537 #define OP_Program 131
9538 #define OP_Param 132
9539 #define OP_Real 133 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
9540 #define OP_FkCounter 134 /* synopsis: fkctr[P1]+=P2 */
9541 #define OP_FkIfZero 135 /* synopsis: if fkctr[P1]==0 goto P2 */
9542 #define OP_MemMax 136 /* synopsis: r[P1]=max(r[P1],r[P2]) */
9543 #define OP_IfPos 137 /* synopsis: if r[P1]>0 goto P2 */
9544 #define OP_IfNeg 138 /* synopsis: r[P1]+=P3, if r[P1]<0 goto P2 */
9545 #define OP_IfZero 139 /* synopsis: r[P1]+=P3, if r[P1]==0 goto P2 */
9546 #define OP_AggFinal 140 /* synopsis: accum=r[P1] N=P2 */
9547 #define OP_IncrVacuum 141
9548 #define OP_Expire 142
9549 #define OP_TableLock 143 /* synopsis: iDb=P1 root=P2 write=P3 */
9550 #define OP_VBegin 144
9551 #define OP_VCreate 145
9552 #define OP_VDestroy 146
9553 #define OP_VOpen 147
9554 #define OP_VColumn 148 /* synopsis: r[P3]=vcolumn(P2) */
9555 #define OP_VNext 149
9556 #define OP_VRename 150
9557 #define OP_Pagecount 151
9558 #define OP_MaxPgcnt 152
9559 #define OP_Init 153 /* synopsis: Start at P2 */
9560 #define OP_Noop 154
9561 #define OP_Explain 155
9564 /* Properties such as "out2" or "jump" that are specified in
9565 ** comments following the "case" for each opcode in the vdbe.c
9566 ** are encoded into bitvectors as follows:
9568 #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
9569 #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
9570 #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
9571 #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
9572 #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
9573 #define OPFLG_OUT2 0x0020 /* out2: P2 is an output */
9574 #define OPFLG_OUT3 0x0040 /* out3: P3 is an output */
9575 #define OPFLG_INITIALIZER {\
9576 /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\
9577 /* 8 */ 0x01, 0x01, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00,\
9578 /* 16 */ 0x01, 0x01, 0x04, 0x24, 0x01, 0x04, 0x05, 0x10,\
9579 /* 24 */ 0x00, 0x02, 0x02, 0x02, 0x02, 0x00, 0x02, 0x02,\
9580 /* 32 */ 0x00, 0x00, 0x20, 0x00, 0x00, 0x04, 0x05, 0x04,\
9581 /* 40 */ 0x04, 0x00, 0x00, 0x01, 0x01, 0x05, 0x05, 0x00,\
9582 /* 48 */ 0x00, 0x00, 0x02, 0x02, 0x10, 0x00, 0x00, 0x00,\
9583 /* 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
9584 /* 64 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x4c,\
9585 /* 72 */ 0x4c, 0x02, 0x02, 0x00, 0x05, 0x05, 0x15, 0x15,\
9586 /* 80 */ 0x15, 0x15, 0x15, 0x15, 0x00, 0x4c, 0x4c, 0x4c,\
9587 /* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x00,\
9588 /* 96 */ 0x24, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,\
9589 /* 104 */ 0x00, 0x01, 0x01, 0x01, 0x01, 0x08, 0x08, 0x00,\
9590 /* 112 */ 0x02, 0x01, 0x01, 0x01, 0x01, 0x02, 0x00, 0x00,\
9591 /* 120 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
9592 /* 128 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x02, 0x00, 0x01,\
9593 /* 136 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x01, 0x00, 0x00,\
9594 /* 144 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02,\
9595 /* 152 */ 0x02, 0x01, 0x00, 0x00,}
9597 /************** End of opcodes.h *********************************************/
9598 /************** Continuing where we left off in vdbe.h ***********************/
9601 ** Prototypes for the VDBE interface. See comments on the implementation
9602 ** for a description of what each of these routines does.
9604 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
9605 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
9606 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
9607 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
9608 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
9609 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
9610 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
9611 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
9612 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
9613 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
9614 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
9615 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
9616 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
9617 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
9618 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
9619 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
9620 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
9621 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
9622 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
9623 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
9624 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
9625 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
9626 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
9627 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
9628 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
9629 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
9630 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
9631 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
9632 #ifdef SQLITE_DEBUG
9633 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
9634 #endif
9635 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
9636 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
9637 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
9638 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
9639 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
9640 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
9641 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
9642 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
9643 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
9644 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
9645 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
9646 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
9647 #ifndef SQLITE_OMIT_TRACE
9648 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
9649 #endif
9650 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
9652 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
9653 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
9654 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
9656 typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
9657 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
9659 #ifndef SQLITE_OMIT_TRIGGER
9660 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
9661 #endif
9663 /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
9664 ** each VDBE opcode.
9666 ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
9667 ** comments in VDBE programs that show key decision points in the code
9668 ** generator.
9670 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
9671 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
9672 # define VdbeComment(X) sqlite3VdbeComment X
9673 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
9674 # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
9675 # ifdef SQLITE_ENABLE_MODULE_COMMENTS
9676 # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
9677 # else
9678 # define VdbeModuleComment(X)
9679 # endif
9680 #else
9681 # define VdbeComment(X)
9682 # define VdbeNoopComment(X)
9683 # define VdbeModuleComment(X)
9684 #endif
9687 ** The VdbeCoverage macros are used to set a coverage testing point
9688 ** for VDBE branch instructions. The coverage testing points are line
9689 ** numbers in the sqlite3.c source file. VDBE branch coverage testing
9690 ** only works with an amalagmation build. That's ok since a VDBE branch
9691 ** coverage build designed for testing the test suite only. No application
9692 ** should ever ship with VDBE branch coverage measuring turned on.
9694 ** VdbeCoverage(v) // Mark the previously coded instruction
9695 ** // as a branch
9697 ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
9699 ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
9701 ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
9703 ** Every VDBE branch operation must be tagged with one of the macros above.
9704 ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
9705 ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
9706 ** routine in vdbe.c, alerting the developer to the missed tag.
9708 #ifdef SQLITE_VDBE_COVERAGE
9709 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
9710 # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
9711 # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
9712 # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
9713 # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
9714 # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
9715 #else
9716 # define VdbeCoverage(v)
9717 # define VdbeCoverageIf(v,x)
9718 # define VdbeCoverageAlwaysTaken(v)
9719 # define VdbeCoverageNeverTaken(v)
9720 # define VDBE_OFFSET_LINENO(x) 0
9721 #endif
9723 #endif
9725 /************** End of vdbe.h ************************************************/
9726 /************** Continuing where we left off in sqliteInt.h ******************/
9727 /************** Include pager.h in the middle of sqliteInt.h *****************/
9728 /************** Begin file pager.h *******************************************/
9730 ** 2001 September 15
9732 ** The author disclaims copyright to this source code. In place of
9733 ** a legal notice, here is a blessing:
9735 ** May you do good and not evil.
9736 ** May you find forgiveness for yourself and forgive others.
9737 ** May you share freely, never taking more than you give.
9739 *************************************************************************
9740 ** This header file defines the interface that the sqlite page cache
9741 ** subsystem. The page cache subsystem reads and writes a file a page
9742 ** at a time and provides a journal for rollback.
9745 #ifndef _PAGER_H_
9746 #define _PAGER_H_
9749 ** Default maximum size for persistent journal files. A negative
9750 ** value means no limit. This value may be overridden using the
9751 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
9753 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
9754 #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
9755 #endif
9758 ** The type used to represent a page number. The first page in a file
9759 ** is called page 1. 0 is used to represent "not a page".
9761 typedef u32 Pgno;
9764 ** Each open file is managed by a separate instance of the "Pager" structure.
9766 typedef struct Pager Pager;
9769 ** Handle type for pages.
9771 typedef struct PgHdr DbPage;
9774 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
9775 ** reserved for working around a windows/posix incompatibility). It is
9776 ** used in the journal to signify that the remainder of the journal file
9777 ** is devoted to storing a master journal name - there are no more pages to
9778 ** roll back. See comments for function writeMasterJournal() in pager.c
9779 ** for details.
9781 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
9784 ** Allowed values for the flags parameter to sqlite3PagerOpen().
9786 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
9788 #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
9789 #define PAGER_MEMORY 0x0002 /* In-memory database */
9792 ** Valid values for the second argument to sqlite3PagerLockingMode().
9794 #define PAGER_LOCKINGMODE_QUERY -1
9795 #define PAGER_LOCKINGMODE_NORMAL 0
9796 #define PAGER_LOCKINGMODE_EXCLUSIVE 1
9799 ** Numeric constants that encode the journalmode.
9801 #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
9802 #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
9803 #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
9804 #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
9805 #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
9806 #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
9807 #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
9810 ** Flags that make up the mask passed to sqlite3PagerAcquire().
9812 #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
9813 #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
9816 ** Flags for sqlite3PagerSetFlags()
9818 #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
9819 #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
9820 #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
9821 #define PAGER_SYNCHRONOUS_MASK 0x03 /* Mask for three values above */
9822 #define PAGER_FULLFSYNC 0x04 /* PRAGMA fullfsync=ON */
9823 #define PAGER_CKPT_FULLFSYNC 0x08 /* PRAGMA checkpoint_fullfsync=ON */
9824 #define PAGER_CACHESPILL 0x10 /* PRAGMA cache_spill=ON */
9825 #define PAGER_FLAGS_MASK 0x1c /* All above except SYNCHRONOUS */
9828 ** The remainder of this file contains the declarations of the functions
9829 ** that make up the Pager sub-system API. See source code comments for
9830 ** a detailed description of each routine.
9833 /* Open and close a Pager connection. */
9834 SQLITE_PRIVATE int sqlite3PagerOpen(
9835 sqlite3_vfs*,
9836 Pager **ppPager,
9837 const char*,
9838 int,
9839 int,
9840 int,
9841 void(*)(DbPage*)
9843 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
9844 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
9846 /* Functions used to configure a Pager object. */
9847 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
9848 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
9849 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
9850 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
9851 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
9852 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
9853 SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
9854 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
9855 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
9856 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
9857 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
9858 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
9859 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
9861 /* Functions used to obtain and release page references. */
9862 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
9863 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
9864 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
9865 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
9866 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
9867 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
9869 /* Operations on page references. */
9870 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
9871 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
9872 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
9873 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
9874 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
9875 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
9877 /* Functions used to manage pager transactions and savepoints. */
9878 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
9879 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
9880 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
9881 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
9882 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
9883 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
9884 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
9885 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
9886 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
9887 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
9889 #ifndef SQLITE_OMIT_WAL
9890 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
9891 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
9892 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
9893 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
9894 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
9895 #endif
9897 #ifdef SQLITE_ENABLE_ZIPVFS
9898 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
9899 #endif
9901 /* Functions used to query pager state and configuration. */
9902 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
9903 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
9904 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
9905 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
9906 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
9907 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
9908 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
9909 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
9910 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
9911 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
9912 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
9913 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
9914 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
9916 /* Functions used to truncate the database file. */
9917 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
9919 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
9920 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
9921 #endif
9923 /* Functions to support testing and debugging. */
9924 #if !defined(NDEBUG) || defined(SQLITE_TEST)
9925 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
9926 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
9927 #endif
9928 #ifdef SQLITE_TEST
9929 SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
9930 SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
9931 void disable_simulated_io_errors(void);
9932 void enable_simulated_io_errors(void);
9933 #else
9934 # define disable_simulated_io_errors()
9935 # define enable_simulated_io_errors()
9936 #endif
9938 #endif /* _PAGER_H_ */
9940 /************** End of pager.h ***********************************************/
9941 /************** Continuing where we left off in sqliteInt.h ******************/
9942 /************** Include pcache.h in the middle of sqliteInt.h ****************/
9943 /************** Begin file pcache.h ******************************************/
9945 ** 2008 August 05
9947 ** The author disclaims copyright to this source code. In place of
9948 ** a legal notice, here is a blessing:
9950 ** May you do good and not evil.
9951 ** May you find forgiveness for yourself and forgive others.
9952 ** May you share freely, never taking more than you give.
9954 *************************************************************************
9955 ** This header file defines the interface that the sqlite page cache
9956 ** subsystem.
9959 #ifndef _PCACHE_H_
9961 typedef struct PgHdr PgHdr;
9962 typedef struct PCache PCache;
9965 ** Every page in the cache is controlled by an instance of the following
9966 ** structure.
9968 struct PgHdr {
9969 sqlite3_pcache_page *pPage; /* Pcache object page handle */
9970 void *pData; /* Page data */
9971 void *pExtra; /* Extra content */
9972 PgHdr *pDirty; /* Transient list of dirty pages */
9973 Pager *pPager; /* The pager this page is part of */
9974 Pgno pgno; /* Page number for this page */
9975 #ifdef SQLITE_CHECK_PAGES
9976 u32 pageHash; /* Hash of page content */
9977 #endif
9978 u16 flags; /* PGHDR flags defined below */
9980 /**********************************************************************
9981 ** Elements above are public. All that follows is private to pcache.c
9982 ** and should not be accessed by other modules.
9984 i16 nRef; /* Number of users of this page */
9985 PCache *pCache; /* Cache that owns this page */
9987 PgHdr *pDirtyNext; /* Next element in list of dirty pages */
9988 PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
9991 /* Bit values for PgHdr.flags */
9992 #define PGHDR_DIRTY 0x002 /* Page has changed */
9993 #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
9994 ** writing this page to the database */
9995 #define PGHDR_NEED_READ 0x008 /* Content is unread */
9996 #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
9997 #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
9999 #define PGHDR_MMAP 0x040 /* This is an mmap page object */
10001 /* Initialize and shutdown the page cache subsystem */
10002 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
10003 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
10005 /* Page cache buffer management:
10006 ** These routines implement SQLITE_CONFIG_PAGECACHE.
10008 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
10010 /* Create a new pager cache.
10011 ** Under memory stress, invoke xStress to try to make pages clean.
10012 ** Only clean and unpinned pages can be reclaimed.
10014 SQLITE_PRIVATE int sqlite3PcacheOpen(
10015 int szPage, /* Size of every page */
10016 int szExtra, /* Extra space associated with each page */
10017 int bPurgeable, /* True if pages are on backing store */
10018 int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
10019 void *pStress, /* Argument to xStress */
10020 PCache *pToInit /* Preallocated space for the PCache */
10023 /* Modify the page-size after the cache has been created. */
10024 SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
10026 /* Return the size in bytes of a PCache object. Used to preallocate
10027 ** storage space.
10029 SQLITE_PRIVATE int sqlite3PcacheSize(void);
10031 /* One release per successful fetch. Page is pinned until released.
10032 ** Reference counted.
10034 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
10035 SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
10036 SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
10037 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
10039 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
10040 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
10041 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
10042 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
10044 /* Change a page number. Used by incr-vacuum. */
10045 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
10047 /* Remove all pages with pgno>x. Reset the cache if x==0 */
10048 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
10050 /* Get a list of all dirty pages in the cache, sorted by page number */
10051 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
10053 /* Reset and close the cache object */
10054 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
10056 /* Clear flags from pages of the page cache */
10057 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
10059 /* Discard the contents of the cache */
10060 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
10062 /* Return the total number of outstanding page references */
10063 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
10065 /* Increment the reference count of an existing page */
10066 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
10068 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
10070 /* Return the total number of pages stored in the cache */
10071 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
10073 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
10074 /* Iterate through all dirty pages currently stored in the cache. This
10075 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
10076 ** library is built.
10078 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
10079 #endif
10081 /* Set and get the suggested cache-size for the specified pager-cache.
10083 ** If no global maximum is configured, then the system attempts to limit
10084 ** the total number of pages cached by purgeable pager-caches to the sum
10085 ** of the suggested cache-sizes.
10087 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
10088 #ifdef SQLITE_TEST
10089 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
10090 #endif
10092 /* Free up as much memory as possible from the page cache */
10093 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
10095 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
10096 /* Try to return memory used by the pcache module to the main memory heap */
10097 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
10098 #endif
10100 #ifdef SQLITE_TEST
10101 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
10102 #endif
10104 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
10106 #endif /* _PCACHE_H_ */
10108 /************** End of pcache.h **********************************************/
10109 /************** Continuing where we left off in sqliteInt.h ******************/
10111 /************** Include os.h in the middle of sqliteInt.h ********************/
10112 /************** Begin file os.h **********************************************/
10114 ** 2001 September 16
10116 ** The author disclaims copyright to this source code. In place of
10117 ** a legal notice, here is a blessing:
10119 ** May you do good and not evil.
10120 ** May you find forgiveness for yourself and forgive others.
10121 ** May you share freely, never taking more than you give.
10123 ******************************************************************************
10125 ** This header file (together with is companion C source-code file
10126 ** "os.c") attempt to abstract the underlying operating system so that
10127 ** the SQLite library will work on both POSIX and windows systems.
10129 ** This header file is #include-ed by sqliteInt.h and thus ends up
10130 ** being included by every source file.
10132 #ifndef _SQLITE_OS_H_
10133 #define _SQLITE_OS_H_
10136 ** Attempt to automatically detect the operating system and setup the
10137 ** necessary pre-processor macros for it.
10139 /************** Include os_setup.h in the middle of os.h *********************/
10140 /************** Begin file os_setup.h ****************************************/
10142 ** 2013 November 25
10144 ** The author disclaims copyright to this source code. In place of
10145 ** a legal notice, here is a blessing:
10147 ** May you do good and not evil.
10148 ** May you find forgiveness for yourself and forgive others.
10149 ** May you share freely, never taking more than you give.
10151 ******************************************************************************
10153 ** This file contains pre-processor directives related to operating system
10154 ** detection and/or setup.
10156 #ifndef _OS_SETUP_H_
10157 #define _OS_SETUP_H_
10160 ** Figure out if we are dealing with Unix, Windows, or some other operating
10161 ** system.
10163 ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
10164 ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
10165 ** the three will be 1. The other two will be 0.
10167 #if defined(SQLITE_OS_OTHER)
10168 # if SQLITE_OS_OTHER==1
10169 # undef SQLITE_OS_UNIX
10170 # define SQLITE_OS_UNIX 0
10171 # undef SQLITE_OS_WIN
10172 # define SQLITE_OS_WIN 0
10173 # else
10174 # undef SQLITE_OS_OTHER
10175 # endif
10176 #endif
10177 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
10178 # define SQLITE_OS_OTHER 0
10179 # ifndef SQLITE_OS_WIN
10180 # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
10181 defined(__MINGW32__) || defined(__BORLANDC__)
10182 # define SQLITE_OS_WIN 1
10183 # define SQLITE_OS_UNIX 0
10184 # else
10185 # define SQLITE_OS_WIN 0
10186 # define SQLITE_OS_UNIX 1
10187 # endif
10188 # else
10189 # define SQLITE_OS_UNIX 0
10190 # endif
10191 #else
10192 # ifndef SQLITE_OS_WIN
10193 # define SQLITE_OS_WIN 0
10194 # endif
10195 #endif
10197 #endif /* _OS_SETUP_H_ */
10199 /************** End of os_setup.h ********************************************/
10200 /************** Continuing where we left off in os.h *************************/
10202 /* If the SET_FULLSYNC macro is not defined above, then make it
10203 ** a no-op
10205 #ifndef SET_FULLSYNC
10206 # define SET_FULLSYNC(x,y)
10207 #endif
10210 ** The default size of a disk sector
10212 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
10213 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
10214 #endif
10217 ** Temporary files are named starting with this prefix followed by 16 random
10218 ** alphanumeric characters, and no file extension. They are stored in the
10219 ** OS's standard temporary file directory, and are deleted prior to exit.
10220 ** If sqlite is being embedded in another program, you may wish to change the
10221 ** prefix to reflect your program's name, so that if your program exits
10222 ** prematurely, old temporary files can be easily identified. This can be done
10223 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
10225 ** 2006-10-31: The default prefix used to be "sqlite_". But then
10226 ** Mcafee started using SQLite in their anti-virus product and it
10227 ** started putting files with the "sqlite" name in the c:/temp folder.
10228 ** This annoyed many windows users. Those users would then do a
10229 ** Google search for "sqlite", find the telephone numbers of the
10230 ** developers and call to wake them up at night and complain.
10231 ** For this reason, the default name prefix is changed to be "sqlite"
10232 ** spelled backwards. So the temp files are still identified, but
10233 ** anybody smart enough to figure out the code is also likely smart
10234 ** enough to know that calling the developer will not help get rid
10235 ** of the file.
10237 #ifndef SQLITE_TEMP_FILE_PREFIX
10238 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
10239 #endif
10242 ** The following values may be passed as the second argument to
10243 ** sqlite3OsLock(). The various locks exhibit the following semantics:
10245 ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
10246 ** RESERVED: A single process may hold a RESERVED lock on a file at
10247 ** any time. Other processes may hold and obtain new SHARED locks.
10248 ** PENDING: A single process may hold a PENDING lock on a file at
10249 ** any one time. Existing SHARED locks may persist, but no new
10250 ** SHARED locks may be obtained by other processes.
10251 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
10253 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
10254 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
10255 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
10256 ** sqlite3OsLock().
10258 #define NO_LOCK 0
10259 #define SHARED_LOCK 1
10260 #define RESERVED_LOCK 2
10261 #define PENDING_LOCK 3
10262 #define EXCLUSIVE_LOCK 4
10265 ** File Locking Notes: (Mostly about windows but also some info for Unix)
10267 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
10268 ** those functions are not available. So we use only LockFile() and
10269 ** UnlockFile().
10271 ** LockFile() prevents not just writing but also reading by other processes.
10272 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
10273 ** byte out of a specific range of bytes. The lock byte is obtained at
10274 ** random so two separate readers can probably access the file at the
10275 ** same time, unless they are unlucky and choose the same lock byte.
10276 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
10277 ** There can only be one writer. A RESERVED_LOCK is obtained by locking
10278 ** a single byte of the file that is designated as the reserved lock byte.
10279 ** A PENDING_LOCK is obtained by locking a designated byte different from
10280 ** the RESERVED_LOCK byte.
10282 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
10283 ** which means we can use reader/writer locks. When reader/writer locks
10284 ** are used, the lock is placed on the same range of bytes that is used
10285 ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
10286 ** will support two or more Win95 readers or two or more WinNT readers.
10287 ** But a single Win95 reader will lock out all WinNT readers and a single
10288 ** WinNT reader will lock out all other Win95 readers.
10290 ** The following #defines specify the range of bytes used for locking.
10291 ** SHARED_SIZE is the number of bytes available in the pool from which
10292 ** a random byte is selected for a shared lock. The pool of bytes for
10293 ** shared locks begins at SHARED_FIRST.
10295 ** The same locking strategy and
10296 ** byte ranges are used for Unix. This leaves open the possibility of having
10297 ** clients on win95, winNT, and unix all talking to the same shared file
10298 ** and all locking correctly. To do so would require that samba (or whatever
10299 ** tool is being used for file sharing) implements locks correctly between
10300 ** windows and unix. I'm guessing that isn't likely to happen, but by
10301 ** using the same locking range we are at least open to the possibility.
10303 ** Locking in windows is manditory. For this reason, we cannot store
10304 ** actual data in the bytes used for locking. The pager never allocates
10305 ** the pages involved in locking therefore. SHARED_SIZE is selected so
10306 ** that all locks will fit on a single page even at the minimum page size.
10307 ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
10308 ** is set high so that we don't have to allocate an unused page except
10309 ** for very large databases. But one should test the page skipping logic
10310 ** by setting PENDING_BYTE low and running the entire regression suite.
10312 ** Changing the value of PENDING_BYTE results in a subtly incompatible
10313 ** file format. Depending on how it is changed, you might not notice
10314 ** the incompatibility right away, even running a full regression test.
10315 ** The default location of PENDING_BYTE is the first byte past the
10316 ** 1GB boundary.
10319 #ifdef SQLITE_OMIT_WSD
10320 # define PENDING_BYTE (0x40000000)
10321 #else
10322 # define PENDING_BYTE sqlite3PendingByte
10323 #endif
10324 #define RESERVED_BYTE (PENDING_BYTE+1)
10325 #define SHARED_FIRST (PENDING_BYTE+2)
10326 #define SHARED_SIZE 510
10329 ** Wrapper around OS specific sqlite3_os_init() function.
10331 SQLITE_PRIVATE int sqlite3OsInit(void);
10334 ** Functions for accessing sqlite3_file methods
10336 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
10337 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
10338 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
10339 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
10340 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
10341 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
10342 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
10343 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
10344 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
10345 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
10346 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
10347 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
10348 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
10349 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
10350 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
10351 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
10352 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
10353 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
10354 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
10355 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
10359 ** Functions for accessing sqlite3_vfs methods
10361 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
10362 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
10363 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
10364 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
10365 #ifndef SQLITE_OMIT_LOAD_EXTENSION
10366 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
10367 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
10368 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
10369 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
10370 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
10371 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
10372 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
10373 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
10376 ** Convenience functions for opening and closing files using
10377 ** sqlite3_malloc() to obtain space for the file-handle structure.
10379 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
10380 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
10382 #endif /* _SQLITE_OS_H_ */
10384 /************** End of os.h **************************************************/
10385 /************** Continuing where we left off in sqliteInt.h ******************/
10386 /************** Include mutex.h in the middle of sqliteInt.h *****************/
10387 /************** Begin file mutex.h *******************************************/
10389 ** 2007 August 28
10391 ** The author disclaims copyright to this source code. In place of
10392 ** a legal notice, here is a blessing:
10394 ** May you do good and not evil.
10395 ** May you find forgiveness for yourself and forgive others.
10396 ** May you share freely, never taking more than you give.
10398 *************************************************************************
10400 ** This file contains the common header for all mutex implementations.
10401 ** The sqliteInt.h header #includes this file so that it is available
10402 ** to all source files. We break it out in an effort to keep the code
10403 ** better organized.
10405 ** NOTE: source files should *not* #include this header file directly.
10406 ** Source files should #include the sqliteInt.h file and let that file
10407 ** include this one indirectly.
10412 ** Figure out what version of the code to use. The choices are
10414 ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
10415 ** mutexes implementation cannot be overridden
10416 ** at start-time.
10418 ** SQLITE_MUTEX_NOOP For single-threaded applications. No
10419 ** mutual exclusion is provided. But this
10420 ** implementation can be overridden at
10421 ** start-time.
10423 ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
10425 ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
10427 #if !SQLITE_THREADSAFE
10428 # define SQLITE_MUTEX_OMIT
10429 #endif
10430 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
10431 # if SQLITE_OS_UNIX
10432 # define SQLITE_MUTEX_PTHREADS
10433 # elif SQLITE_OS_WIN
10434 # define SQLITE_MUTEX_W32
10435 # else
10436 # define SQLITE_MUTEX_NOOP
10437 # endif
10438 #endif
10440 #ifdef SQLITE_MUTEX_OMIT
10442 ** If this is a no-op implementation, implement everything as macros.
10444 #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
10445 #define sqlite3_mutex_free(X)
10446 #define sqlite3_mutex_enter(X)
10447 #define sqlite3_mutex_try(X) SQLITE_OK
10448 #define sqlite3_mutex_leave(X)
10449 #define sqlite3_mutex_held(X) ((void)(X),1)
10450 #define sqlite3_mutex_notheld(X) ((void)(X),1)
10451 #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
10452 #define sqlite3MutexInit() SQLITE_OK
10453 #define sqlite3MutexEnd()
10454 #define MUTEX_LOGIC(X)
10455 #else
10456 #define MUTEX_LOGIC(X) X
10457 #endif /* defined(SQLITE_MUTEX_OMIT) */
10459 /************** End of mutex.h ***********************************************/
10460 /************** Continuing where we left off in sqliteInt.h ******************/
10464 ** Each database file to be accessed by the system is an instance
10465 ** of the following structure. There are normally two of these structures
10466 ** in the sqlite.aDb[] array. aDb[0] is the main database file and
10467 ** aDb[1] is the database file used to hold temporary tables. Additional
10468 ** databases may be attached.
10470 struct Db {
10471 char *zName; /* Name of this database */
10472 Btree *pBt; /* The B*Tree structure for this database file */
10473 u8 safety_level; /* How aggressive at syncing data to disk */
10474 Schema *pSchema; /* Pointer to database schema (possibly shared) */
10478 ** An instance of the following structure stores a database schema.
10480 ** Most Schema objects are associated with a Btree. The exception is
10481 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
10482 ** In shared cache mode, a single Schema object can be shared by multiple
10483 ** Btrees that refer to the same underlying BtShared object.
10485 ** Schema objects are automatically deallocated when the last Btree that
10486 ** references them is destroyed. The TEMP Schema is manually freed by
10487 ** sqlite3_close().
10489 ** A thread must be holding a mutex on the corresponding Btree in order
10490 ** to access Schema content. This implies that the thread must also be
10491 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
10492 ** For a TEMP Schema, only the connection mutex is required.
10494 struct Schema {
10495 int schema_cookie; /* Database schema version number for this file */
10496 int iGeneration; /* Generation counter. Incremented with each change */
10497 Hash tblHash; /* All tables indexed by name */
10498 Hash idxHash; /* All (named) indices indexed by name */
10499 Hash trigHash; /* All triggers indexed by name */
10500 Hash fkeyHash; /* All foreign keys by referenced table name */
10501 Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
10502 u8 file_format; /* Schema format version for this file */
10503 u8 enc; /* Text encoding used by this database */
10504 u16 schemaFlags; /* Flags associated with this schema */
10505 int cache_size; /* Number of pages to use in the cache */
10509 ** These macros can be used to test, set, or clear bits in the
10510 ** Db.pSchema->flags field.
10512 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
10513 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
10514 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
10515 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
10518 ** Allowed values for the DB.pSchema->flags field.
10520 ** The DB_SchemaLoaded flag is set after the database schema has been
10521 ** read into internal hash tables.
10523 ** DB_UnresetViews means that one or more views have column names that
10524 ** have been filled out. If the schema changes, these column names might
10525 ** changes and so the view will need to be reset.
10527 #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
10528 #define DB_UnresetViews 0x0002 /* Some views have defined column names */
10529 #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
10532 ** The number of different kinds of things that can be limited
10533 ** using the sqlite3_limit() interface.
10535 #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
10538 ** Lookaside malloc is a set of fixed-size buffers that can be used
10539 ** to satisfy small transient memory allocation requests for objects
10540 ** associated with a particular database connection. The use of
10541 ** lookaside malloc provides a significant performance enhancement
10542 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
10543 ** SQL statements.
10545 ** The Lookaside structure holds configuration information about the
10546 ** lookaside malloc subsystem. Each available memory allocation in
10547 ** the lookaside subsystem is stored on a linked list of LookasideSlot
10548 ** objects.
10550 ** Lookaside allocations are only allowed for objects that are associated
10551 ** with a particular database connection. Hence, schema information cannot
10552 ** be stored in lookaside because in shared cache mode the schema information
10553 ** is shared by multiple database connections. Therefore, while parsing
10554 ** schema information, the Lookaside.bEnabled flag is cleared so that
10555 ** lookaside allocations are not used to construct the schema objects.
10557 struct Lookaside {
10558 u16 sz; /* Size of each buffer in bytes */
10559 u8 bEnabled; /* False to disable new lookaside allocations */
10560 u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
10561 int nOut; /* Number of buffers currently checked out */
10562 int mxOut; /* Highwater mark for nOut */
10563 int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
10564 LookasideSlot *pFree; /* List of available buffers */
10565 void *pStart; /* First byte of available memory space */
10566 void *pEnd; /* First byte past end of available space */
10568 struct LookasideSlot {
10569 LookasideSlot *pNext; /* Next buffer in the list of free buffers */
10573 ** A hash table for function definitions.
10575 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
10576 ** Collisions are on the FuncDef.pHash chain.
10578 struct FuncDefHash {
10579 FuncDef *a[23]; /* Hash table for functions */
10582 #ifdef SQLITE_USER_AUTHENTICATION
10584 ** Information held in the "sqlite3" database connection object and used
10585 ** to manage user authentication.
10587 typedef struct sqlite3_userauth sqlite3_userauth;
10588 struct sqlite3_userauth {
10589 u8 authLevel; /* Current authentication level */
10590 int nAuthPW; /* Size of the zAuthPW in bytes */
10591 char *zAuthPW; /* Password used to authenticate */
10592 char *zAuthUser; /* User name used to authenticate */
10595 /* Allowed values for sqlite3_userauth.authLevel */
10596 #define UAUTH_Unknown 0 /* Authentication not yet checked */
10597 #define UAUTH_Fail 1 /* User authentication failed */
10598 #define UAUTH_User 2 /* Authenticated as a normal user */
10599 #define UAUTH_Admin 3 /* Authenticated as an administrator */
10601 /* Functions used only by user authorization logic */
10602 SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
10603 SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
10604 SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
10605 SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
10607 #endif /* SQLITE_USER_AUTHENTICATION */
10610 ** typedef for the authorization callback function.
10612 #ifdef SQLITE_USER_AUTHENTICATION
10613 typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
10614 const char*, const char*);
10615 #else
10616 typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
10617 const char*);
10618 #endif
10622 ** Each database connection is an instance of the following structure.
10624 struct sqlite3 {
10625 sqlite3_vfs *pVfs; /* OS Interface */
10626 struct Vdbe *pVdbe; /* List of active virtual machines */
10627 CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
10628 sqlite3_mutex *mutex; /* Connection mutex */
10629 Db *aDb; /* All backends */
10630 int nDb; /* Number of backends currently in use */
10631 int flags; /* Miscellaneous flags. See below */
10632 i64 lastRowid; /* ROWID of most recent insert (see above) */
10633 i64 szMmap; /* Default mmap_size setting */
10634 unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
10635 int errCode; /* Most recent error code (SQLITE_*) */
10636 int errMask; /* & result codes with this before returning */
10637 u16 dbOptFlags; /* Flags to enable/disable optimizations */
10638 u8 autoCommit; /* The auto-commit flag. */
10639 u8 temp_store; /* 1: file 2: memory 0: default */
10640 u8 mallocFailed; /* True if we have seen a malloc failure */
10641 u8 dfltLockMode; /* Default locking-mode for attached dbs */
10642 signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
10643 u8 suppressErr; /* Do not issue error messages if true */
10644 u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
10645 u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
10646 int nextPagesize; /* Pagesize after VACUUM if >0 */
10647 u32 magic; /* Magic number for detect library misuse */
10648 int nChange; /* Value returned by sqlite3_changes() */
10649 int nTotalChange; /* Value returned by sqlite3_total_changes() */
10650 int aLimit[SQLITE_N_LIMIT]; /* Limits */
10651 int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
10652 struct sqlite3InitInfo { /* Information used during initialization */
10653 int newTnum; /* Rootpage of table being initialized */
10654 u8 iDb; /* Which db file is being initialized */
10655 u8 busy; /* TRUE if currently initializing */
10656 u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
10657 } init;
10658 int nVdbeActive; /* Number of VDBEs currently running */
10659 int nVdbeRead; /* Number of active VDBEs that read or write */
10660 int nVdbeWrite; /* Number of active VDBEs that read and write */
10661 int nVdbeExec; /* Number of nested calls to VdbeExec() */
10662 int nExtension; /* Number of loaded extensions */
10663 void **aExtension; /* Array of shared library handles */
10664 void (*xTrace)(void*,const char*); /* Trace function */
10665 void *pTraceArg; /* Argument to the trace function */
10666 void (*xProfile)(void*,const char*,u64); /* Profiling function */
10667 void *pProfileArg; /* Argument to profile function */
10668 void *pCommitArg; /* Argument to xCommitCallback() */
10669 int (*xCommitCallback)(void*); /* Invoked at every commit. */
10670 void *pRollbackArg; /* Argument to xRollbackCallback() */
10671 void (*xRollbackCallback)(void*); /* Invoked at every commit. */
10672 void *pUpdateArg;
10673 void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
10674 #ifndef SQLITE_OMIT_WAL
10675 int (*xWalCallback)(void *, sqlite3 *, const char *, int);
10676 void *pWalArg;
10677 #endif
10678 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
10679 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
10680 void *pCollNeededArg;
10681 sqlite3_value *pErr; /* Most recent error message */
10682 union {
10683 volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
10684 double notUsed1; /* Spacer */
10685 } u1;
10686 Lookaside lookaside; /* Lookaside malloc configuration */
10687 #ifndef SQLITE_OMIT_AUTHORIZATION
10688 sqlite3_xauth xAuth; /* Access authorization function */
10689 void *pAuthArg; /* 1st argument to the access auth function */
10690 #endif
10691 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
10692 int (*xProgress)(void *); /* The progress callback */
10693 void *pProgressArg; /* Argument to the progress callback */
10694 unsigned nProgressOps; /* Number of opcodes for progress callback */
10695 #endif
10696 #ifndef SQLITE_OMIT_VIRTUALTABLE
10697 int nVTrans; /* Allocated size of aVTrans */
10698 Hash aModule; /* populated by sqlite3_create_module() */
10699 VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
10700 VTable **aVTrans; /* Virtual tables with open transactions */
10701 VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
10702 #endif
10703 FuncDefHash aFunc; /* Hash table of connection functions */
10704 Hash aCollSeq; /* All collating sequences */
10705 BusyHandler busyHandler; /* Busy callback */
10706 Db aDbStatic[2]; /* Static space for the 2 default backends */
10707 Savepoint *pSavepoint; /* List of active savepoints */
10708 int busyTimeout; /* Busy handler timeout, in msec */
10709 int nSavepoint; /* Number of non-transaction savepoints */
10710 int nStatement; /* Number of nested statement-transactions */
10711 i64 nDeferredCons; /* Net deferred constraints this transaction. */
10712 i64 nDeferredImmCons; /* Net deferred immediate constraints */
10713 int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
10714 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10715 /* The following variables are all protected by the STATIC_MASTER
10716 ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
10718 ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
10719 ** unlock so that it can proceed.
10721 ** When X.pBlockingConnection==Y, that means that something that X tried
10722 ** tried to do recently failed with an SQLITE_LOCKED error due to locks
10723 ** held by Y.
10725 sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
10726 sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
10727 void *pUnlockArg; /* Argument to xUnlockNotify */
10728 void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
10729 sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
10730 #endif
10731 #ifdef SQLITE_USER_AUTHENTICATION
10732 sqlite3_userauth auth; /* User authentication information */
10733 #endif
10737 ** A macro to discover the encoding of a database.
10739 #define ENC(db) ((db)->aDb[0].pSchema->enc)
10742 ** Possible values for the sqlite3.flags.
10744 #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
10745 #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
10746 #define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */
10747 #define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */
10748 #define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */
10749 #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
10750 #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
10751 #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
10752 /* DELETE, or UPDATE and return */
10753 /* the count using a callback. */
10754 #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
10755 /* result set is empty */
10756 #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
10757 #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
10758 #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
10759 #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
10760 #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
10761 #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
10762 #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
10763 #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
10764 #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
10765 #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
10766 #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
10767 #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
10768 #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
10769 #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
10770 #define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
10771 #define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
10772 #define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
10773 #define SQLITE_VdbeEQP 0x04000000 /* Debug EXPLAIN QUERY PLAN */
10777 ** Bits of the sqlite3.dbOptFlags field that are used by the
10778 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
10779 ** selectively disable various optimizations.
10781 #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
10782 #define SQLITE_ColumnCache 0x0002 /* Column cache */
10783 #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
10784 #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
10785 /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */
10786 #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
10787 #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
10788 #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
10789 #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
10790 #define SQLITE_Transitive 0x0200 /* Transitive constraints */
10791 #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
10792 #define SQLITE_Stat3 0x0800 /* Use the SQLITE_STAT3 table */
10793 #define SQLITE_AllOpts 0xffff /* All optimizations */
10796 ** Macros for testing whether or not optimizations are enabled or disabled.
10798 #ifndef SQLITE_OMIT_BUILTIN_TEST
10799 #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
10800 #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
10801 #else
10802 #define OptimizationDisabled(db, mask) 0
10803 #define OptimizationEnabled(db, mask) 1
10804 #endif
10807 ** Return true if it OK to factor constant expressions into the initialization
10808 ** code. The argument is a Parse object for the code generator.
10810 #define ConstFactorOk(P) ((P)->okConstFactor)
10813 ** Possible values for the sqlite.magic field.
10814 ** The numbers are obtained at random and have no special meaning, other
10815 ** than being distinct from one another.
10817 #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
10818 #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
10819 #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
10820 #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
10821 #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
10822 #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
10825 ** Each SQL function is defined by an instance of the following
10826 ** structure. A pointer to this structure is stored in the sqlite.aFunc
10827 ** hash table. When multiple functions have the same name, the hash table
10828 ** points to a linked list of these structures.
10830 struct FuncDef {
10831 i16 nArg; /* Number of arguments. -1 means unlimited */
10832 u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
10833 void *pUserData; /* User data parameter */
10834 FuncDef *pNext; /* Next function with same name */
10835 void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
10836 void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
10837 void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
10838 char *zName; /* SQL name of the function. */
10839 FuncDef *pHash; /* Next with a different name but the same hash */
10840 FuncDestructor *pDestructor; /* Reference counted destructor function */
10844 ** This structure encapsulates a user-function destructor callback (as
10845 ** configured using create_function_v2()) and a reference counter. When
10846 ** create_function_v2() is called to create a function with a destructor,
10847 ** a single object of this type is allocated. FuncDestructor.nRef is set to
10848 ** the number of FuncDef objects created (either 1 or 3, depending on whether
10849 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
10850 ** member of each of the new FuncDef objects is set to point to the allocated
10851 ** FuncDestructor.
10853 ** Thereafter, when one of the FuncDef objects is deleted, the reference
10854 ** count on this object is decremented. When it reaches 0, the destructor
10855 ** is invoked and the FuncDestructor structure freed.
10857 struct FuncDestructor {
10858 int nRef;
10859 void (*xDestroy)(void *);
10860 void *pUserData;
10864 ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
10865 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There
10866 ** are assert() statements in the code to verify this.
10868 #define SQLITE_FUNC_ENCMASK 0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
10869 #define SQLITE_FUNC_LIKE 0x004 /* Candidate for the LIKE optimization */
10870 #define SQLITE_FUNC_CASE 0x008 /* Case-sensitive LIKE-type function */
10871 #define SQLITE_FUNC_EPHEM 0x010 /* Ephemeral. Delete with VDBE */
10872 #define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
10873 #define SQLITE_FUNC_LENGTH 0x040 /* Built-in length() function */
10874 #define SQLITE_FUNC_TYPEOF 0x080 /* Built-in typeof() function */
10875 #define SQLITE_FUNC_COUNT 0x100 /* Built-in count(*) aggregate */
10876 #define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
10877 #define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
10878 #define SQLITE_FUNC_CONSTANT 0x800 /* Constant inputs give a constant output */
10879 #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
10882 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
10883 ** used to create the initializers for the FuncDef structures.
10885 ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
10886 ** Used to create a scalar function definition of a function zName
10887 ** implemented by C function xFunc that accepts nArg arguments. The
10888 ** value passed as iArg is cast to a (void*) and made available
10889 ** as the user-data (sqlite3_user_data()) for the function. If
10890 ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
10892 ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
10893 ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
10895 ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
10896 ** Used to create an aggregate function definition implemented by
10897 ** the C functions xStep and xFinal. The first four parameters
10898 ** are interpreted in the same way as the first 4 parameters to
10899 ** FUNCTION().
10901 ** LIKEFUNC(zName, nArg, pArg, flags)
10902 ** Used to create a scalar function definition of a function zName
10903 ** that accepts nArg arguments and is implemented by a call to C
10904 ** function likeFunc. Argument pArg is cast to a (void *) and made
10905 ** available as the function user-data (sqlite3_user_data()). The
10906 ** FuncDef.flags variable is set to the value passed as the flags
10907 ** parameter.
10909 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
10910 {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
10911 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10912 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
10913 {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
10914 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10915 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
10916 {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
10917 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10918 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
10919 {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
10920 pArg, 0, xFunc, 0, 0, #zName, 0, 0}
10921 #define LIKEFUNC(zName, nArg, arg, flags) \
10922 {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
10923 (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
10924 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
10925 {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
10926 SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
10927 #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
10928 {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
10929 SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
10932 ** All current savepoints are stored in a linked list starting at
10933 ** sqlite3.pSavepoint. The first element in the list is the most recently
10934 ** opened savepoint. Savepoints are added to the list by the vdbe
10935 ** OP_Savepoint instruction.
10937 struct Savepoint {
10938 char *zName; /* Savepoint name (nul-terminated) */
10939 i64 nDeferredCons; /* Number of deferred fk violations */
10940 i64 nDeferredImmCons; /* Number of deferred imm fk. */
10941 Savepoint *pNext; /* Parent savepoint (if any) */
10945 ** The following are used as the second parameter to sqlite3Savepoint(),
10946 ** and as the P1 argument to the OP_Savepoint instruction.
10948 #define SAVEPOINT_BEGIN 0
10949 #define SAVEPOINT_RELEASE 1
10950 #define SAVEPOINT_ROLLBACK 2
10954 ** Each SQLite module (virtual table definition) is defined by an
10955 ** instance of the following structure, stored in the sqlite3.aModule
10956 ** hash table.
10958 struct Module {
10959 const sqlite3_module *pModule; /* Callback pointers */
10960 const char *zName; /* Name passed to create_module() */
10961 void *pAux; /* pAux passed to create_module() */
10962 void (*xDestroy)(void *); /* Module destructor function */
10966 ** information about each column of an SQL table is held in an instance
10967 ** of this structure.
10969 struct Column {
10970 char *zName; /* Name of this column */
10971 Expr *pDflt; /* Default value of this column */
10972 char *zDflt; /* Original text of the default value */
10973 char *zType; /* Data type for this column */
10974 char *zColl; /* Collating sequence. If NULL, use the default */
10975 u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
10976 char affinity; /* One of the SQLITE_AFF_... values */
10977 u8 szEst; /* Estimated size of this column. INT==1 */
10978 u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
10981 /* Allowed values for Column.colFlags:
10983 #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
10984 #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
10987 ** A "Collating Sequence" is defined by an instance of the following
10988 ** structure. Conceptually, a collating sequence consists of a name and
10989 ** a comparison routine that defines the order of that sequence.
10991 ** If CollSeq.xCmp is NULL, it means that the
10992 ** collating sequence is undefined. Indices built on an undefined
10993 ** collating sequence may not be read or written.
10995 struct CollSeq {
10996 char *zName; /* Name of the collating sequence, UTF-8 encoded */
10997 u8 enc; /* Text encoding handled by xCmp() */
10998 void *pUser; /* First argument to xCmp() */
10999 int (*xCmp)(void*,int, const void*, int, const void*);
11000 void (*xDel)(void*); /* Destructor for pUser */
11004 ** A sort order can be either ASC or DESC.
11006 #define SQLITE_SO_ASC 0 /* Sort in ascending order */
11007 #define SQLITE_SO_DESC 1 /* Sort in ascending order */
11010 ** Column affinity types.
11012 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
11013 ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
11014 ** the speed a little by numbering the values consecutively.
11016 ** But rather than start with 0 or 1, we begin with 'A'. That way,
11017 ** when multiple affinity types are concatenated into a string and
11018 ** used as the P4 operand, they will be more readable.
11020 ** Note also that the numeric types are grouped together so that testing
11021 ** for a numeric type is a single comparison. And the NONE type is first.
11023 #define SQLITE_AFF_NONE 'A'
11024 #define SQLITE_AFF_TEXT 'B'
11025 #define SQLITE_AFF_NUMERIC 'C'
11026 #define SQLITE_AFF_INTEGER 'D'
11027 #define SQLITE_AFF_REAL 'E'
11029 #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
11032 ** The SQLITE_AFF_MASK values masks off the significant bits of an
11033 ** affinity value.
11035 #define SQLITE_AFF_MASK 0x47
11038 ** Additional bit values that can be ORed with an affinity without
11039 ** changing the affinity.
11041 ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
11042 ** It causes an assert() to fire if either operand to a comparison
11043 ** operator is NULL. It is added to certain comparison operators to
11044 ** prove that the operands are always NOT NULL.
11046 #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
11047 #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
11048 #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
11049 #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
11052 ** An object of this type is created for each virtual table present in
11053 ** the database schema.
11055 ** If the database schema is shared, then there is one instance of this
11056 ** structure for each database connection (sqlite3*) that uses the shared
11057 ** schema. This is because each database connection requires its own unique
11058 ** instance of the sqlite3_vtab* handle used to access the virtual table
11059 ** implementation. sqlite3_vtab* handles can not be shared between
11060 ** database connections, even when the rest of the in-memory database
11061 ** schema is shared, as the implementation often stores the database
11062 ** connection handle passed to it via the xConnect() or xCreate() method
11063 ** during initialization internally. This database connection handle may
11064 ** then be used by the virtual table implementation to access real tables
11065 ** within the database. So that they appear as part of the callers
11066 ** transaction, these accesses need to be made via the same database
11067 ** connection as that used to execute SQL operations on the virtual table.
11069 ** All VTable objects that correspond to a single table in a shared
11070 ** database schema are initially stored in a linked-list pointed to by
11071 ** the Table.pVTable member variable of the corresponding Table object.
11072 ** When an sqlite3_prepare() operation is required to access the virtual
11073 ** table, it searches the list for the VTable that corresponds to the
11074 ** database connection doing the preparing so as to use the correct
11075 ** sqlite3_vtab* handle in the compiled query.
11077 ** When an in-memory Table object is deleted (for example when the
11078 ** schema is being reloaded for some reason), the VTable objects are not
11079 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
11080 ** immediately. Instead, they are moved from the Table.pVTable list to
11081 ** another linked list headed by the sqlite3.pDisconnect member of the
11082 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
11083 ** next time a statement is prepared using said sqlite3*. This is done
11084 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
11085 ** Refer to comments above function sqlite3VtabUnlockList() for an
11086 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
11087 ** list without holding the corresponding sqlite3.mutex mutex.
11089 ** The memory for objects of this type is always allocated by
11090 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
11091 ** the first argument.
11093 struct VTable {
11094 sqlite3 *db; /* Database connection associated with this table */
11095 Module *pMod; /* Pointer to module implementation */
11096 sqlite3_vtab *pVtab; /* Pointer to vtab instance */
11097 int nRef; /* Number of pointers to this structure */
11098 u8 bConstraint; /* True if constraints are supported */
11099 int iSavepoint; /* Depth of the SAVEPOINT stack */
11100 VTable *pNext; /* Next in linked list (see above) */
11104 ** Each SQL table is represented in memory by an instance of the
11105 ** following structure.
11107 ** Table.zName is the name of the table. The case of the original
11108 ** CREATE TABLE statement is stored, but case is not significant for
11109 ** comparisons.
11111 ** Table.nCol is the number of columns in this table. Table.aCol is a
11112 ** pointer to an array of Column structures, one for each column.
11114 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
11115 ** the column that is that key. Otherwise Table.iPKey is negative. Note
11116 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
11117 ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
11118 ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
11119 ** is generated for each row of the table. TF_HasPrimaryKey is set if
11120 ** the table has any PRIMARY KEY, INTEGER or otherwise.
11122 ** Table.tnum is the page number for the root BTree page of the table in the
11123 ** database file. If Table.iDb is the index of the database table backend
11124 ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
11125 ** holds temporary tables and indices. If TF_Ephemeral is set
11126 ** then the table is stored in a file that is automatically deleted
11127 ** when the VDBE cursor to the table is closed. In this case Table.tnum
11128 ** refers VDBE cursor number that holds the table open, not to the root
11129 ** page number. Transient tables are used to hold the results of a
11130 ** sub-query that appears instead of a real table name in the FROM clause
11131 ** of a SELECT statement.
11133 struct Table {
11134 char *zName; /* Name of the table or view */
11135 Column *aCol; /* Information about each column */
11136 Index *pIndex; /* List of SQL indexes on this table. */
11137 Select *pSelect; /* NULL for tables. Points to definition if a view. */
11138 FKey *pFKey; /* Linked list of all foreign keys in this table */
11139 char *zColAff; /* String defining the affinity of each column */
11140 #ifndef SQLITE_OMIT_CHECK
11141 ExprList *pCheck; /* All CHECK constraints */
11142 #endif
11143 LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
11144 int tnum; /* Root BTree node for this table (see note above) */
11145 i16 iPKey; /* If not negative, use aCol[iPKey] as the primary key */
11146 i16 nCol; /* Number of columns in this table */
11147 u16 nRef; /* Number of pointers to this Table */
11148 LogEst szTabRow; /* Estimated size of each table row in bytes */
11149 #ifdef SQLITE_ENABLE_COSTMULT
11150 LogEst costMult; /* Cost multiplier for using this table */
11151 #endif
11152 u8 tabFlags; /* Mask of TF_* values */
11153 u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
11154 #ifndef SQLITE_OMIT_ALTERTABLE
11155 int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
11156 #endif
11157 #ifndef SQLITE_OMIT_VIRTUALTABLE
11158 int nModuleArg; /* Number of arguments to the module */
11159 char **azModuleArg; /* Text of all module args. [0] is module name */
11160 VTable *pVTable; /* List of VTable objects. */
11161 #endif
11162 Trigger *pTrigger; /* List of triggers stored in pSchema */
11163 Schema *pSchema; /* Schema that contains this table */
11164 Table *pNextZombie; /* Next on the Parse.pZombieTab list */
11168 ** Allowed values for Table.tabFlags.
11170 #define TF_Readonly 0x01 /* Read-only system table */
11171 #define TF_Ephemeral 0x02 /* An ephemeral table */
11172 #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
11173 #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
11174 #define TF_Virtual 0x10 /* Is a virtual table */
11175 #define TF_WithoutRowid 0x20 /* No rowid used. PRIMARY KEY is the key */
11179 ** Test to see whether or not a table is a virtual table. This is
11180 ** done as a macro so that it will be optimized out when virtual
11181 ** table support is omitted from the build.
11183 #ifndef SQLITE_OMIT_VIRTUALTABLE
11184 # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
11185 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
11186 #else
11187 # define IsVirtual(X) 0
11188 # define IsHiddenColumn(X) 0
11189 #endif
11191 /* Does the table have a rowid */
11192 #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
11195 ** Each foreign key constraint is an instance of the following structure.
11197 ** A foreign key is associated with two tables. The "from" table is
11198 ** the table that contains the REFERENCES clause that creates the foreign
11199 ** key. The "to" table is the table that is named in the REFERENCES clause.
11200 ** Consider this example:
11202 ** CREATE TABLE ex1(
11203 ** a INTEGER PRIMARY KEY,
11204 ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
11205 ** );
11207 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
11208 ** Equivalent names:
11210 ** from-table == child-table
11211 ** to-table == parent-table
11213 ** Each REFERENCES clause generates an instance of the following structure
11214 ** which is attached to the from-table. The to-table need not exist when
11215 ** the from-table is created. The existence of the to-table is not checked.
11217 ** The list of all parents for child Table X is held at X.pFKey.
11219 ** A list of all children for a table named Z (which might not even exist)
11220 ** is held in Schema.fkeyHash with a hash key of Z.
11222 struct FKey {
11223 Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
11224 FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
11225 char *zTo; /* Name of table that the key points to (aka: Parent) */
11226 FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
11227 FKey *pPrevTo; /* Previous with the same zTo */
11228 int nCol; /* Number of columns in this key */
11229 /* EV: R-30323-21917 */
11230 u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
11231 u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
11232 Trigger *apTrigger[2];/* Triggers for aAction[] actions */
11233 struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
11234 int iFrom; /* Index of column in pFrom */
11235 char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
11236 } aCol[1]; /* One entry for each of nCol columns */
11240 ** SQLite supports many different ways to resolve a constraint
11241 ** error. ROLLBACK processing means that a constraint violation
11242 ** causes the operation in process to fail and for the current transaction
11243 ** to be rolled back. ABORT processing means the operation in process
11244 ** fails and any prior changes from that one operation are backed out,
11245 ** but the transaction is not rolled back. FAIL processing means that
11246 ** the operation in progress stops and returns an error code. But prior
11247 ** changes due to the same operation are not backed out and no rollback
11248 ** occurs. IGNORE means that the particular row that caused the constraint
11249 ** error is not inserted or updated. Processing continues and no error
11250 ** is returned. REPLACE means that preexisting database rows that caused
11251 ** a UNIQUE constraint violation are removed so that the new insert or
11252 ** update can proceed. Processing continues and no error is reported.
11254 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
11255 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
11256 ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
11257 ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
11258 ** referenced table row is propagated into the row that holds the
11259 ** foreign key.
11261 ** The following symbolic values are used to record which type
11262 ** of action to take.
11264 #define OE_None 0 /* There is no constraint to check */
11265 #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
11266 #define OE_Abort 2 /* Back out changes but do no rollback transaction */
11267 #define OE_Fail 3 /* Stop the operation but leave all prior changes */
11268 #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
11269 #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
11271 #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
11272 #define OE_SetNull 7 /* Set the foreign key value to NULL */
11273 #define OE_SetDflt 8 /* Set the foreign key value to its default */
11274 #define OE_Cascade 9 /* Cascade the changes */
11276 #define OE_Default 10 /* Do whatever the default action is */
11280 ** An instance of the following structure is passed as the first
11281 ** argument to sqlite3VdbeKeyCompare and is used to control the
11282 ** comparison of the two index keys.
11284 ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
11285 ** are nField slots for the columns of an index then one extra slot
11286 ** for the rowid at the end.
11288 struct KeyInfo {
11289 u32 nRef; /* Number of references to this KeyInfo object */
11290 u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
11291 u16 nField; /* Number of key columns in the index */
11292 u16 nXField; /* Number of columns beyond the key columns */
11293 sqlite3 *db; /* The database connection */
11294 u8 *aSortOrder; /* Sort order for each column. */
11295 CollSeq *aColl[1]; /* Collating sequence for each term of the key */
11299 ** An instance of the following structure holds information about a
11300 ** single index record that has already been parsed out into individual
11301 ** values.
11303 ** A record is an object that contains one or more fields of data.
11304 ** Records are used to store the content of a table row and to store
11305 ** the key of an index. A blob encoding of a record is created by
11306 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
11307 ** OP_Column opcode.
11309 ** This structure holds a record that has already been disassembled
11310 ** into its constituent fields.
11312 ** The r1 and r2 member variables are only used by the optimized comparison
11313 ** functions vdbeRecordCompareInt() and vdbeRecordCompareString().
11315 struct UnpackedRecord {
11316 KeyInfo *pKeyInfo; /* Collation and sort-order information */
11317 u16 nField; /* Number of entries in apMem[] */
11318 i8 default_rc; /* Comparison result if keys are equal */
11319 u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
11320 Mem *aMem; /* Values */
11321 int r1; /* Value to return if (lhs > rhs) */
11322 int r2; /* Value to return if (rhs < lhs) */
11327 ** Each SQL index is represented in memory by an
11328 ** instance of the following structure.
11330 ** The columns of the table that are to be indexed are described
11331 ** by the aiColumn[] field of this structure. For example, suppose
11332 ** we have the following table and index:
11334 ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
11335 ** CREATE INDEX Ex2 ON Ex1(c3,c1);
11337 ** In the Table structure describing Ex1, nCol==3 because there are
11338 ** three columns in the table. In the Index structure describing
11339 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
11340 ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
11341 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
11342 ** The second column to be indexed (c1) has an index of 0 in
11343 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
11345 ** The Index.onError field determines whether or not the indexed columns
11346 ** must be unique and what to do if they are not. When Index.onError=OE_None,
11347 ** it means this is not a unique index. Otherwise it is a unique index
11348 ** and the value of Index.onError indicate the which conflict resolution
11349 ** algorithm to employ whenever an attempt is made to insert a non-unique
11350 ** element.
11352 struct Index {
11353 char *zName; /* Name of this index */
11354 i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
11355 LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
11356 Table *pTable; /* The SQL table being indexed */
11357 char *zColAff; /* String defining the affinity of each column */
11358 Index *pNext; /* The next index associated with the same table */
11359 Schema *pSchema; /* Schema containing this index */
11360 u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
11361 char **azColl; /* Array of collation sequence names for index */
11362 Expr *pPartIdxWhere; /* WHERE clause for partial indices */
11363 KeyInfo *pKeyInfo; /* A KeyInfo object suitable for this index */
11364 int tnum; /* DB Page containing root of this index */
11365 LogEst szIdxRow; /* Estimated average row size in bytes */
11366 u16 nKeyCol; /* Number of columns forming the key */
11367 u16 nColumn; /* Number of columns stored in the index */
11368 u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
11369 unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
11370 unsigned bUnordered:1; /* Use this index for == or IN queries only */
11371 unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
11372 unsigned isResized:1; /* True if resizeIndexObject() has been called */
11373 unsigned isCovering:1; /* True if this is a covering index */
11374 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
11375 int nSample; /* Number of elements in aSample[] */
11376 int nSampleCol; /* Size of IndexSample.anEq[] and so on */
11377 tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
11378 IndexSample *aSample; /* Samples of the left-most key */
11379 tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this table */
11380 #endif
11384 ** Allowed values for Index.idxType
11386 #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
11387 #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
11388 #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
11390 /* Return true if index X is a PRIMARY KEY index */
11391 #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
11393 /* Return true if index X is a UNIQUE index */
11394 #define IsUniqueIndex(X) ((X)->onError!=OE_None)
11397 ** Each sample stored in the sqlite_stat3 table is represented in memory
11398 ** using a structure of this type. See documentation at the top of the
11399 ** analyze.c source file for additional information.
11401 struct IndexSample {
11402 void *p; /* Pointer to sampled record */
11403 int n; /* Size of record in bytes */
11404 tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
11405 tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
11406 tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
11410 ** Each token coming out of the lexer is an instance of
11411 ** this structure. Tokens are also used as part of an expression.
11413 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
11414 ** may contain random values. Do not make any assumptions about Token.dyn
11415 ** and Token.n when Token.z==0.
11417 struct Token {
11418 const char *z; /* Text of the token. Not NULL-terminated! */
11419 unsigned int n; /* Number of characters in this token */
11423 ** An instance of this structure contains information needed to generate
11424 ** code for a SELECT that contains aggregate functions.
11426 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
11427 ** pointer to this structure. The Expr.iColumn field is the index in
11428 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
11429 ** code for that node.
11431 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
11432 ** original Select structure that describes the SELECT statement. These
11433 ** fields do not need to be freed when deallocating the AggInfo structure.
11435 struct AggInfo {
11436 u8 directMode; /* Direct rendering mode means take data directly
11437 ** from source tables rather than from accumulators */
11438 u8 useSortingIdx; /* In direct mode, reference the sorting index rather
11439 ** than the source table */
11440 int sortingIdx; /* Cursor number of the sorting index */
11441 int sortingIdxPTab; /* Cursor number of pseudo-table */
11442 int nSortingColumn; /* Number of columns in the sorting index */
11443 int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
11444 ExprList *pGroupBy; /* The group by clause */
11445 struct AggInfo_col { /* For each column used in source tables */
11446 Table *pTab; /* Source table */
11447 int iTable; /* Cursor number of the source table */
11448 int iColumn; /* Column number within the source table */
11449 int iSorterColumn; /* Column number in the sorting index */
11450 int iMem; /* Memory location that acts as accumulator */
11451 Expr *pExpr; /* The original expression */
11452 } *aCol;
11453 int nColumn; /* Number of used entries in aCol[] */
11454 int nAccumulator; /* Number of columns that show through to the output.
11455 ** Additional columns are used only as parameters to
11456 ** aggregate functions */
11457 struct AggInfo_func { /* For each aggregate function */
11458 Expr *pExpr; /* Expression encoding the function */
11459 FuncDef *pFunc; /* The aggregate function implementation */
11460 int iMem; /* Memory location that acts as accumulator */
11461 int iDistinct; /* Ephemeral table used to enforce DISTINCT */
11462 } *aFunc;
11463 int nFunc; /* Number of entries in aFunc[] */
11467 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
11468 ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
11469 ** than 32767 we have to make it 32-bit. 16-bit is preferred because
11470 ** it uses less memory in the Expr object, which is a big memory user
11471 ** in systems with lots of prepared statements. And few applications
11472 ** need more than about 10 or 20 variables. But some extreme users want
11473 ** to have prepared statements with over 32767 variables, and for them
11474 ** the option is available (at compile-time).
11476 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
11477 typedef i16 ynVar;
11478 #else
11479 typedef int ynVar;
11480 #endif
11483 ** Each node of an expression in the parse tree is an instance
11484 ** of this structure.
11486 ** Expr.op is the opcode. The integer parser token codes are reused
11487 ** as opcodes here. For example, the parser defines TK_GE to be an integer
11488 ** code representing the ">=" operator. This same integer code is reused
11489 ** to represent the greater-than-or-equal-to operator in the expression
11490 ** tree.
11492 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
11493 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
11494 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
11495 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
11496 ** then Expr.token contains the name of the function.
11498 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
11499 ** binary operator. Either or both may be NULL.
11501 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
11502 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
11503 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
11504 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
11505 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
11506 ** valid.
11508 ** An expression of the form ID or ID.ID refers to a column in a table.
11509 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
11510 ** the integer cursor number of a VDBE cursor pointing to that table and
11511 ** Expr.iColumn is the column number for the specific column. If the
11512 ** expression is used as a result in an aggregate SELECT, then the
11513 ** value is also stored in the Expr.iAgg column in the aggregate so that
11514 ** it can be accessed after all aggregates are computed.
11516 ** If the expression is an unbound variable marker (a question mark
11517 ** character '?' in the original SQL) then the Expr.iTable holds the index
11518 ** number for that variable.
11520 ** If the expression is a subquery then Expr.iColumn holds an integer
11521 ** register number containing the result of the subquery. If the
11522 ** subquery gives a constant result, then iTable is -1. If the subquery
11523 ** gives a different answer at different times during statement processing
11524 ** then iTable is the address of a subroutine that computes the subquery.
11526 ** If the Expr is of type OP_Column, and the table it is selecting from
11527 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
11528 ** corresponding table definition.
11530 ** ALLOCATION NOTES:
11532 ** Expr objects can use a lot of memory space in database schema. To
11533 ** help reduce memory requirements, sometimes an Expr object will be
11534 ** truncated. And to reduce the number of memory allocations, sometimes
11535 ** two or more Expr objects will be stored in a single memory allocation,
11536 ** together with Expr.zToken strings.
11538 ** If the EP_Reduced and EP_TokenOnly flags are set when
11539 ** an Expr object is truncated. When EP_Reduced is set, then all
11540 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
11541 ** are contained within the same memory allocation. Note, however, that
11542 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
11543 ** allocated, regardless of whether or not EP_Reduced is set.
11545 struct Expr {
11546 u8 op; /* Operation performed by this node */
11547 char affinity; /* The affinity of the column or 0 if not a column */
11548 u32 flags; /* Various flags. EP_* See below */
11549 union {
11550 char *zToken; /* Token value. Zero terminated and dequoted */
11551 int iValue; /* Non-negative integer value if EP_IntValue */
11552 } u;
11554 /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
11555 ** space is allocated for the fields below this point. An attempt to
11556 ** access them will result in a segfault or malfunction.
11557 *********************************************************************/
11559 Expr *pLeft; /* Left subnode */
11560 Expr *pRight; /* Right subnode */
11561 union {
11562 ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
11563 Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
11564 } x;
11566 /* If the EP_Reduced flag is set in the Expr.flags mask, then no
11567 ** space is allocated for the fields below this point. An attempt to
11568 ** access them will result in a segfault or malfunction.
11569 *********************************************************************/
11571 #if SQLITE_MAX_EXPR_DEPTH>0
11572 int nHeight; /* Height of the tree headed by this node */
11573 #endif
11574 int iTable; /* TK_COLUMN: cursor number of table holding column
11575 ** TK_REGISTER: register number
11576 ** TK_TRIGGER: 1 -> new, 0 -> old
11577 ** EP_Unlikely: 1000 times likelihood */
11578 ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
11579 ** TK_VARIABLE: variable number (always >= 1). */
11580 i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
11581 i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
11582 u8 op2; /* TK_REGISTER: original value of Expr.op
11583 ** TK_COLUMN: the value of p5 for OP_Column
11584 ** TK_AGG_FUNCTION: nesting depth */
11585 AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
11586 Table *pTab; /* Table for TK_COLUMN expressions. */
11590 ** The following are the meanings of bits in the Expr.flags field.
11592 #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
11593 #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
11594 #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
11595 #define EP_Error 0x000008 /* Expression contains one or more errors */
11596 #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
11597 #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
11598 #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
11599 #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
11600 #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
11601 #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
11602 #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
11603 #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
11604 #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
11605 #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
11606 #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
11607 #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
11608 #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
11609 #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
11610 #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
11611 #define EP_Constant 0x080000 /* Node is a constant */
11612 #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
11615 ** These macros can be used to test, set, or clear bits in the
11616 ** Expr.flags field.
11618 #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
11619 #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
11620 #define ExprSetProperty(E,P) (E)->flags|=(P)
11621 #define ExprClearProperty(E,P) (E)->flags&=~(P)
11623 /* The ExprSetVVAProperty() macro is used for Verification, Validation,
11624 ** and Accreditation only. It works like ExprSetProperty() during VVA
11625 ** processes but is a no-op for delivery.
11627 #ifdef SQLITE_DEBUG
11628 # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
11629 #else
11630 # define ExprSetVVAProperty(E,P)
11631 #endif
11634 ** Macros to determine the number of bytes required by a normal Expr
11635 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
11636 ** and an Expr struct with the EP_TokenOnly flag set.
11638 #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
11639 #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
11640 #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
11643 ** Flags passed to the sqlite3ExprDup() function. See the header comment
11644 ** above sqlite3ExprDup() for details.
11646 #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
11649 ** A list of expressions. Each expression may optionally have a
11650 ** name. An expr/name combination can be used in several ways, such
11651 ** as the list of "expr AS ID" fields following a "SELECT" or in the
11652 ** list of "ID = expr" items in an UPDATE. A list of expressions can
11653 ** also be used as the argument to a function, in which case the a.zName
11654 ** field is not used.
11656 ** By default the Expr.zSpan field holds a human-readable description of
11657 ** the expression that is used in the generation of error messages and
11658 ** column labels. In this case, Expr.zSpan is typically the text of a
11659 ** column expression as it exists in a SELECT statement. However, if
11660 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
11661 ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
11662 ** form is used for name resolution with nested FROM clauses.
11664 struct ExprList {
11665 int nExpr; /* Number of expressions on the list */
11666 struct ExprList_item { /* For each expression in the list */
11667 Expr *pExpr; /* The list of expressions */
11668 char *zName; /* Token associated with this expression */
11669 char *zSpan; /* Original text of the expression */
11670 u8 sortOrder; /* 1 for DESC or 0 for ASC */
11671 unsigned done :1; /* A flag to indicate when processing is finished */
11672 unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
11673 unsigned reusable :1; /* Constant expression is reusable */
11674 union {
11675 struct {
11676 u16 iOrderByCol; /* For ORDER BY, column number in result set */
11677 u16 iAlias; /* Index into Parse.aAlias[] for zName */
11678 } x;
11679 int iConstExprReg; /* Register in which Expr value is cached */
11680 } u;
11681 } *a; /* Alloc a power of two greater or equal to nExpr */
11685 ** An instance of this structure is used by the parser to record both
11686 ** the parse tree for an expression and the span of input text for an
11687 ** expression.
11689 struct ExprSpan {
11690 Expr *pExpr; /* The expression parse tree */
11691 const char *zStart; /* First character of input text */
11692 const char *zEnd; /* One character past the end of input text */
11696 ** An instance of this structure can hold a simple list of identifiers,
11697 ** such as the list "a,b,c" in the following statements:
11699 ** INSERT INTO t(a,b,c) VALUES ...;
11700 ** CREATE INDEX idx ON t(a,b,c);
11701 ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
11703 ** The IdList.a.idx field is used when the IdList represents the list of
11704 ** column names after a table name in an INSERT statement. In the statement
11706 ** INSERT INTO t(a,b,c) ...
11708 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
11710 struct IdList {
11711 struct IdList_item {
11712 char *zName; /* Name of the identifier */
11713 int idx; /* Index in some Table.aCol[] of a column named zName */
11714 } *a;
11715 int nId; /* Number of identifiers on the list */
11719 ** The bitmask datatype defined below is used for various optimizations.
11721 ** Changing this from a 64-bit to a 32-bit type limits the number of
11722 ** tables in a join to 32 instead of 64. But it also reduces the size
11723 ** of the library by 738 bytes on ix86.
11725 typedef u64 Bitmask;
11728 ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
11730 #define BMS ((int)(sizeof(Bitmask)*8))
11733 ** A bit in a Bitmask
11735 #define MASKBIT(n) (((Bitmask)1)<<(n))
11736 #define MASKBIT32(n) (((unsigned int)1)<<(n))
11739 ** The following structure describes the FROM clause of a SELECT statement.
11740 ** Each table or subquery in the FROM clause is a separate element of
11741 ** the SrcList.a[] array.
11743 ** With the addition of multiple database support, the following structure
11744 ** can also be used to describe a particular table such as the table that
11745 ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
11746 ** such a table must be a simple name: ID. But in SQLite, the table can
11747 ** now be identified by a database name, a dot, then the table name: ID.ID.
11749 ** The jointype starts out showing the join type between the current table
11750 ** and the next table on the list. The parser builds the list this way.
11751 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
11752 ** jointype expresses the join between the table and the previous table.
11754 ** In the colUsed field, the high-order bit (bit 63) is set if the table
11755 ** contains more than 63 columns and the 64-th or later column is used.
11757 struct SrcList {
11758 int nSrc; /* Number of tables or subqueries in the FROM clause */
11759 u32 nAlloc; /* Number of entries allocated in a[] below */
11760 struct SrcList_item {
11761 Schema *pSchema; /* Schema to which this item is fixed */
11762 char *zDatabase; /* Name of database holding this table */
11763 char *zName; /* Name of the table */
11764 char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
11765 Table *pTab; /* An SQL table corresponding to zName */
11766 Select *pSelect; /* A SELECT statement used in place of a table name */
11767 int addrFillSub; /* Address of subroutine to manifest a subquery */
11768 int regReturn; /* Register holding return address of addrFillSub */
11769 int regResult; /* Registers holding results of a co-routine */
11770 u8 jointype; /* Type of join between this able and the previous */
11771 unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
11772 unsigned isCorrelated :1; /* True if sub-query is correlated */
11773 unsigned viaCoroutine :1; /* Implemented as a co-routine */
11774 unsigned isRecursive :1; /* True for recursive reference in WITH */
11775 #ifndef SQLITE_OMIT_EXPLAIN
11776 u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
11777 #endif
11778 int iCursor; /* The VDBE cursor number used to access this table */
11779 Expr *pOn; /* The ON clause of a join */
11780 IdList *pUsing; /* The USING clause of a join */
11781 Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
11782 char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
11783 Index *pIndex; /* Index structure corresponding to zIndex, if any */
11784 } a[1]; /* One entry for each identifier on the list */
11788 ** Permitted values of the SrcList.a.jointype field
11790 #define JT_INNER 0x0001 /* Any kind of inner or cross join */
11791 #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
11792 #define JT_NATURAL 0x0004 /* True for a "natural" join */
11793 #define JT_LEFT 0x0008 /* Left outer join */
11794 #define JT_RIGHT 0x0010 /* Right outer join */
11795 #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
11796 #define JT_ERROR 0x0040 /* unknown or unsupported join type */
11800 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
11801 ** and the WhereInfo.wctrlFlags member.
11803 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
11804 #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
11805 #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
11806 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
11807 #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
11808 #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
11809 #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
11810 #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
11811 /* 0x0080 // not currently used */
11812 #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
11813 #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
11814 #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
11815 #define WHERE_SORTBYGROUP 0x0800 /* Support sqlite3WhereIsSorted() */
11816 #define WHERE_REOPEN_IDX 0x1000 /* Try to use OP_ReopenIdx */
11818 /* Allowed return values from sqlite3WhereIsDistinct()
11820 #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
11821 #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
11822 #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
11823 #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
11826 ** A NameContext defines a context in which to resolve table and column
11827 ** names. The context consists of a list of tables (the pSrcList) field and
11828 ** a list of named expression (pEList). The named expression list may
11829 ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
11830 ** to the table being operated on by INSERT, UPDATE, or DELETE. The
11831 ** pEList corresponds to the result set of a SELECT and is NULL for
11832 ** other statements.
11834 ** NameContexts can be nested. When resolving names, the inner-most
11835 ** context is searched first. If no match is found, the next outer
11836 ** context is checked. If there is still no match, the next context
11837 ** is checked. This process continues until either a match is found
11838 ** or all contexts are check. When a match is found, the nRef member of
11839 ** the context containing the match is incremented.
11841 ** Each subquery gets a new NameContext. The pNext field points to the
11842 ** NameContext in the parent query. Thus the process of scanning the
11843 ** NameContext list corresponds to searching through successively outer
11844 ** subqueries looking for a match.
11846 struct NameContext {
11847 Parse *pParse; /* The parser */
11848 SrcList *pSrcList; /* One or more tables used to resolve names */
11849 ExprList *pEList; /* Optional list of result-set columns */
11850 AggInfo *pAggInfo; /* Information about aggregates at this level */
11851 NameContext *pNext; /* Next outer name context. NULL for outermost */
11852 int nRef; /* Number of names resolved by this context */
11853 int nErr; /* Number of errors encountered while resolving names */
11854 u16 ncFlags; /* Zero or more NC_* flags defined below */
11858 ** Allowed values for the NameContext, ncFlags field.
11860 ** Note: NC_MinMaxAgg must have the same value as SF_MinMaxAgg and
11861 ** SQLITE_FUNC_MINMAX.
11864 #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
11865 #define NC_HasAgg 0x0002 /* One or more aggregate functions seen */
11866 #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
11867 #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
11868 #define NC_PartIdx 0x0010 /* True if resolving a partial index WHERE */
11869 #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
11872 ** An instance of the following structure contains all information
11873 ** needed to generate code for a single SELECT statement.
11875 ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
11876 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
11877 ** limit and nOffset to the value of the offset (or 0 if there is not
11878 ** offset). But later on, nLimit and nOffset become the memory locations
11879 ** in the VDBE that record the limit and offset counters.
11881 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
11882 ** These addresses must be stored so that we can go back and fill in
11883 ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
11884 ** the number of columns in P2 can be computed at the same time
11885 ** as the OP_OpenEphm instruction is coded because not
11886 ** enough information about the compound query is known at that point.
11887 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
11888 ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
11889 ** sequences for the ORDER BY clause.
11891 struct Select {
11892 ExprList *pEList; /* The fields of the result */
11893 u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
11894 u16 selFlags; /* Various SF_* values */
11895 int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
11896 #if SELECTTRACE_ENABLED
11897 char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
11898 #endif
11899 int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
11900 u64 nSelectRow; /* Estimated number of result rows */
11901 SrcList *pSrc; /* The FROM clause */
11902 Expr *pWhere; /* The WHERE clause */
11903 ExprList *pGroupBy; /* The GROUP BY clause */
11904 Expr *pHaving; /* The HAVING clause */
11905 ExprList *pOrderBy; /* The ORDER BY clause */
11906 Select *pPrior; /* Prior select in a compound select statement */
11907 Select *pNext; /* Next select to the left in a compound */
11908 Expr *pLimit; /* LIMIT expression. NULL means not used. */
11909 Expr *pOffset; /* OFFSET expression. NULL means not used. */
11910 With *pWith; /* WITH clause attached to this select. Or NULL. */
11914 ** Allowed values for Select.selFlags. The "SF" prefix stands for
11915 ** "Select Flag".
11917 #define SF_Distinct 0x0001 /* Output should be DISTINCT */
11918 #define SF_Resolved 0x0002 /* Identifiers have been resolved */
11919 #define SF_Aggregate 0x0004 /* Contains aggregate functions */
11920 #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
11921 #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
11922 #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
11923 #define SF_Compound 0x0040 /* Part of a compound query */
11924 #define SF_Values 0x0080 /* Synthesized from VALUES clause */
11925 /* 0x0100 NOT USED */
11926 #define SF_NestedFrom 0x0200 /* Part of a parenthesized FROM clause */
11927 #define SF_MaybeConvert 0x0400 /* Need convertCompoundSelectToSubquery() */
11928 #define SF_Recursive 0x0800 /* The recursive part of a recursive CTE */
11929 #define SF_MinMaxAgg 0x1000 /* Aggregate containing min() or max() */
11933 ** The results of a SELECT can be distributed in several ways, as defined
11934 ** by one of the following macros. The "SRT" prefix means "SELECT Result
11935 ** Type".
11937 ** SRT_Union Store results as a key in a temporary index
11938 ** identified by pDest->iSDParm.
11940 ** SRT_Except Remove results from the temporary index pDest->iSDParm.
11942 ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
11943 ** set is not empty.
11945 ** SRT_Discard Throw the results away. This is used by SELECT
11946 ** statements within triggers whose only purpose is
11947 ** the side-effects of functions.
11949 ** All of the above are free to ignore their ORDER BY clause. Those that
11950 ** follow must honor the ORDER BY clause.
11952 ** SRT_Output Generate a row of output (using the OP_ResultRow
11953 ** opcode) for each row in the result set.
11955 ** SRT_Mem Only valid if the result is a single column.
11956 ** Store the first column of the first result row
11957 ** in register pDest->iSDParm then abandon the rest
11958 ** of the query. This destination implies "LIMIT 1".
11960 ** SRT_Set The result must be a single column. Store each
11961 ** row of result as the key in table pDest->iSDParm.
11962 ** Apply the affinity pDest->affSdst before storing
11963 ** results. Used to implement "IN (SELECT ...)".
11965 ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
11966 ** the result there. The cursor is left open after
11967 ** returning. This is like SRT_Table except that
11968 ** this destination uses OP_OpenEphemeral to create
11969 ** the table first.
11971 ** SRT_Coroutine Generate a co-routine that returns a new row of
11972 ** results each time it is invoked. The entry point
11973 ** of the co-routine is stored in register pDest->iSDParm
11974 ** and the result row is stored in pDest->nDest registers
11975 ** starting with pDest->iSdst.
11977 ** SRT_Table Store results in temporary table pDest->iSDParm.
11978 ** SRT_Fifo This is like SRT_EphemTab except that the table
11979 ** is assumed to already be open. SRT_Fifo has
11980 ** the additional property of being able to ignore
11981 ** the ORDER BY clause.
11983 ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
11984 ** But also use temporary table pDest->iSDParm+1 as
11985 ** a record of all prior results and ignore any duplicate
11986 ** rows. Name means: "Distinct Fifo".
11988 ** SRT_Queue Store results in priority queue pDest->iSDParm (really
11989 ** an index). Append a sequence number so that all entries
11990 ** are distinct.
11992 ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
11993 ** the same record has never been stored before. The
11994 ** index at pDest->iSDParm+1 hold all prior stores.
11996 #define SRT_Union 1 /* Store result as keys in an index */
11997 #define SRT_Except 2 /* Remove result from a UNION index */
11998 #define SRT_Exists 3 /* Store 1 if the result is not empty */
11999 #define SRT_Discard 4 /* Do not save the results anywhere */
12000 #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
12001 #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
12002 #define SRT_Queue 7 /* Store result in an queue */
12003 #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
12005 /* The ORDER BY clause is ignored for all of the above */
12006 #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
12008 #define SRT_Output 9 /* Output each row of result */
12009 #define SRT_Mem 10 /* Store result in a memory cell */
12010 #define SRT_Set 11 /* Store results as keys in an index */
12011 #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
12012 #define SRT_Coroutine 13 /* Generate a single row of result */
12013 #define SRT_Table 14 /* Store result as data with an automatic rowid */
12016 ** An instance of this object describes where to put of the results of
12017 ** a SELECT statement.
12019 struct SelectDest {
12020 u8 eDest; /* How to dispose of the results. On of SRT_* above. */
12021 char affSdst; /* Affinity used when eDest==SRT_Set */
12022 int iSDParm; /* A parameter used by the eDest disposal method */
12023 int iSdst; /* Base register where results are written */
12024 int nSdst; /* Number of registers allocated */
12025 ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
12029 ** During code generation of statements that do inserts into AUTOINCREMENT
12030 ** tables, the following information is attached to the Table.u.autoInc.p
12031 ** pointer of each autoincrement table to record some side information that
12032 ** the code generator needs. We have to keep per-table autoincrement
12033 ** information in case inserts are down within triggers. Triggers do not
12034 ** normally coordinate their activities, but we do need to coordinate the
12035 ** loading and saving of autoincrement information.
12037 struct AutoincInfo {
12038 AutoincInfo *pNext; /* Next info block in a list of them all */
12039 Table *pTab; /* Table this info block refers to */
12040 int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
12041 int regCtr; /* Memory register holding the rowid counter */
12045 ** Size of the column cache
12047 #ifndef SQLITE_N_COLCACHE
12048 # define SQLITE_N_COLCACHE 10
12049 #endif
12052 ** At least one instance of the following structure is created for each
12053 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
12054 ** statement. All such objects are stored in the linked list headed at
12055 ** Parse.pTriggerPrg and deleted once statement compilation has been
12056 ** completed.
12058 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
12059 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
12060 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
12061 ** The Parse.pTriggerPrg list never contains two entries with the same
12062 ** values for both pTrigger and orconf.
12064 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
12065 ** accessed (or set to 0 for triggers fired as a result of INSERT
12066 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
12067 ** a mask of new.* columns used by the program.
12069 struct TriggerPrg {
12070 Trigger *pTrigger; /* Trigger this program was coded from */
12071 TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
12072 SubProgram *pProgram; /* Program implementing pTrigger/orconf */
12073 int orconf; /* Default ON CONFLICT policy */
12074 u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
12078 ** The yDbMask datatype for the bitmask of all attached databases.
12080 #if SQLITE_MAX_ATTACHED>30
12081 typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
12082 # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
12083 # define DbMaskZero(M) memset((M),0,sizeof(M))
12084 # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
12085 # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
12086 # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
12087 #else
12088 typedef unsigned int yDbMask;
12089 # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
12090 # define DbMaskZero(M) (M)=0
12091 # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
12092 # define DbMaskAllZero(M) (M)==0
12093 # define DbMaskNonZero(M) (M)!=0
12094 #endif
12097 ** An SQL parser context. A copy of this structure is passed through
12098 ** the parser and down into all the parser action routine in order to
12099 ** carry around information that is global to the entire parse.
12101 ** The structure is divided into two parts. When the parser and code
12102 ** generate call themselves recursively, the first part of the structure
12103 ** is constant but the second part is reset at the beginning and end of
12104 ** each recursion.
12106 ** The nTableLock and aTableLock variables are only used if the shared-cache
12107 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
12108 ** used to store the set of table-locks required by the statement being
12109 ** compiled. Function sqlite3TableLock() is used to add entries to the
12110 ** list.
12112 struct Parse {
12113 sqlite3 *db; /* The main database structure */
12114 char *zErrMsg; /* An error message */
12115 Vdbe *pVdbe; /* An engine for executing database bytecode */
12116 int rc; /* Return code from execution */
12117 u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
12118 u8 checkSchema; /* Causes schema cookie check after an error */
12119 u8 nested; /* Number of nested calls to the parser/code generator */
12120 u8 nTempReg; /* Number of temporary registers in aTempReg[] */
12121 u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
12122 u8 mayAbort; /* True if statement may throw an ABORT exception */
12123 u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
12124 u8 okConstFactor; /* OK to factor out constants */
12125 int aTempReg[8]; /* Holding area for temporary registers */
12126 int nRangeReg; /* Size of the temporary register block */
12127 int iRangeReg; /* First register in temporary register block */
12128 int nErr; /* Number of errors seen */
12129 int nTab; /* Number of previously allocated VDBE cursors */
12130 int nMem; /* Number of memory cells used so far */
12131 int nSet; /* Number of sets used so far */
12132 int nOnce; /* Number of OP_Once instructions so far */
12133 int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
12134 int iFixedOp; /* Never back out opcodes iFixedOp-1 or earlier */
12135 int ckBase; /* Base register of data during check constraints */
12136 int iPartIdxTab; /* Table corresponding to a partial index */
12137 int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
12138 int iCacheCnt; /* Counter used to generate aColCache[].lru values */
12139 int nLabel; /* Number of labels used */
12140 int *aLabel; /* Space to hold the labels */
12141 struct yColCache {
12142 int iTable; /* Table cursor number */
12143 i16 iColumn; /* Table column number */
12144 u8 tempReg; /* iReg is a temp register that needs to be freed */
12145 int iLevel; /* Nesting level */
12146 int iReg; /* Reg with value of this column. 0 means none. */
12147 int lru; /* Least recently used entry has the smallest value */
12148 } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
12149 ExprList *pConstExpr;/* Constant expressions */
12150 Token constraintName;/* Name of the constraint currently being parsed */
12151 yDbMask writeMask; /* Start a write transaction on these databases */
12152 yDbMask cookieMask; /* Bitmask of schema verified databases */
12153 int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
12154 int regRowid; /* Register holding rowid of CREATE TABLE entry */
12155 int regRoot; /* Register holding root page number for new objects */
12156 int nMaxArg; /* Max args passed to user function by sub-program */
12157 #if SELECTTRACE_ENABLED
12158 int nSelect; /* Number of SELECT statements seen */
12159 int nSelectIndent; /* How far to indent SELECTTRACE() output */
12160 #endif
12161 #ifndef SQLITE_OMIT_SHARED_CACHE
12162 int nTableLock; /* Number of locks in aTableLock */
12163 TableLock *aTableLock; /* Required table locks for shared-cache mode */
12164 #endif
12165 AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
12167 /* Information used while coding trigger programs. */
12168 Parse *pToplevel; /* Parse structure for main program (or NULL) */
12169 Table *pTriggerTab; /* Table triggers are being coded for */
12170 int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */
12171 int addrSkipPK; /* Address of instruction to skip PRIMARY KEY index */
12172 u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
12173 u32 oldmask; /* Mask of old.* columns referenced */
12174 u32 newmask; /* Mask of new.* columns referenced */
12175 u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
12176 u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
12177 u8 disableTriggers; /* True to disable triggers */
12179 /************************************************************************
12180 ** Above is constant between recursions. Below is reset before and after
12181 ** each recursion. The boundary between these two regions is determined
12182 ** using offsetof(Parse,nVar) so the nVar field must be the first field
12183 ** in the recursive region.
12184 ************************************************************************/
12186 int nVar; /* Number of '?' variables seen in the SQL so far */
12187 int nzVar; /* Number of available slots in azVar[] */
12188 u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
12189 u8 bFreeWith; /* True if pWith should be freed with parser */
12190 u8 explain; /* True if the EXPLAIN flag is found on the query */
12191 #ifndef SQLITE_OMIT_VIRTUALTABLE
12192 u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
12193 int nVtabLock; /* Number of virtual tables to lock */
12194 #endif
12195 int nAlias; /* Number of aliased result set columns */
12196 int nHeight; /* Expression tree height of current sub-select */
12197 #ifndef SQLITE_OMIT_EXPLAIN
12198 int iSelectId; /* ID of current select for EXPLAIN output */
12199 int iNextSelectId; /* Next available select ID for EXPLAIN output */
12200 #endif
12201 char **azVar; /* Pointers to names of parameters */
12202 Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
12203 const char *zTail; /* All SQL text past the last semicolon parsed */
12204 Table *pNewTable; /* A table being constructed by CREATE TABLE */
12205 Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
12206 const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
12207 Token sNameToken; /* Token with unqualified schema object name */
12208 Token sLastToken; /* The last token parsed */
12209 #ifndef SQLITE_OMIT_VIRTUALTABLE
12210 Token sArg; /* Complete text of a module argument */
12211 Table **apVtabLock; /* Pointer to virtual tables needing locking */
12212 #endif
12213 Table *pZombieTab; /* List of Table objects to delete after code gen */
12214 TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
12215 With *pWith; /* Current WITH clause, or NULL */
12219 ** Return true if currently inside an sqlite3_declare_vtab() call.
12221 #ifdef SQLITE_OMIT_VIRTUALTABLE
12222 #define IN_DECLARE_VTAB 0
12223 #else
12224 #define IN_DECLARE_VTAB (pParse->declareVtab)
12225 #endif
12228 ** An instance of the following structure can be declared on a stack and used
12229 ** to save the Parse.zAuthContext value so that it can be restored later.
12231 struct AuthContext {
12232 const char *zAuthContext; /* Put saved Parse.zAuthContext here */
12233 Parse *pParse; /* The Parse structure */
12237 ** Bitfield flags for P5 value in various opcodes.
12239 #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
12240 #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
12241 #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
12242 #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
12243 #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
12244 #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
12245 #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
12246 #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
12247 #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
12248 #define OPFLAG_P2ISREG 0x02 /* P2 to OP_Open** is a register number */
12249 #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
12252 * Each trigger present in the database schema is stored as an instance of
12253 * struct Trigger.
12255 * Pointers to instances of struct Trigger are stored in two ways.
12256 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
12257 * database). This allows Trigger structures to be retrieved by name.
12258 * 2. All triggers associated with a single table form a linked list, using the
12259 * pNext member of struct Trigger. A pointer to the first element of the
12260 * linked list is stored as the "pTrigger" member of the associated
12261 * struct Table.
12263 * The "step_list" member points to the first element of a linked list
12264 * containing the SQL statements specified as the trigger program.
12266 struct Trigger {
12267 char *zName; /* The name of the trigger */
12268 char *table; /* The table or view to which the trigger applies */
12269 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
12270 u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
12271 Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
12272 IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
12273 the <column-list> is stored here */
12274 Schema *pSchema; /* Schema containing the trigger */
12275 Schema *pTabSchema; /* Schema containing the table */
12276 TriggerStep *step_list; /* Link list of trigger program steps */
12277 Trigger *pNext; /* Next trigger associated with the table */
12281 ** A trigger is either a BEFORE or an AFTER trigger. The following constants
12282 ** determine which.
12284 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
12285 ** In that cases, the constants below can be ORed together.
12287 #define TRIGGER_BEFORE 1
12288 #define TRIGGER_AFTER 2
12291 * An instance of struct TriggerStep is used to store a single SQL statement
12292 * that is a part of a trigger-program.
12294 * Instances of struct TriggerStep are stored in a singly linked list (linked
12295 * using the "pNext" member) referenced by the "step_list" member of the
12296 * associated struct Trigger instance. The first element of the linked list is
12297 * the first step of the trigger-program.
12299 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
12300 * "SELECT" statement. The meanings of the other members is determined by the
12301 * value of "op" as follows:
12303 * (op == TK_INSERT)
12304 * orconf -> stores the ON CONFLICT algorithm
12305 * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
12306 * this stores a pointer to the SELECT statement. Otherwise NULL.
12307 * target -> A token holding the quoted name of the table to insert into.
12308 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
12309 * this stores values to be inserted. Otherwise NULL.
12310 * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
12311 * statement, then this stores the column-names to be
12312 * inserted into.
12314 * (op == TK_DELETE)
12315 * target -> A token holding the quoted name of the table to delete from.
12316 * pWhere -> The WHERE clause of the DELETE statement if one is specified.
12317 * Otherwise NULL.
12319 * (op == TK_UPDATE)
12320 * target -> A token holding the quoted name of the table to update rows of.
12321 * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
12322 * Otherwise NULL.
12323 * pExprList -> A list of the columns to update and the expressions to update
12324 * them to. See sqlite3Update() documentation of "pChanges"
12325 * argument.
12328 struct TriggerStep {
12329 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
12330 u8 orconf; /* OE_Rollback etc. */
12331 Trigger *pTrig; /* The trigger that this step is a part of */
12332 Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
12333 Token target; /* Target table for DELETE, UPDATE, INSERT */
12334 Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
12335 ExprList *pExprList; /* SET clause for UPDATE. */
12336 IdList *pIdList; /* Column names for INSERT */
12337 TriggerStep *pNext; /* Next in the link-list */
12338 TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
12342 ** The following structure contains information used by the sqliteFix...
12343 ** routines as they walk the parse tree to make database references
12344 ** explicit.
12346 typedef struct DbFixer DbFixer;
12347 struct DbFixer {
12348 Parse *pParse; /* The parsing context. Error messages written here */
12349 Schema *pSchema; /* Fix items to this schema */
12350 int bVarOnly; /* Check for variable references only */
12351 const char *zDb; /* Make sure all objects are contained in this database */
12352 const char *zType; /* Type of the container - used for error messages */
12353 const Token *pName; /* Name of the container - used for error messages */
12357 ** An objected used to accumulate the text of a string where we
12358 ** do not necessarily know how big the string will be in the end.
12360 struct StrAccum {
12361 sqlite3 *db; /* Optional database for lookaside. Can be NULL */
12362 char *zBase; /* A base allocation. Not from malloc. */
12363 char *zText; /* The string collected so far */
12364 int nChar; /* Length of the string so far */
12365 int nAlloc; /* Amount of space allocated in zText */
12366 int mxAlloc; /* Maximum allowed string length */
12367 u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
12368 u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
12370 #define STRACCUM_NOMEM 1
12371 #define STRACCUM_TOOBIG 2
12374 ** A pointer to this structure is used to communicate information
12375 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
12377 typedef struct {
12378 sqlite3 *db; /* The database being initialized */
12379 char **pzErrMsg; /* Error message stored here */
12380 int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
12381 int rc; /* Result code stored here */
12382 } InitData;
12385 ** Structure containing global configuration data for the SQLite library.
12387 ** This structure also contains some state information.
12389 struct Sqlite3Config {
12390 int bMemstat; /* True to enable memory status */
12391 int bCoreMutex; /* True to enable core mutexing */
12392 int bFullMutex; /* True to enable full mutexing */
12393 int bOpenUri; /* True to interpret filenames as URIs */
12394 int bUseCis; /* Use covering indices for full-scans */
12395 int mxStrlen; /* Maximum string length */
12396 int neverCorrupt; /* Database is always well-formed */
12397 int szLookaside; /* Default lookaside buffer size */
12398 int nLookaside; /* Default lookaside buffer count */
12399 sqlite3_mem_methods m; /* Low-level memory allocation interface */
12400 sqlite3_mutex_methods mutex; /* Low-level mutex interface */
12401 sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
12402 void *pHeap; /* Heap storage space */
12403 int nHeap; /* Size of pHeap[] */
12404 int mnReq, mxReq; /* Min and max heap requests sizes */
12405 sqlite3_int64 szMmap; /* mmap() space per open file */
12406 sqlite3_int64 mxMmap; /* Maximum value for szMmap */
12407 void *pScratch; /* Scratch memory */
12408 int szScratch; /* Size of each scratch buffer */
12409 int nScratch; /* Number of scratch buffers */
12410 void *pPage; /* Page cache memory */
12411 int szPage; /* Size of each page in pPage[] */
12412 int nPage; /* Number of pages in pPage[] */
12413 int mxParserStack; /* maximum depth of the parser stack */
12414 int sharedCacheEnabled; /* true if shared-cache mode enabled */
12415 /* The above might be initialized to non-zero. The following need to always
12416 ** initially be zero, however. */
12417 int isInit; /* True after initialization has finished */
12418 int inProgress; /* True while initialization in progress */
12419 int isMutexInit; /* True after mutexes are initialized */
12420 int isMallocInit; /* True after malloc is initialized */
12421 int isPCacheInit; /* True after malloc is initialized */
12422 int nRefInitMutex; /* Number of users of pInitMutex */
12423 sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
12424 void (*xLog)(void*,int,const char*); /* Function for logging */
12425 void *pLogArg; /* First argument to xLog() */
12426 #ifdef SQLITE_ENABLE_SQLLOG
12427 void(*xSqllog)(void*,sqlite3*,const char*, int);
12428 void *pSqllogArg;
12429 #endif
12430 #ifdef SQLITE_VDBE_COVERAGE
12431 /* The following callback (if not NULL) is invoked on every VDBE branch
12432 ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
12434 void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
12435 void *pVdbeBranchArg; /* 1st argument */
12436 #endif
12437 #ifndef SQLITE_OMIT_BUILTIN_TEST
12438 int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
12439 #endif
12440 int bLocaltimeFault; /* True to fail localtime() calls */
12444 ** This macro is used inside of assert() statements to indicate that
12445 ** the assert is only valid on a well-formed database. Instead of:
12447 ** assert( X );
12449 ** One writes:
12451 ** assert( X || CORRUPT_DB );
12453 ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
12454 ** that the database is definitely corrupt, only that it might be corrupt.
12455 ** For most test cases, CORRUPT_DB is set to false using a special
12456 ** sqlite3_test_control(). This enables assert() statements to prove
12457 ** things that are always true for well-formed databases.
12459 #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
12462 ** Context pointer passed down through the tree-walk.
12464 struct Walker {
12465 int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
12466 int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
12467 void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
12468 Parse *pParse; /* Parser context. */
12469 int walkerDepth; /* Number of subqueries */
12470 union { /* Extra data for callback */
12471 NameContext *pNC; /* Naming context */
12472 int i; /* Integer value */
12473 SrcList *pSrcList; /* FROM clause */
12474 struct SrcCount *pSrcCount; /* Counting column references */
12475 } u;
12478 /* Forward declarations */
12479 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
12480 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
12481 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
12482 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
12483 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
12486 ** Return code from the parse-tree walking primitives and their
12487 ** callbacks.
12489 #define WRC_Continue 0 /* Continue down into children */
12490 #define WRC_Prune 1 /* Omit children but continue walking siblings */
12491 #define WRC_Abort 2 /* Abandon the tree walk */
12494 ** An instance of this structure represents a set of one or more CTEs
12495 ** (common table expressions) created by a single WITH clause.
12497 struct With {
12498 int nCte; /* Number of CTEs in the WITH clause */
12499 With *pOuter; /* Containing WITH clause, or NULL */
12500 struct Cte { /* For each CTE in the WITH clause.... */
12501 char *zName; /* Name of this CTE */
12502 ExprList *pCols; /* List of explicit column names, or NULL */
12503 Select *pSelect; /* The definition of this CTE */
12504 const char *zErr; /* Error message for circular references */
12505 } a[1];
12508 #ifdef SQLITE_DEBUG
12510 ** An instance of the TreeView object is used for printing the content of
12511 ** data structures on sqlite3DebugPrintf() using a tree-like view.
12513 struct TreeView {
12514 int iLevel; /* Which level of the tree we are on */
12515 u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
12517 #endif /* SQLITE_DEBUG */
12520 ** Assuming zIn points to the first byte of a UTF-8 character,
12521 ** advance zIn to point to the first byte of the next UTF-8 character.
12523 #define SQLITE_SKIP_UTF8(zIn) { \
12524 if( (*(zIn++))>=0xc0 ){ \
12525 while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
12530 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
12531 ** the same name but without the _BKPT suffix. These macros invoke
12532 ** routines that report the line-number on which the error originated
12533 ** using sqlite3_log(). The routines also provide a convenient place
12534 ** to set a debugger breakpoint.
12536 SQLITE_PRIVATE int sqlite3CorruptError(int);
12537 SQLITE_PRIVATE int sqlite3MisuseError(int);
12538 SQLITE_PRIVATE int sqlite3CantopenError(int);
12539 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
12540 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
12541 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
12545 ** FTS4 is really an extension for FTS3. It is enabled using the
12546 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
12547 ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
12549 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
12550 # define SQLITE_ENABLE_FTS3
12551 #endif
12554 ** The ctype.h header is needed for non-ASCII systems. It is also
12555 ** needed by FTS3 when FTS3 is included in the amalgamation.
12557 #if !defined(SQLITE_ASCII) || \
12558 (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
12559 # include <ctype.h>
12560 #endif
12563 ** The CoreServices.h and CoreFoundation.h headers are needed for excluding a
12564 ** -journal file from Time Machine backups when its associated database has
12565 ** previously been excluded by the client code.
12567 #if defined(__APPLE__)
12568 #include <CoreServices/CoreServices.h>
12569 #include <CoreFoundation/CoreFoundation.h>
12570 #endif
12573 ** The following macros mimic the standard library functions toupper(),
12574 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
12575 ** sqlite versions only work for ASCII characters, regardless of locale.
12577 #ifdef SQLITE_ASCII
12578 # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
12579 # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
12580 # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
12581 # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
12582 # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
12583 # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
12584 # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
12585 #else
12586 # define sqlite3Toupper(x) toupper((unsigned char)(x))
12587 # define sqlite3Isspace(x) isspace((unsigned char)(x))
12588 # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
12589 # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
12590 # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
12591 # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
12592 # define sqlite3Tolower(x) tolower((unsigned char)(x))
12593 #endif
12594 SQLITE_PRIVATE int sqlite3IsIdChar(u8);
12597 ** Internal function prototypes
12599 #define sqlite3StrICmp sqlite3_stricmp
12600 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
12601 #define sqlite3StrNICmp sqlite3_strnicmp
12603 SQLITE_PRIVATE int sqlite3MallocInit(void);
12604 SQLITE_PRIVATE void sqlite3MallocEnd(void);
12605 SQLITE_PRIVATE void *sqlite3Malloc(u64);
12606 SQLITE_PRIVATE void *sqlite3MallocZero(u64);
12607 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
12608 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
12609 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
12610 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
12611 SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
12612 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
12613 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
12614 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
12615 SQLITE_PRIVATE int sqlite3MallocSize(void*);
12616 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
12617 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
12618 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
12619 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
12620 SQLITE_PRIVATE void sqlite3PageFree(void*);
12621 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
12622 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
12623 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
12626 ** On systems with ample stack space and that support alloca(), make
12627 ** use of alloca() to obtain space for large automatic objects. By default,
12628 ** obtain space from malloc().
12630 ** The alloca() routine never returns NULL. This will cause code paths
12631 ** that deal with sqlite3StackAlloc() failures to be unreachable.
12633 #ifdef SQLITE_USE_ALLOCA
12634 # define sqlite3StackAllocRaw(D,N) alloca(N)
12635 # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
12636 # define sqlite3StackFree(D,P)
12637 #else
12638 # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
12639 # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
12640 # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
12641 #endif
12643 #ifdef SQLITE_ENABLE_MEMSYS3
12644 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
12645 #endif
12646 #ifdef SQLITE_ENABLE_MEMSYS5
12647 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
12648 #endif
12651 #ifndef SQLITE_MUTEX_OMIT
12652 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
12653 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
12654 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
12655 SQLITE_PRIVATE int sqlite3MutexInit(void);
12656 SQLITE_PRIVATE int sqlite3MutexEnd(void);
12657 #endif
12659 SQLITE_PRIVATE int sqlite3StatusValue(int);
12660 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
12661 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
12663 #ifndef SQLITE_OMIT_FLOATING_POINT
12664 SQLITE_PRIVATE int sqlite3IsNaN(double);
12665 #else
12666 # define sqlite3IsNaN(X) 0
12667 #endif
12670 ** An instance of the following structure holds information about SQL
12671 ** functions arguments that are the parameters to the printf() function.
12673 struct PrintfArguments {
12674 int nArg; /* Total number of arguments */
12675 int nUsed; /* Number of arguments used so far */
12676 sqlite3_value **apArg; /* The argument values */
12679 #define SQLITE_PRINTF_INTERNAL 0x01
12680 #define SQLITE_PRINTF_SQLFUNC 0x02
12681 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, u32, const char*, va_list);
12682 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, u32, const char*, ...);
12683 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
12684 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
12685 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
12686 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
12687 SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
12688 #endif
12689 #if defined(SQLITE_TEST)
12690 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
12691 #endif
12693 #if defined(SQLITE_DEBUG)
12694 SQLITE_PRIVATE TreeView *sqlite3TreeViewPush(TreeView*,u8);
12695 SQLITE_PRIVATE void sqlite3TreeViewPop(TreeView*);
12696 SQLITE_PRIVATE void sqlite3TreeViewLine(TreeView*, const char*, ...);
12697 SQLITE_PRIVATE void sqlite3TreeViewItem(TreeView*, const char*, u8);
12698 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
12699 SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
12700 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
12701 #endif
12704 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
12705 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
12706 SQLITE_PRIVATE int sqlite3Dequote(char*);
12707 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
12708 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
12709 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
12710 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
12711 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
12712 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
12713 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
12714 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
12715 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
12716 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
12717 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
12718 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
12719 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
12720 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
12721 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
12722 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
12723 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
12724 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
12725 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
12726 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
12727 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
12728 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
12729 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
12730 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
12731 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
12732 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
12733 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
12734 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
12735 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
12736 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
12737 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
12738 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
12739 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
12740 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
12741 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
12742 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
12743 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
12744 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
12745 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
12746 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
12747 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
12748 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
12749 sqlite3_vfs**,char**,char **);
12750 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
12751 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
12753 #ifdef SQLITE_OMIT_BUILTIN_TEST
12754 # define sqlite3FaultSim(X) SQLITE_OK
12755 #else
12756 SQLITE_PRIVATE int sqlite3FaultSim(int);
12757 #endif
12759 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
12760 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
12761 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
12762 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
12763 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
12764 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
12765 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
12767 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
12768 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
12769 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
12770 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
12771 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
12773 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
12775 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
12776 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
12777 #else
12778 # define sqlite3ViewGetColumnNames(A,B) 0
12779 #endif
12781 #if SQLITE_MAX_ATTACHED>30
12782 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
12783 #endif
12784 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
12785 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
12786 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
12787 #ifndef SQLITE_OMIT_AUTOINCREMENT
12788 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
12789 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
12790 #else
12791 # define sqlite3AutoincrementBegin(X)
12792 # define sqlite3AutoincrementEnd(X)
12793 #endif
12794 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
12795 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
12796 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
12797 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
12798 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
12799 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
12800 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
12801 Token*, Select*, Expr*, IdList*);
12802 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
12803 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
12804 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
12805 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
12806 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
12807 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
12808 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
12809 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
12810 Expr*, int, int);
12811 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
12812 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
12813 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
12814 Expr*,ExprList*,u16,Expr*,Expr*);
12815 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
12816 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
12817 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
12818 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
12819 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
12820 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
12821 #endif
12822 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
12823 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
12824 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
12825 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
12826 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
12827 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
12828 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
12829 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
12830 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
12831 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
12832 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
12833 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
12834 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
12835 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
12836 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
12837 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
12838 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
12839 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
12840 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
12841 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
12842 SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
12843 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
12844 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
12845 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
12846 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
12847 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
12848 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, u8);
12849 #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
12850 #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
12851 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
12852 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
12853 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
12854 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
12855 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
12856 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
12857 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
12858 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
12859 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
12860 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
12861 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
12862 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
12863 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
12864 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
12865 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
12866 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
12867 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
12868 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
12869 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
12870 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
12871 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
12872 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
12873 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
12874 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
12875 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
12876 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
12877 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
12878 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
12879 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
12880 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
12881 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
12882 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
12883 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
12884 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
12885 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
12886 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
12887 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8);
12888 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*);
12889 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
12890 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
12891 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
12892 u8,u8,int,int*);
12893 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
12894 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, u8*, int*, int*);
12895 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
12896 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
12897 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
12898 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
12899 SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
12900 SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
12901 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
12902 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
12903 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
12904 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
12905 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
12906 #if SELECTTRACE_ENABLED
12907 SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
12908 #else
12909 # define sqlite3SelectSetName(A,B)
12910 #endif
12911 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
12912 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
12913 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
12914 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
12915 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
12916 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
12917 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
12918 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
12920 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
12921 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
12922 #endif
12924 #ifndef SQLITE_OMIT_TRIGGER
12925 SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
12926 Expr*,int, int);
12927 SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
12928 SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
12929 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
12930 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
12931 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
12932 SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
12933 int, int, int);
12934 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
12935 void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
12936 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
12937 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
12938 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
12939 Select*,u8);
12940 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
12941 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
12942 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
12943 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
12944 SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
12945 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
12946 #else
12947 # define sqlite3TriggersExist(B,C,D,E,F) 0
12948 # define sqlite3DeleteTrigger(A,B)
12949 # define sqlite3DropTriggerPtr(A,B)
12950 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
12951 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
12952 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
12953 # define sqlite3TriggerList(X, Y) 0
12954 # define sqlite3ParseToplevel(p) p
12955 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
12956 #endif
12958 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
12959 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
12960 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
12961 #ifndef SQLITE_OMIT_AUTHORIZATION
12962 SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
12963 SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
12964 SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
12965 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
12966 SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
12967 #else
12968 # define sqlite3AuthRead(a,b,c,d)
12969 # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
12970 # define sqlite3AuthContextPush(a,b,c)
12971 # define sqlite3AuthContextPop(a) ((void)(a))
12972 #endif
12973 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
12974 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
12975 SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
12976 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
12977 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
12978 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
12979 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
12980 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
12981 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
12982 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
12983 SQLITE_PRIVATE int sqlite3Atoi(const char*);
12984 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
12985 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
12986 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
12987 SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
12988 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
12989 #ifndef SQLITE_OMIT_VIRTUALTABLE
12990 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
12991 #endif
12992 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
12995 ** Routines to read and write variable-length integers. These used to
12996 ** be defined locally, but now we use the varint routines in the util.c
12997 ** file.
12999 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
13000 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
13001 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
13002 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
13005 ** The common case is for a varint to be a single byte. They following
13006 ** macros handle the common case without a procedure call, but then call
13007 ** the procedure for larger varints.
13009 #define getVarint32(A,B) \
13010 (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
13011 #define putVarint32(A,B) \
13012 (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
13013 sqlite3PutVarint((A),(B)))
13014 #define getVarint sqlite3GetVarint
13015 #define putVarint sqlite3PutVarint
13018 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
13019 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
13020 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
13021 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
13022 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
13023 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
13024 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
13025 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
13026 SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
13027 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
13028 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
13029 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
13031 #if defined(SQLITE_TEST)
13032 SQLITE_PRIVATE const char *sqlite3ErrName(int);
13033 #endif
13035 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
13036 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
13037 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
13038 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
13039 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
13040 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
13041 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
13042 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
13043 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
13044 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
13045 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
13046 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
13047 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
13048 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
13049 SQLITE_PRIVATE int sqlite3AbsInt32(int);
13050 #ifdef SQLITE_ENABLE_8_3_NAMES
13051 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
13052 #else
13053 # define sqlite3FileSuffix3(X,Y)
13054 #endif
13055 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
13057 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
13058 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
13059 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
13060 void(*)(void*));
13061 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
13062 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
13063 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
13064 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
13065 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
13066 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
13067 #ifndef SQLITE_AMALGAMATION
13068 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
13069 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
13070 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
13071 SQLITE_PRIVATE const Token sqlite3IntTokens[];
13072 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
13073 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
13074 #ifndef SQLITE_OMIT_WSD
13075 SQLITE_PRIVATE int sqlite3PendingByte;
13076 #endif
13077 #endif
13078 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
13079 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
13080 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
13081 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
13082 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
13083 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
13084 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
13085 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
13086 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
13087 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
13088 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
13089 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
13090 SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
13091 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
13092 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
13093 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
13094 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
13095 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
13096 SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
13097 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
13098 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
13099 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
13100 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
13101 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
13102 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
13103 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
13104 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
13105 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
13106 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
13107 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
13108 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
13109 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
13110 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
13111 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
13112 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
13113 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
13114 #ifdef SQLITE_DEBUG
13115 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
13116 #endif
13117 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
13118 void (*)(sqlite3_context*,int,sqlite3_value **),
13119 void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
13120 FuncDestructor *pDestructor
13122 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
13123 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
13125 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
13126 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
13127 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
13128 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
13129 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
13130 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
13131 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
13132 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
13134 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
13135 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
13137 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
13138 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
13139 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
13140 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
13141 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
13142 SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
13143 #endif
13146 ** The interface to the LEMON-generated parser
13148 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
13149 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
13150 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
13151 #ifdef YYTRACKMAXSTACKDEPTH
13152 SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
13153 #endif
13155 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
13156 #ifndef SQLITE_OMIT_LOAD_EXTENSION
13157 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
13158 #else
13159 # define sqlite3CloseExtensions(X)
13160 #endif
13162 #ifndef SQLITE_OMIT_SHARED_CACHE
13163 SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
13164 #else
13165 #define sqlite3TableLock(v,w,x,y,z)
13166 #endif
13168 #ifdef SQLITE_TEST
13169 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
13170 #endif
13172 #ifdef SQLITE_OMIT_VIRTUALTABLE
13173 # define sqlite3VtabClear(Y)
13174 # define sqlite3VtabSync(X,Y) SQLITE_OK
13175 # define sqlite3VtabRollback(X)
13176 # define sqlite3VtabCommit(X)
13177 # define sqlite3VtabInSync(db) 0
13178 # define sqlite3VtabLock(X)
13179 # define sqlite3VtabUnlock(X)
13180 # define sqlite3VtabUnlockList(X)
13181 # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
13182 # define sqlite3GetVTable(X,Y) ((VTable*)0)
13183 #else
13184 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
13185 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
13186 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
13187 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
13188 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
13189 SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
13190 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
13191 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
13192 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
13193 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
13194 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
13195 # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
13196 #endif
13197 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
13198 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
13199 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
13200 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
13201 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
13202 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
13203 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
13204 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
13205 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
13206 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
13207 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
13208 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
13209 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
13210 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
13211 SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
13212 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
13213 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
13214 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
13215 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
13216 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
13217 #ifndef SQLITE_OMIT_WAL
13218 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
13219 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
13220 #endif
13221 #ifndef SQLITE_OMIT_CTE
13222 SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
13223 SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
13224 SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
13225 #else
13226 #define sqlite3WithPush(x,y,z)
13227 #define sqlite3WithDelete(x,y)
13228 #endif
13230 /* Declarations for functions in fkey.c. All of these are replaced by
13231 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
13232 ** key functionality is available. If OMIT_TRIGGER is defined but
13233 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
13234 ** this case foreign keys are parsed, but no other functionality is
13235 ** provided (enforcement of FK constraints requires the triggers sub-system).
13237 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
13238 SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
13239 SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
13240 SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
13241 SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
13242 SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
13243 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
13244 #else
13245 #define sqlite3FkActions(a,b,c,d,e,f)
13246 #define sqlite3FkCheck(a,b,c,d,e,f)
13247 #define sqlite3FkDropTable(a,b,c)
13248 #define sqlite3FkOldmask(a,b) 0
13249 #define sqlite3FkRequired(a,b,c,d) 0
13250 #endif
13251 #ifndef SQLITE_OMIT_FOREIGN_KEY
13252 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
13253 SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
13254 #else
13255 #define sqlite3FkDelete(a,b)
13256 #define sqlite3FkLocateIndex(a,b,c,d,e)
13257 #endif
13261 ** Available fault injectors. Should be numbered beginning with 0.
13263 #define SQLITE_FAULTINJECTOR_MALLOC 0
13264 #define SQLITE_FAULTINJECTOR_COUNT 1
13267 ** The interface to the code in fault.c used for identifying "benign"
13268 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
13269 ** is not defined.
13271 #ifndef SQLITE_OMIT_BUILTIN_TEST
13272 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
13273 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
13274 #else
13275 #define sqlite3BeginBenignMalloc()
13276 #define sqlite3EndBenignMalloc()
13277 #endif
13280 ** Allowed return values from sqlite3FindInIndex()
13282 #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
13283 #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
13284 #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
13285 #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
13286 #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
13288 ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
13290 #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
13291 #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
13292 #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
13293 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
13295 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
13296 SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
13297 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
13298 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
13299 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p);
13300 #else
13301 #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
13302 #define sqlite3JournalExists(p) 1
13303 #endif
13305 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
13306 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
13307 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
13309 #if SQLITE_MAX_EXPR_DEPTH>0
13310 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
13311 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
13312 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
13313 #else
13314 #define sqlite3ExprSetHeight(x,y)
13315 #define sqlite3SelectExprHeight(x) 0
13316 #define sqlite3ExprCheckHeight(x,y)
13317 #endif
13319 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
13320 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
13322 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
13323 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
13324 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
13325 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
13326 #else
13327 #define sqlite3ConnectionBlocked(x,y)
13328 #define sqlite3ConnectionUnlocked(x)
13329 #define sqlite3ConnectionClosed(x)
13330 #endif
13332 #ifdef SQLITE_DEBUG
13333 SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
13334 #endif
13337 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
13338 ** sqlite3IoTrace is a pointer to a printf-like routine used to
13339 ** print I/O tracing messages.
13341 #ifdef SQLITE_ENABLE_IOTRACE
13342 # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
13343 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
13344 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
13345 #else
13346 # define IOTRACE(A)
13347 # define sqlite3VdbeIOTraceSql(X)
13348 #endif
13351 ** These routines are available for the mem2.c debugging memory allocator
13352 ** only. They are used to verify that different "types" of memory
13353 ** allocations are properly tracked by the system.
13355 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
13356 ** the MEMTYPE_* macros defined below. The type must be a bitmask with
13357 ** a single bit set.
13359 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
13360 ** argument match the type set by the previous sqlite3MemdebugSetType().
13361 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
13363 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
13364 ** argument match the type set by the previous sqlite3MemdebugSetType().
13366 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
13367 ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
13368 ** it might have been allocated by lookaside, except the allocation was
13369 ** too large or lookaside was already full. It is important to verify
13370 ** that allocations that might have been satisfied by lookaside are not
13371 ** passed back to non-lookaside free() routines. Asserts such as the
13372 ** example above are placed on the non-lookaside free() routines to verify
13373 ** this constraint.
13375 ** All of this is no-op for a production build. It only comes into
13376 ** play when the SQLITE_MEMDEBUG compile-time option is used.
13378 #ifdef SQLITE_MEMDEBUG
13379 SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
13380 SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
13381 SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
13382 #else
13383 # define sqlite3MemdebugSetType(X,Y) /* no-op */
13384 # define sqlite3MemdebugHasType(X,Y) 1
13385 # define sqlite3MemdebugNoType(X,Y) 1
13386 #endif
13387 #define MEMTYPE_HEAP 0x01 /* General heap allocations */
13388 #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
13389 #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
13390 #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
13393 ** Threading interface
13395 #if SQLITE_MAX_WORKER_THREADS>0
13396 SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
13397 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
13398 #endif
13400 #endif /* _SQLITEINT_H_ */
13402 /************** End of sqliteInt.h *******************************************/
13403 /************** Begin file global.c ******************************************/
13405 ** 2008 June 13
13407 ** The author disclaims copyright to this source code. In place of
13408 ** a legal notice, here is a blessing:
13410 ** May you do good and not evil.
13411 ** May you find forgiveness for yourself and forgive others.
13412 ** May you share freely, never taking more than you give.
13414 *************************************************************************
13416 ** This file contains definitions of global variables and constants.
13419 /* An array to map all upper-case characters into their corresponding
13420 ** lower-case character.
13422 ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
13423 ** handle case conversions for the UTF character set since the tables
13424 ** involved are nearly as big or bigger than SQLite itself.
13426 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
13427 #ifdef SQLITE_ASCII
13428 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
13429 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
13430 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
13431 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
13432 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
13433 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
13434 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
13435 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
13436 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
13437 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
13438 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
13439 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
13440 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
13441 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
13442 252,253,254,255
13443 #endif
13444 #ifdef SQLITE_EBCDIC
13445 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
13446 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
13447 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
13448 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
13449 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
13450 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
13451 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
13452 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
13453 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
13454 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
13455 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
13456 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
13457 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
13458 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
13459 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
13460 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
13461 #endif
13465 ** The following 256 byte lookup table is used to support SQLites built-in
13466 ** equivalents to the following standard library functions:
13468 ** isspace() 0x01
13469 ** isalpha() 0x02
13470 ** isdigit() 0x04
13471 ** isalnum() 0x06
13472 ** isxdigit() 0x08
13473 ** toupper() 0x20
13474 ** SQLite identifier character 0x40
13476 ** Bit 0x20 is set if the mapped character requires translation to upper
13477 ** case. i.e. if the character is a lower-case ASCII character.
13478 ** If x is a lower-case ASCII character, then its upper-case equivalent
13479 ** is (x - 0x20). Therefore toupper() can be implemented as:
13481 ** (x & ~(map[x]&0x20))
13483 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
13484 ** array. tolower() is used more often than toupper() by SQLite.
13486 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
13487 ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
13488 ** non-ASCII UTF character. Hence the test for whether or not a character is
13489 ** part of an identifier is 0x46.
13491 ** SQLite's versions are identical to the standard versions assuming a
13492 ** locale of "C". They are implemented as macros in sqliteInt.h.
13494 #ifdef SQLITE_ASCII
13495 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
13496 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
13497 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
13498 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
13499 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
13500 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
13501 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
13502 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
13503 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
13505 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
13506 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
13507 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
13508 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
13509 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
13510 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
13511 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
13512 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
13514 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
13515 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
13516 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
13517 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
13518 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
13519 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
13520 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
13521 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
13523 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
13524 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
13525 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
13526 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
13527 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
13528 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
13529 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
13530 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
13532 #endif
13534 /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
13535 ** compatibility for legacy applications, the URI filename capability is
13536 ** disabled by default.
13538 ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
13539 ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
13541 #ifndef SQLITE_USE_URI
13542 # define SQLITE_USE_URI 0
13543 #endif
13545 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
13546 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
13547 #endif
13550 ** The following singleton contains the global configuration for
13551 ** the SQLite library.
13553 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
13554 SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
13555 1, /* bCoreMutex */
13556 SQLITE_THREADSAFE==1, /* bFullMutex */
13557 SQLITE_USE_URI, /* bOpenUri */
13558 SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
13559 0x7ffffffe, /* mxStrlen */
13560 0, /* neverCorrupt */
13561 128, /* szLookaside */
13562 500, /* nLookaside */
13563 {0,0,0,0,0,0,0,0}, /* m */
13564 {0,0,0,0,0,0,0,0,0}, /* mutex */
13565 {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
13566 (void*)0, /* pHeap */
13567 0, /* nHeap */
13568 0, 0, /* mnHeap, mxHeap */
13569 SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
13570 SQLITE_MAX_MMAP_SIZE, /* mxMmap */
13571 (void*)0, /* pScratch */
13572 0, /* szScratch */
13573 0, /* nScratch */
13574 (void*)0, /* pPage */
13575 0, /* szPage */
13576 0, /* nPage */
13577 0, /* mxParserStack */
13578 0, /* sharedCacheEnabled */
13579 /* All the rest should always be initialized to zero */
13580 0, /* isInit */
13581 0, /* inProgress */
13582 0, /* isMutexInit */
13583 0, /* isMallocInit */
13584 0, /* isPCacheInit */
13585 0, /* nRefInitMutex */
13586 0, /* pInitMutex */
13587 0, /* xLog */
13588 0, /* pLogArg */
13589 #ifdef SQLITE_ENABLE_SQLLOG
13590 0, /* xSqllog */
13591 0, /* pSqllogArg */
13592 #endif
13593 #ifdef SQLITE_VDBE_COVERAGE
13594 0, /* xVdbeBranch */
13595 0, /* pVbeBranchArg */
13596 #endif
13597 #ifndef SQLITE_OMIT_BUILTIN_TEST
13598 0, /* xTestCallback */
13599 #endif
13600 0 /* bLocaltimeFault */
13604 ** Hash table for global functions - functions common to all
13605 ** database connections. After initialization, this table is
13606 ** read-only.
13608 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
13611 ** Constant tokens for values 0 and 1.
13613 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
13614 { "0", 1 },
13615 { "1", 1 }
13620 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
13621 ** 1-gibabyte boundary) in a compatible database. SQLite never uses
13622 ** the database page that contains the pending byte. It never attempts
13623 ** to read or write that page. The pending byte page is set assign
13624 ** for use by the VFS layers as space for managing file locks.
13626 ** During testing, it is often desirable to move the pending byte to
13627 ** a different position in the file. This allows code that has to
13628 ** deal with the pending byte to run on files that are much smaller
13629 ** than 1 GiB. The sqlite3_test_control() interface can be used to
13630 ** move the pending byte.
13632 ** IMPORTANT: Changing the pending byte to any value other than
13633 ** 0x40000000 results in an incompatible database file format!
13634 ** Changing the pending byte during operating results in undefined
13635 ** and dileterious behavior.
13637 #ifndef SQLITE_OMIT_WSD
13638 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
13639 #endif
13642 ** Properties of opcodes. The OPFLG_INITIALIZER macro is
13643 ** created by mkopcodeh.awk during compilation. Data is obtained
13644 ** from the comments following the "case OP_xxxx:" statements in
13645 ** the vdbe.c file.
13647 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
13649 /************** End of global.c **********************************************/
13650 /************** Begin file ctime.c *******************************************/
13652 ** 2010 February 23
13654 ** The author disclaims copyright to this source code. In place of
13655 ** a legal notice, here is a blessing:
13657 ** May you do good and not evil.
13658 ** May you find forgiveness for yourself and forgive others.
13659 ** May you share freely, never taking more than you give.
13661 *************************************************************************
13663 ** This file implements routines used to report what compile-time options
13664 ** SQLite was built with.
13667 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
13671 ** An array of names of all compile-time options. This array should
13672 ** be sorted A-Z.
13674 ** This array looks large, but in a typical installation actually uses
13675 ** only a handful of compile-time options, so most times this array is usually
13676 ** rather short and uses little memory space.
13678 static const char * const azCompileOpt[] = {
13680 /* These macros are provided to "stringify" the value of the define
13681 ** for those options in which the value is meaningful. */
13682 #define CTIMEOPT_VAL_(opt) #opt
13683 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
13685 #ifdef SQLITE_32BIT_ROWID
13686 "32BIT_ROWID",
13687 #endif
13688 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
13689 "4_BYTE_ALIGNED_MALLOC",
13690 #endif
13691 #ifdef SQLITE_CASE_SENSITIVE_LIKE
13692 "CASE_SENSITIVE_LIKE",
13693 #endif
13694 #ifdef SQLITE_CHECK_PAGES
13695 "CHECK_PAGES",
13696 #endif
13697 #ifdef SQLITE_COVERAGE_TEST
13698 "COVERAGE_TEST",
13699 #endif
13700 #ifdef SQLITE_DEBUG
13701 "DEBUG",
13702 #endif
13703 #ifdef SQLITE_DEFAULT_LOCKING_MODE
13704 "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
13705 #endif
13706 #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
13707 "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
13708 #endif
13709 #ifdef SQLITE_DISABLE_DIRSYNC
13710 "DISABLE_DIRSYNC",
13711 #endif
13712 #ifdef SQLITE_DISABLE_LFS
13713 "DISABLE_LFS",
13714 #endif
13715 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
13716 "ENABLE_ATOMIC_WRITE",
13717 #endif
13718 #ifdef SQLITE_ENABLE_CEROD
13719 "ENABLE_CEROD",
13720 #endif
13721 #ifdef SQLITE_ENABLE_COLUMN_METADATA
13722 "ENABLE_COLUMN_METADATA",
13723 #endif
13724 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
13725 "ENABLE_EXPENSIVE_ASSERT",
13726 #endif
13727 #ifdef SQLITE_ENABLE_FTS1
13728 "ENABLE_FTS1",
13729 #endif
13730 #ifdef SQLITE_ENABLE_FTS2
13731 "ENABLE_FTS2",
13732 #endif
13733 #ifdef SQLITE_ENABLE_FTS3
13734 "ENABLE_FTS3",
13735 #endif
13736 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
13737 "ENABLE_FTS3_PARENTHESIS",
13738 #endif
13739 #ifdef SQLITE_ENABLE_FTS4
13740 "ENABLE_FTS4",
13741 #endif
13742 #ifdef SQLITE_ENABLE_ICU
13743 "ENABLE_ICU",
13744 #endif
13745 #ifdef SQLITE_ENABLE_IOTRACE
13746 "ENABLE_IOTRACE",
13747 #endif
13748 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
13749 "ENABLE_LOAD_EXTENSION",
13750 #endif
13751 #ifdef SQLITE_ENABLE_LOCKING_STYLE
13752 "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
13753 #endif
13754 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
13755 "ENABLE_MEMORY_MANAGEMENT",
13756 #endif
13757 #ifdef SQLITE_ENABLE_MEMSYS3
13758 "ENABLE_MEMSYS3",
13759 #endif
13760 #ifdef SQLITE_ENABLE_MEMSYS5
13761 "ENABLE_MEMSYS5",
13762 #endif
13763 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
13764 "ENABLE_OVERSIZE_CELL_CHECK",
13765 #endif
13766 #ifdef SQLITE_ENABLE_RTREE
13767 "ENABLE_RTREE",
13768 #endif
13769 #if defined(SQLITE_ENABLE_STAT4)
13770 "ENABLE_STAT4",
13771 #elif defined(SQLITE_ENABLE_STAT3)
13772 "ENABLE_STAT3",
13773 #endif
13774 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
13775 "ENABLE_UNLOCK_NOTIFY",
13776 #endif
13777 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
13778 "ENABLE_UPDATE_DELETE_LIMIT",
13779 #endif
13780 #ifdef SQLITE_HAS_CODEC
13781 "HAS_CODEC",
13782 #endif
13783 #ifdef SQLITE_HAVE_ISNAN
13784 "HAVE_ISNAN",
13785 #endif
13786 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
13787 "HOMEGROWN_RECURSIVE_MUTEX",
13788 #endif
13789 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
13790 "IGNORE_AFP_LOCK_ERRORS",
13791 #endif
13792 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
13793 "IGNORE_FLOCK_LOCK_ERRORS",
13794 #endif
13795 #ifdef SQLITE_INT64_TYPE
13796 "INT64_TYPE",
13797 #endif
13798 #ifdef SQLITE_LOCK_TRACE
13799 "LOCK_TRACE",
13800 #endif
13801 #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
13802 "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
13803 #endif
13804 #ifdef SQLITE_MAX_SCHEMA_RETRY
13805 "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
13806 #endif
13807 #ifdef SQLITE_MEMDEBUG
13808 "MEMDEBUG",
13809 #endif
13810 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
13811 "MIXED_ENDIAN_64BIT_FLOAT",
13812 #endif
13813 #ifdef SQLITE_NO_SYNC
13814 "NO_SYNC",
13815 #endif
13816 #ifdef SQLITE_OMIT_ALTERTABLE
13817 "OMIT_ALTERTABLE",
13818 #endif
13819 #ifdef SQLITE_OMIT_ANALYZE
13820 "OMIT_ANALYZE",
13821 #endif
13822 #ifdef SQLITE_OMIT_ATTACH
13823 "OMIT_ATTACH",
13824 #endif
13825 #ifdef SQLITE_OMIT_AUTHORIZATION
13826 "OMIT_AUTHORIZATION",
13827 #endif
13828 #ifdef SQLITE_OMIT_AUTOINCREMENT
13829 "OMIT_AUTOINCREMENT",
13830 #endif
13831 #ifdef SQLITE_OMIT_AUTOINIT
13832 "OMIT_AUTOINIT",
13833 #endif
13834 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
13835 "OMIT_AUTOMATIC_INDEX",
13836 #endif
13837 #ifdef SQLITE_OMIT_AUTORESET
13838 "OMIT_AUTORESET",
13839 #endif
13840 #ifdef SQLITE_OMIT_AUTOVACUUM
13841 "OMIT_AUTOVACUUM",
13842 #endif
13843 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
13844 "OMIT_BETWEEN_OPTIMIZATION",
13845 #endif
13846 #ifdef SQLITE_OMIT_BLOB_LITERAL
13847 "OMIT_BLOB_LITERAL",
13848 #endif
13849 #ifdef SQLITE_OMIT_BTREECOUNT
13850 "OMIT_BTREECOUNT",
13851 #endif
13852 #ifdef SQLITE_OMIT_BUILTIN_TEST
13853 "OMIT_BUILTIN_TEST",
13854 #endif
13855 #ifdef SQLITE_OMIT_CAST
13856 "OMIT_CAST",
13857 #endif
13858 #ifdef SQLITE_OMIT_CHECK
13859 "OMIT_CHECK",
13860 #endif
13861 #ifdef SQLITE_OMIT_COMPLETE
13862 "OMIT_COMPLETE",
13863 #endif
13864 #ifdef SQLITE_OMIT_COMPOUND_SELECT
13865 "OMIT_COMPOUND_SELECT",
13866 #endif
13867 #ifdef SQLITE_OMIT_CTE
13868 "OMIT_CTE",
13869 #endif
13870 #ifdef SQLITE_OMIT_DATETIME_FUNCS
13871 "OMIT_DATETIME_FUNCS",
13872 #endif
13873 #ifdef SQLITE_OMIT_DECLTYPE
13874 "OMIT_DECLTYPE",
13875 #endif
13876 #ifdef SQLITE_OMIT_DEPRECATED
13877 "OMIT_DEPRECATED",
13878 #endif
13879 #ifdef SQLITE_OMIT_DISKIO
13880 "OMIT_DISKIO",
13881 #endif
13882 #ifdef SQLITE_OMIT_EXPLAIN
13883 "OMIT_EXPLAIN",
13884 #endif
13885 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
13886 "OMIT_FLAG_PRAGMAS",
13887 #endif
13888 #ifdef SQLITE_OMIT_FLOATING_POINT
13889 "OMIT_FLOATING_POINT",
13890 #endif
13891 #ifdef SQLITE_OMIT_FOREIGN_KEY
13892 "OMIT_FOREIGN_KEY",
13893 #endif
13894 #ifdef SQLITE_OMIT_GET_TABLE
13895 "OMIT_GET_TABLE",
13896 #endif
13897 #ifdef SQLITE_OMIT_INCRBLOB
13898 "OMIT_INCRBLOB",
13899 #endif
13900 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
13901 "OMIT_INTEGRITY_CHECK",
13902 #endif
13903 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
13904 "OMIT_LIKE_OPTIMIZATION",
13905 #endif
13906 #ifdef SQLITE_OMIT_LOAD_EXTENSION
13907 "OMIT_LOAD_EXTENSION",
13908 #endif
13909 #ifdef SQLITE_OMIT_LOCALTIME
13910 "OMIT_LOCALTIME",
13911 #endif
13912 #ifdef SQLITE_OMIT_LOOKASIDE
13913 "OMIT_LOOKASIDE",
13914 #endif
13915 #ifdef SQLITE_OMIT_MEMORYDB
13916 "OMIT_MEMORYDB",
13917 #endif
13918 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
13919 "OMIT_OR_OPTIMIZATION",
13920 #endif
13921 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
13922 "OMIT_PAGER_PRAGMAS",
13923 #endif
13924 #ifdef SQLITE_OMIT_PRAGMA
13925 "OMIT_PRAGMA",
13926 #endif
13927 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
13928 "OMIT_PROGRESS_CALLBACK",
13929 #endif
13930 #ifdef SQLITE_OMIT_QUICKBALANCE
13931 "OMIT_QUICKBALANCE",
13932 #endif
13933 #ifdef SQLITE_OMIT_REINDEX
13934 "OMIT_REINDEX",
13935 #endif
13936 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
13937 "OMIT_SCHEMA_PRAGMAS",
13938 #endif
13939 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
13940 "OMIT_SCHEMA_VERSION_PRAGMAS",
13941 #endif
13942 #ifdef SQLITE_OMIT_SHARED_CACHE
13943 "OMIT_SHARED_CACHE",
13944 #endif
13945 #ifdef SQLITE_OMIT_SUBQUERY
13946 "OMIT_SUBQUERY",
13947 #endif
13948 #ifdef SQLITE_OMIT_TCL_VARIABLE
13949 "OMIT_TCL_VARIABLE",
13950 #endif
13951 #ifdef SQLITE_OMIT_TEMPDB
13952 "OMIT_TEMPDB",
13953 #endif
13954 #ifdef SQLITE_OMIT_TRACE
13955 "OMIT_TRACE",
13956 #endif
13957 #ifdef SQLITE_OMIT_TRIGGER
13958 "OMIT_TRIGGER",
13959 #endif
13960 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
13961 "OMIT_TRUNCATE_OPTIMIZATION",
13962 #endif
13963 #ifdef SQLITE_OMIT_UTF16
13964 "OMIT_UTF16",
13965 #endif
13966 #ifdef SQLITE_OMIT_VACUUM
13967 "OMIT_VACUUM",
13968 #endif
13969 #ifdef SQLITE_OMIT_VIEW
13970 "OMIT_VIEW",
13971 #endif
13972 #ifdef SQLITE_OMIT_VIRTUALTABLE
13973 "OMIT_VIRTUALTABLE",
13974 #endif
13975 #ifdef SQLITE_OMIT_WAL
13976 "OMIT_WAL",
13977 #endif
13978 #ifdef SQLITE_OMIT_WSD
13979 "OMIT_WSD",
13980 #endif
13981 #ifdef SQLITE_OMIT_XFER_OPT
13982 "OMIT_XFER_OPT",
13983 #endif
13984 #ifdef SQLITE_PERFORMANCE_TRACE
13985 "PERFORMANCE_TRACE",
13986 #endif
13987 #ifdef SQLITE_PROXY_DEBUG
13988 "PROXY_DEBUG",
13989 #endif
13990 #ifdef SQLITE_RTREE_INT_ONLY
13991 "RTREE_INT_ONLY",
13992 #endif
13993 #ifdef SQLITE_SECURE_DELETE
13994 "SECURE_DELETE",
13995 #endif
13996 #ifdef SQLITE_SMALL_STACK
13997 "SMALL_STACK",
13998 #endif
13999 #ifdef SQLITE_SOUNDEX
14000 "SOUNDEX",
14001 #endif
14002 #ifdef SQLITE_SYSTEM_MALLOC
14003 "SYSTEM_MALLOC",
14004 #endif
14005 #ifdef SQLITE_TCL
14006 "TCL",
14007 #endif
14008 #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
14009 "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
14010 #endif
14011 #ifdef SQLITE_TEST
14012 "TEST",
14013 #endif
14014 #if defined(SQLITE_THREADSAFE)
14015 "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
14016 #endif
14017 #ifdef SQLITE_USE_ALLOCA
14018 "USE_ALLOCA",
14019 #endif
14020 #ifdef SQLITE_USER_AUTHENTICATION
14021 "USER_AUTHENTICATION",
14022 #endif
14023 #ifdef SQLITE_WIN32_MALLOC
14024 "WIN32_MALLOC",
14025 #endif
14026 #ifdef SQLITE_ZERO_MALLOC
14027 "ZERO_MALLOC"
14028 #endif
14032 ** Given the name of a compile-time option, return true if that option
14033 ** was used and false if not.
14035 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
14036 ** is not required for a match.
14038 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
14039 int i, n;
14040 if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
14041 n = sqlite3Strlen30(zOptName);
14043 /* Since ArraySize(azCompileOpt) is normally in single digits, a
14044 ** linear search is adequate. No need for a binary search. */
14045 for(i=0; i<ArraySize(azCompileOpt); i++){
14046 if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
14047 && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
14049 return 1;
14052 return 0;
14056 ** Return the N-th compile-time option string. If N is out of range,
14057 ** return a NULL pointer.
14059 SQLITE_API const char *sqlite3_compileoption_get(int N){
14060 if( N>=0 && N<ArraySize(azCompileOpt) ){
14061 return azCompileOpt[N];
14063 return 0;
14066 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
14068 /************** End of ctime.c ***********************************************/
14069 /************** Begin file status.c ******************************************/
14071 ** 2008 June 18
14073 ** The author disclaims copyright to this source code. In place of
14074 ** a legal notice, here is a blessing:
14076 ** May you do good and not evil.
14077 ** May you find forgiveness for yourself and forgive others.
14078 ** May you share freely, never taking more than you give.
14080 *************************************************************************
14082 ** This module implements the sqlite3_status() interface and related
14083 ** functionality.
14085 /************** Include vdbeInt.h in the middle of status.c ******************/
14086 /************** Begin file vdbeInt.h *****************************************/
14088 ** 2003 September 6
14090 ** The author disclaims copyright to this source code. In place of
14091 ** a legal notice, here is a blessing:
14093 ** May you do good and not evil.
14094 ** May you find forgiveness for yourself and forgive others.
14095 ** May you share freely, never taking more than you give.
14097 *************************************************************************
14098 ** This is the header file for information that is private to the
14099 ** VDBE. This information used to all be at the top of the single
14100 ** source code file "vdbe.c". When that file became too big (over
14101 ** 6000 lines long) it was split up into several smaller files and
14102 ** this header information was factored out.
14104 #ifndef _VDBEINT_H_
14105 #define _VDBEINT_H_
14108 ** The maximum number of times that a statement will try to reparse
14109 ** itself before giving up and returning SQLITE_SCHEMA.
14111 #ifndef SQLITE_MAX_SCHEMA_RETRY
14112 # define SQLITE_MAX_SCHEMA_RETRY 50
14113 #endif
14116 ** SQL is translated into a sequence of instructions to be
14117 ** executed by a virtual machine. Each instruction is an instance
14118 ** of the following structure.
14120 typedef struct VdbeOp Op;
14123 ** Boolean values
14125 typedef unsigned Bool;
14127 /* Opaque type used by code in vdbesort.c */
14128 typedef struct VdbeSorter VdbeSorter;
14130 /* Opaque type used by the explainer */
14131 typedef struct Explain Explain;
14133 /* Elements of the linked list at Vdbe.pAuxData */
14134 typedef struct AuxData AuxData;
14137 ** A cursor is a pointer into a single BTree within a database file.
14138 ** The cursor can seek to a BTree entry with a particular key, or
14139 ** loop over all entries of the Btree. You can also insert new BTree
14140 ** entries or retrieve the key or data from the entry that the cursor
14141 ** is currently pointing to.
14143 ** Cursors can also point to virtual tables, sorters, or "pseudo-tables".
14144 ** A pseudo-table is a single-row table implemented by registers.
14146 ** Every cursor that the virtual machine has open is represented by an
14147 ** instance of the following structure.
14149 struct VdbeCursor {
14150 BtCursor *pCursor; /* The cursor structure of the backend */
14151 Btree *pBt; /* Separate file holding temporary table */
14152 KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
14153 int seekResult; /* Result of previous sqlite3BtreeMoveto() */
14154 int pseudoTableReg; /* Register holding pseudotable content. */
14155 i16 nField; /* Number of fields in the header */
14156 u16 nHdrParsed; /* Number of header fields parsed so far */
14157 #ifdef SQLITE_DEBUG
14158 u8 seekOp; /* Most recent seek operation on this cursor */
14159 #endif
14160 i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
14161 u8 nullRow; /* True if pointing to a row with no data */
14162 u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
14163 Bool isEphemeral:1; /* True for an ephemeral table */
14164 Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
14165 Bool isTable:1; /* True if a table requiring integer keys */
14166 Bool isOrdered:1; /* True if the underlying table is BTREE_UNORDERED */
14167 Pgno pgnoRoot; /* Root page of the open btree cursor */
14168 sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
14169 i64 seqCount; /* Sequence counter */
14170 i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
14171 VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */
14173 /* Cached information about the header for the data record that the
14174 ** cursor is currently pointing to. Only valid if cacheStatus matches
14175 ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
14176 ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
14177 ** the cache is out of date.
14179 ** aRow might point to (ephemeral) data for the current row, or it might
14180 ** be NULL.
14182 u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
14183 u32 payloadSize; /* Total number of bytes in the record */
14184 u32 szRow; /* Byte available in aRow */
14185 u32 iHdrOffset; /* Offset to next unparsed byte of the header */
14186 const u8 *aRow; /* Data for the current row, if all on one page */
14187 u32 *aOffset; /* Pointer to aType[nField] */
14188 u32 aType[1]; /* Type values for all entries in the record */
14189 /* 2*nField extra array elements allocated for aType[], beyond the one
14190 ** static element declared in the structure. nField total array slots for
14191 ** aType[] and nField+1 array slots for aOffset[] */
14193 typedef struct VdbeCursor VdbeCursor;
14196 ** When a sub-program is executed (OP_Program), a structure of this type
14197 ** is allocated to store the current value of the program counter, as
14198 ** well as the current memory cell array and various other frame specific
14199 ** values stored in the Vdbe struct. When the sub-program is finished,
14200 ** these values are copied back to the Vdbe from the VdbeFrame structure,
14201 ** restoring the state of the VM to as it was before the sub-program
14202 ** began executing.
14204 ** The memory for a VdbeFrame object is allocated and managed by a memory
14205 ** cell in the parent (calling) frame. When the memory cell is deleted or
14206 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
14207 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
14208 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
14209 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
14210 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
14211 ** child frame are released.
14213 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
14214 ** set to NULL if the currently executing frame is the main program.
14216 typedef struct VdbeFrame VdbeFrame;
14217 struct VdbeFrame {
14218 Vdbe *v; /* VM this frame belongs to */
14219 VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
14220 Op *aOp; /* Program instructions for parent frame */
14221 Mem *aMem; /* Array of memory cells for parent frame */
14222 u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
14223 VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
14224 void *token; /* Copy of SubProgram.token */
14225 i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
14226 int nCursor; /* Number of entries in apCsr */
14227 int pc; /* Program Counter in parent (calling) frame */
14228 int nOp; /* Size of aOp array */
14229 int nMem; /* Number of entries in aMem */
14230 int nOnceFlag; /* Number of entries in aOnceFlag */
14231 int nChildMem; /* Number of memory cells for child frame */
14232 int nChildCsr; /* Number of cursors for child frame */
14233 int nChange; /* Statement changes (Vdbe.nChanges) */
14236 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
14239 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
14241 #define CACHE_STALE 0
14244 ** Internally, the vdbe manipulates nearly all SQL values as Mem
14245 ** structures. Each Mem struct may cache multiple representations (string,
14246 ** integer etc.) of the same value.
14248 struct Mem {
14249 union MemValue {
14250 double r; /* Real value used when MEM_Real is set in flags */
14251 i64 i; /* Integer value used when MEM_Int is set in flags */
14252 int nZero; /* Used when bit MEM_Zero is set in flags */
14253 FuncDef *pDef; /* Used only when flags==MEM_Agg */
14254 RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
14255 VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
14256 } u;
14257 u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
14258 u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
14259 int n; /* Number of characters in string value, excluding '\0' */
14260 char *z; /* String or BLOB value */
14261 /* ShallowCopy only needs to copy the information above */
14262 char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
14263 int szMalloc; /* Size of the zMalloc allocation */
14264 u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
14265 sqlite3 *db; /* The associated database connection */
14266 void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
14267 #ifdef SQLITE_DEBUG
14268 Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
14269 void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
14270 #endif
14273 /* One or more of the following flags are set to indicate the validOK
14274 ** representations of the value stored in the Mem struct.
14276 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
14277 ** No other flags may be set in this case.
14279 ** If the MEM_Str flag is set then Mem.z points at a string representation.
14280 ** Usually this is encoded in the same unicode encoding as the main
14281 ** database (see below for exceptions). If the MEM_Term flag is also
14282 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
14283 ** flags may coexist with the MEM_Str flag.
14285 #define MEM_Null 0x0001 /* Value is NULL */
14286 #define MEM_Str 0x0002 /* Value is a string */
14287 #define MEM_Int 0x0004 /* Value is an integer */
14288 #define MEM_Real 0x0008 /* Value is a real number */
14289 #define MEM_Blob 0x0010 /* Value is a BLOB */
14290 #define MEM_AffMask 0x001f /* Mask of affinity bits */
14291 #define MEM_RowSet 0x0020 /* Value is a RowSet object */
14292 #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
14293 #define MEM_Undefined 0x0080 /* Value is undefined */
14294 #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
14295 #define MEM_TypeMask 0x01ff /* Mask of type bits */
14298 /* Whenever Mem contains a valid string or blob representation, one of
14299 ** the following flags must be set to determine the memory management
14300 ** policy for Mem.z. The MEM_Term flag tells us whether or not the
14301 ** string is \000 or \u0000 terminated
14303 #define MEM_Term 0x0200 /* String rep is nul terminated */
14304 #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
14305 #define MEM_Static 0x0800 /* Mem.z points to a static string */
14306 #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
14307 #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
14308 #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
14309 #ifdef SQLITE_OMIT_INCRBLOB
14310 #undef MEM_Zero
14311 #define MEM_Zero 0x0000
14312 #endif
14315 ** Clear any existing type flags from a Mem and replace them with f
14317 #define MemSetTypeFlag(p, f) \
14318 ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
14321 ** Return true if a memory cell is not marked as invalid. This macro
14322 ** is for use inside assert() statements only.
14324 #ifdef SQLITE_DEBUG
14325 #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
14326 #endif
14329 ** Each auxiliary data pointer stored by a user defined function
14330 ** implementation calling sqlite3_set_auxdata() is stored in an instance
14331 ** of this structure. All such structures associated with a single VM
14332 ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
14333 ** when the VM is halted (if not before).
14335 struct AuxData {
14336 int iOp; /* Instruction number of OP_Function opcode */
14337 int iArg; /* Index of function argument. */
14338 void *pAux; /* Aux data pointer */
14339 void (*xDelete)(void *); /* Destructor for the aux data */
14340 AuxData *pNext; /* Next element in list */
14344 ** The "context" argument for an installable function. A pointer to an
14345 ** instance of this structure is the first argument to the routines used
14346 ** implement the SQL functions.
14348 ** There is a typedef for this structure in sqlite.h. So all routines,
14349 ** even the public interface to SQLite, can use a pointer to this structure.
14350 ** But this file is the only place where the internal details of this
14351 ** structure are known.
14353 ** This structure is defined inside of vdbeInt.h because it uses substructures
14354 ** (Mem) which are only defined there.
14356 struct sqlite3_context {
14357 Mem *pOut; /* The return value is stored here */
14358 FuncDef *pFunc; /* Pointer to function information */
14359 Mem *pMem; /* Memory cell used to store aggregate context */
14360 Vdbe *pVdbe; /* The VM that owns this context */
14361 int iOp; /* Instruction number of OP_Function */
14362 int isError; /* Error code returned by the function. */
14363 u8 skipFlag; /* Skip accumulator loading if true */
14364 u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
14368 ** An Explain object accumulates indented output which is helpful
14369 ** in describing recursive data structures.
14371 struct Explain {
14372 Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
14373 StrAccum str; /* The string being accumulated */
14374 int nIndent; /* Number of elements in aIndent */
14375 u16 aIndent[100]; /* Levels of indentation */
14376 char zBase[100]; /* Initial space */
14379 /* A bitfield type for use inside of structures. Always follow with :N where
14380 ** N is the number of bits.
14382 typedef unsigned bft; /* Bit Field Type */
14385 ** An instance of the virtual machine. This structure contains the complete
14386 ** state of the virtual machine.
14388 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
14389 ** is really a pointer to an instance of this structure.
14391 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
14392 ** any virtual table method invocations made by the vdbe program. It is
14393 ** set to 2 for xDestroy method calls and 1 for all other methods. This
14394 ** variable is used for two purposes: to allow xDestroy methods to execute
14395 ** "DROP TABLE" statements and to prevent some nasty side effects of
14396 ** malloc failure when SQLite is invoked recursively by a virtual table
14397 ** method function.
14399 struct Vdbe {
14400 sqlite3 *db; /* The database connection that owns this statement */
14401 Op *aOp; /* Space to hold the virtual machine's program */
14402 Mem *aMem; /* The memory locations */
14403 Mem **apArg; /* Arguments to currently executing user function */
14404 Mem *aColName; /* Column names to return */
14405 Mem *pResultSet; /* Pointer to an array of results */
14406 Parse *pParse; /* Parsing context used to create this Vdbe */
14407 int nMem; /* Number of memory locations currently allocated */
14408 int nOp; /* Number of instructions in the program */
14409 int nCursor; /* Number of slots in apCsr[] */
14410 u32 magic; /* Magic number for sanity checking */
14411 char *zErrMsg; /* Error message written here */
14412 Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
14413 VdbeCursor **apCsr; /* One element of this array for each open cursor */
14414 Mem *aVar; /* Values for the OP_Variable opcode. */
14415 char **azVar; /* Name of variables */
14416 ynVar nVar; /* Number of entries in aVar[] */
14417 ynVar nzVar; /* Number of entries in azVar[] */
14418 u32 cacheCtr; /* VdbeCursor row cache generation counter */
14419 int pc; /* The program counter */
14420 int rc; /* Value to return */
14421 u16 nResColumn; /* Number of columns in one row of the result set */
14422 u8 errorAction; /* Recovery action to do in case of an error */
14423 u8 minWriteFileFormat; /* Minimum file format for writable database files */
14424 bft explain:2; /* True if EXPLAIN present on SQL command */
14425 bft inVtabMethod:2; /* See comments above */
14426 bft changeCntOn:1; /* True to update the change-counter */
14427 bft expired:1; /* True if the VM needs to be recompiled */
14428 bft runOnlyOnce:1; /* Automatically expire on reset */
14429 bft usesStmtJournal:1; /* True if uses a statement journal */
14430 bft readOnly:1; /* True for statements that do not write */
14431 bft bIsReader:1; /* True for statements that read */
14432 bft isPrepareV2:1; /* True if prepared with prepare_v2() */
14433 bft doingRerun:1; /* True if rerunning after an auto-reprepare */
14434 int nChange; /* Number of db changes made since last reset */
14435 yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
14436 yDbMask lockMask; /* Subset of btreeMask that requires a lock */
14437 int iStatement; /* Statement number (or 0 if has not opened stmt) */
14438 u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
14439 #ifndef SQLITE_OMIT_TRACE
14440 i64 startTime; /* Time when query started - used for profiling */
14441 #endif
14442 i64 iCurrentTime; /* Value of julianday('now') for this statement */
14443 i64 nFkConstraint; /* Number of imm. FK constraints this VM */
14444 i64 nStmtDefCons; /* Number of def. constraints when stmt started */
14445 i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
14446 char *zSql; /* Text of the SQL statement that generated this */
14447 void *pFree; /* Free this when deleting the vdbe */
14448 VdbeFrame *pFrame; /* Parent frame */
14449 VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
14450 int nFrame; /* Number of frames in pFrame list */
14451 u32 expmask; /* Binding to these vars invalidates VM */
14452 SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
14453 int nOnceFlag; /* Size of array aOnceFlag[] */
14454 u8 *aOnceFlag; /* Flags for OP_Once */
14455 AuxData *pAuxData; /* Linked list of auxdata allocations */
14459 ** The following are allowed values for Vdbe.magic
14461 #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
14462 #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
14463 #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
14464 #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
14467 ** Function prototypes
14469 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
14470 void sqliteVdbePopStack(Vdbe*,int);
14471 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
14472 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
14473 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
14474 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
14475 #endif
14476 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
14477 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
14478 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
14479 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
14480 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
14482 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
14483 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
14484 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
14485 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
14486 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
14487 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
14488 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
14489 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
14490 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
14491 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
14492 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
14493 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
14494 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
14495 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
14496 #ifdef SQLITE_OMIT_FLOATING_POINT
14497 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
14498 #else
14499 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
14500 #endif
14501 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
14502 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
14503 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
14504 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
14505 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
14506 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
14507 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
14508 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
14509 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
14510 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
14511 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
14512 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
14513 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
14514 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
14515 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
14516 #define VdbeMemDynamic(X) \
14517 (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
14518 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
14519 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
14520 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
14521 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
14522 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
14523 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
14524 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
14525 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
14527 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
14528 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
14529 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
14530 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
14531 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
14532 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
14533 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
14534 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
14536 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
14537 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
14538 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
14539 #else
14540 # define sqlite3VdbeEnter(X)
14541 # define sqlite3VdbeLeave(X)
14542 #endif
14544 #ifdef SQLITE_DEBUG
14545 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
14546 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
14547 #endif
14549 #ifndef SQLITE_OMIT_FOREIGN_KEY
14550 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
14551 #else
14552 # define sqlite3VdbeCheckFk(p,i) 0
14553 #endif
14555 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
14556 #ifdef SQLITE_DEBUG
14557 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
14558 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
14559 #endif
14560 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
14562 #ifndef SQLITE_OMIT_INCRBLOB
14563 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
14564 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
14565 #else
14566 #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
14567 #define ExpandBlob(P) SQLITE_OK
14568 #endif
14570 #endif /* !defined(_VDBEINT_H_) */
14572 /************** End of vdbeInt.h *********************************************/
14573 /************** Continuing where we left off in status.c *********************/
14576 ** Variables in which to record status information.
14578 typedef struct sqlite3StatType sqlite3StatType;
14579 static SQLITE_WSD struct sqlite3StatType {
14580 int nowValue[10]; /* Current value */
14581 int mxValue[10]; /* Maximum value */
14582 } sqlite3Stat = { {0,}, {0,} };
14585 /* The "wsdStat" macro will resolve to the status information
14586 ** state vector. If writable static data is unsupported on the target,
14587 ** we have to locate the state vector at run-time. In the more common
14588 ** case where writable static data is supported, wsdStat can refer directly
14589 ** to the "sqlite3Stat" state vector declared above.
14591 #ifdef SQLITE_OMIT_WSD
14592 # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
14593 # define wsdStat x[0]
14594 #else
14595 # define wsdStatInit
14596 # define wsdStat sqlite3Stat
14597 #endif
14600 ** Return the current value of a status parameter.
14602 SQLITE_PRIVATE int sqlite3StatusValue(int op){
14603 wsdStatInit;
14604 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
14605 return wsdStat.nowValue[op];
14609 ** Add N to the value of a status record. It is assumed that the
14610 ** caller holds appropriate locks.
14612 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
14613 wsdStatInit;
14614 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
14615 wsdStat.nowValue[op] += N;
14616 if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
14617 wsdStat.mxValue[op] = wsdStat.nowValue[op];
14622 ** Set the value of a status to X.
14624 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
14625 wsdStatInit;
14626 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
14627 wsdStat.nowValue[op] = X;
14628 if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
14629 wsdStat.mxValue[op] = wsdStat.nowValue[op];
14634 ** Query status information.
14636 ** This implementation assumes that reading or writing an aligned
14637 ** 32-bit integer is an atomic operation. If that assumption is not true,
14638 ** then this routine is not threadsafe.
14640 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
14641 wsdStatInit;
14642 if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
14643 return SQLITE_MISUSE_BKPT;
14645 *pCurrent = wsdStat.nowValue[op];
14646 *pHighwater = wsdStat.mxValue[op];
14647 if( resetFlag ){
14648 wsdStat.mxValue[op] = wsdStat.nowValue[op];
14650 return SQLITE_OK;
14654 ** Query status information for a single database connection
14656 SQLITE_API int sqlite3_db_status(
14657 sqlite3 *db, /* The database connection whose status is desired */
14658 int op, /* Status verb */
14659 int *pCurrent, /* Write current value here */
14660 int *pHighwater, /* Write high-water mark here */
14661 int resetFlag /* Reset high-water mark if true */
14663 int rc = SQLITE_OK; /* Return code */
14664 sqlite3_mutex_enter(db->mutex);
14665 switch( op ){
14666 case SQLITE_DBSTATUS_LOOKASIDE_USED: {
14667 *pCurrent = db->lookaside.nOut;
14668 *pHighwater = db->lookaside.mxOut;
14669 if( resetFlag ){
14670 db->lookaside.mxOut = db->lookaside.nOut;
14672 break;
14675 case SQLITE_DBSTATUS_LOOKASIDE_HIT:
14676 case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
14677 case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
14678 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
14679 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
14680 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
14681 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
14682 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
14683 *pCurrent = 0;
14684 *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
14685 if( resetFlag ){
14686 db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
14688 break;
14692 ** Return an approximation for the amount of memory currently used
14693 ** by all pagers associated with the given database connection. The
14694 ** highwater mark is meaningless and is returned as zero.
14696 case SQLITE_DBSTATUS_CACHE_USED: {
14697 int totalUsed = 0;
14698 int i;
14699 sqlite3BtreeEnterAll(db);
14700 for(i=0; i<db->nDb; i++){
14701 Btree *pBt = db->aDb[i].pBt;
14702 if( pBt ){
14703 Pager *pPager = sqlite3BtreePager(pBt);
14704 totalUsed += sqlite3PagerMemUsed(pPager);
14707 sqlite3BtreeLeaveAll(db);
14708 *pCurrent = totalUsed;
14709 *pHighwater = 0;
14710 break;
14714 ** *pCurrent gets an accurate estimate of the amount of memory used
14715 ** to store the schema for all databases (main, temp, and any ATTACHed
14716 ** databases. *pHighwater is set to zero.
14718 case SQLITE_DBSTATUS_SCHEMA_USED: {
14719 int i; /* Used to iterate through schemas */
14720 int nByte = 0; /* Used to accumulate return value */
14722 sqlite3BtreeEnterAll(db);
14723 db->pnBytesFreed = &nByte;
14724 for(i=0; i<db->nDb; i++){
14725 Schema *pSchema = db->aDb[i].pSchema;
14726 if( ALWAYS(pSchema!=0) ){
14727 HashElem *p;
14729 nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
14730 pSchema->tblHash.count
14731 + pSchema->trigHash.count
14732 + pSchema->idxHash.count
14733 + pSchema->fkeyHash.count
14735 nByte += sqlite3MallocSize(pSchema->tblHash.ht);
14736 nByte += sqlite3MallocSize(pSchema->trigHash.ht);
14737 nByte += sqlite3MallocSize(pSchema->idxHash.ht);
14738 nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
14740 for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
14741 sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
14743 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
14744 sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
14748 db->pnBytesFreed = 0;
14749 sqlite3BtreeLeaveAll(db);
14751 *pHighwater = 0;
14752 *pCurrent = nByte;
14753 break;
14757 ** *pCurrent gets an accurate estimate of the amount of memory used
14758 ** to store all prepared statements.
14759 ** *pHighwater is set to zero.
14761 case SQLITE_DBSTATUS_STMT_USED: {
14762 struct Vdbe *pVdbe; /* Used to iterate through VMs */
14763 int nByte = 0; /* Used to accumulate return value */
14765 db->pnBytesFreed = &nByte;
14766 for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
14767 sqlite3VdbeClearObject(db, pVdbe);
14768 sqlite3DbFree(db, pVdbe);
14770 db->pnBytesFreed = 0;
14772 *pHighwater = 0; /* IMP: R-64479-57858 */
14773 *pCurrent = nByte;
14775 break;
14779 ** Set *pCurrent to the total cache hits or misses encountered by all
14780 ** pagers the database handle is connected to. *pHighwater is always set
14781 ** to zero.
14783 case SQLITE_DBSTATUS_CACHE_HIT:
14784 case SQLITE_DBSTATUS_CACHE_MISS:
14785 case SQLITE_DBSTATUS_CACHE_WRITE:{
14786 int i;
14787 int nRet = 0;
14788 assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
14789 assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
14791 for(i=0; i<db->nDb; i++){
14792 if( db->aDb[i].pBt ){
14793 Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
14794 sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
14797 *pHighwater = 0; /* IMP: R-42420-56072 */
14798 /* IMP: R-54100-20147 */
14799 /* IMP: R-29431-39229 */
14800 *pCurrent = nRet;
14801 break;
14804 /* Set *pCurrent to non-zero if there are unresolved deferred foreign
14805 ** key constraints. Set *pCurrent to zero if all foreign key constraints
14806 ** have been satisfied. The *pHighwater is always set to zero.
14808 case SQLITE_DBSTATUS_DEFERRED_FKS: {
14809 *pHighwater = 0; /* IMP: R-11967-56545 */
14810 *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
14811 break;
14814 default: {
14815 rc = SQLITE_ERROR;
14818 sqlite3_mutex_leave(db->mutex);
14819 return rc;
14822 /************** End of status.c **********************************************/
14823 /************** Begin file date.c ********************************************/
14825 ** 2003 October 31
14827 ** The author disclaims copyright to this source code. In place of
14828 ** a legal notice, here is a blessing:
14830 ** May you do good and not evil.
14831 ** May you find forgiveness for yourself and forgive others.
14832 ** May you share freely, never taking more than you give.
14834 *************************************************************************
14835 ** This file contains the C functions that implement date and time
14836 ** functions for SQLite.
14838 ** There is only one exported symbol in this file - the function
14839 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
14840 ** All other code has file scope.
14842 ** SQLite processes all times and dates as Julian Day numbers. The
14843 ** dates and times are stored as the number of days since noon
14844 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
14845 ** calendar system.
14847 ** 1970-01-01 00:00:00 is JD 2440587.5
14848 ** 2000-01-01 00:00:00 is JD 2451544.5
14850 ** This implementation requires years to be expressed as a 4-digit number
14851 ** which means that only dates between 0000-01-01 and 9999-12-31 can
14852 ** be represented, even though julian day numbers allow a much wider
14853 ** range of dates.
14855 ** The Gregorian calendar system is used for all dates and times,
14856 ** even those that predate the Gregorian calendar. Historians usually
14857 ** use the Julian calendar for dates prior to 1582-10-15 and for some
14858 ** dates afterwards, depending on locale. Beware of this difference.
14860 ** The conversion algorithms are implemented based on descriptions
14861 ** in the following text:
14863 ** Jean Meeus
14864 ** Astronomical Algorithms, 2nd Edition, 1998
14865 ** ISBM 0-943396-61-1
14866 ** Willmann-Bell, Inc
14867 ** Richmond, Virginia (USA)
14869 /* #include <stdlib.h> */
14870 /* #include <assert.h> */
14871 #include <time.h>
14873 #ifndef SQLITE_OMIT_DATETIME_FUNCS
14877 ** A structure for holding a single date and time.
14879 typedef struct DateTime DateTime;
14880 struct DateTime {
14881 sqlite3_int64 iJD; /* The julian day number times 86400000 */
14882 int Y, M, D; /* Year, month, and day */
14883 int h, m; /* Hour and minutes */
14884 int tz; /* Timezone offset in minutes */
14885 double s; /* Seconds */
14886 char validYMD; /* True (1) if Y,M,D are valid */
14887 char validHMS; /* True (1) if h,m,s are valid */
14888 char validJD; /* True (1) if iJD is valid */
14889 char validTZ; /* True (1) if tz is valid */
14894 ** Convert zDate into one or more integers. Additional arguments
14895 ** come in groups of 5 as follows:
14897 ** N number of digits in the integer
14898 ** min minimum allowed value of the integer
14899 ** max maximum allowed value of the integer
14900 ** nextC first character after the integer
14901 ** pVal where to write the integers value.
14903 ** Conversions continue until one with nextC==0 is encountered.
14904 ** The function returns the number of successful conversions.
14906 static int getDigits(const char *zDate, ...){
14907 va_list ap;
14908 int val;
14909 int N;
14910 int min;
14911 int max;
14912 int nextC;
14913 int *pVal;
14914 int cnt = 0;
14915 va_start(ap, zDate);
14917 N = va_arg(ap, int);
14918 min = va_arg(ap, int);
14919 max = va_arg(ap, int);
14920 nextC = va_arg(ap, int);
14921 pVal = va_arg(ap, int*);
14922 val = 0;
14923 while( N-- ){
14924 if( !sqlite3Isdigit(*zDate) ){
14925 goto end_getDigits;
14927 val = val*10 + *zDate - '0';
14928 zDate++;
14930 if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
14931 goto end_getDigits;
14933 *pVal = val;
14934 zDate++;
14935 cnt++;
14936 }while( nextC );
14937 end_getDigits:
14938 va_end(ap);
14939 return cnt;
14943 ** Parse a timezone extension on the end of a date-time.
14944 ** The extension is of the form:
14946 ** (+/-)HH:MM
14948 ** Or the "zulu" notation:
14950 ** Z
14952 ** If the parse is successful, write the number of minutes
14953 ** of change in p->tz and return 0. If a parser error occurs,
14954 ** return non-zero.
14956 ** A missing specifier is not considered an error.
14958 static int parseTimezone(const char *zDate, DateTime *p){
14959 int sgn = 0;
14960 int nHr, nMn;
14961 int c;
14962 while( sqlite3Isspace(*zDate) ){ zDate++; }
14963 p->tz = 0;
14964 c = *zDate;
14965 if( c=='-' ){
14966 sgn = -1;
14967 }else if( c=='+' ){
14968 sgn = +1;
14969 }else if( c=='Z' || c=='z' ){
14970 zDate++;
14971 goto zulu_time;
14972 }else{
14973 return c!=0;
14975 zDate++;
14976 if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
14977 return 1;
14979 zDate += 5;
14980 p->tz = sgn*(nMn + nHr*60);
14981 zulu_time:
14982 while( sqlite3Isspace(*zDate) ){ zDate++; }
14983 return *zDate!=0;
14987 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
14988 ** The HH, MM, and SS must each be exactly 2 digits. The
14989 ** fractional seconds FFFF can be one or more digits.
14991 ** Return 1 if there is a parsing error and 0 on success.
14993 static int parseHhMmSs(const char *zDate, DateTime *p){
14994 int h, m, s;
14995 double ms = 0.0;
14996 if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
14997 return 1;
14999 zDate += 5;
15000 if( *zDate==':' ){
15001 zDate++;
15002 if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
15003 return 1;
15005 zDate += 2;
15006 if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
15007 double rScale = 1.0;
15008 zDate++;
15009 while( sqlite3Isdigit(*zDate) ){
15010 ms = ms*10.0 + *zDate - '0';
15011 rScale *= 10.0;
15012 zDate++;
15014 ms /= rScale;
15016 }else{
15017 s = 0;
15019 p->validJD = 0;
15020 p->validHMS = 1;
15021 p->h = h;
15022 p->m = m;
15023 p->s = s + ms;
15024 if( parseTimezone(zDate, p) ) return 1;
15025 p->validTZ = (p->tz!=0)?1:0;
15026 return 0;
15030 ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
15031 ** that the YYYY-MM-DD is according to the Gregorian calendar.
15033 ** Reference: Meeus page 61
15035 static void computeJD(DateTime *p){
15036 int Y, M, D, A, B, X1, X2;
15038 if( p->validJD ) return;
15039 if( p->validYMD ){
15040 Y = p->Y;
15041 M = p->M;
15042 D = p->D;
15043 }else{
15044 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
15045 M = 1;
15046 D = 1;
15048 if( M<=2 ){
15049 Y--;
15050 M += 12;
15052 A = Y/100;
15053 B = 2 - A + (A/4);
15054 X1 = 36525*(Y+4716)/100;
15055 X2 = 306001*(M+1)/10000;
15056 p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
15057 p->validJD = 1;
15058 if( p->validHMS ){
15059 p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
15060 if( p->validTZ ){
15061 p->iJD -= p->tz*60000;
15062 p->validYMD = 0;
15063 p->validHMS = 0;
15064 p->validTZ = 0;
15070 ** Parse dates of the form
15072 ** YYYY-MM-DD HH:MM:SS.FFF
15073 ** YYYY-MM-DD HH:MM:SS
15074 ** YYYY-MM-DD HH:MM
15075 ** YYYY-MM-DD
15077 ** Write the result into the DateTime structure and return 0
15078 ** on success and 1 if the input string is not a well-formed
15079 ** date.
15081 static int parseYyyyMmDd(const char *zDate, DateTime *p){
15082 int Y, M, D, neg;
15084 if( zDate[0]=='-' ){
15085 zDate++;
15086 neg = 1;
15087 }else{
15088 neg = 0;
15090 if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
15091 return 1;
15093 zDate += 10;
15094 while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
15095 if( parseHhMmSs(zDate, p)==0 ){
15096 /* We got the time */
15097 }else if( *zDate==0 ){
15098 p->validHMS = 0;
15099 }else{
15100 return 1;
15102 p->validJD = 0;
15103 p->validYMD = 1;
15104 p->Y = neg ? -Y : Y;
15105 p->M = M;
15106 p->D = D;
15107 if( p->validTZ ){
15108 computeJD(p);
15110 return 0;
15114 ** Set the time to the current time reported by the VFS.
15116 ** Return the number of errors.
15118 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
15119 p->iJD = sqlite3StmtCurrentTime(context);
15120 if( p->iJD>0 ){
15121 p->validJD = 1;
15122 return 0;
15123 }else{
15124 return 1;
15129 ** Attempt to parse the given string into a Julian Day Number. Return
15130 ** the number of errors.
15132 ** The following are acceptable forms for the input string:
15134 ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
15135 ** DDDD.DD
15136 ** now
15138 ** In the first form, the +/-HH:MM is always optional. The fractional
15139 ** seconds extension (the ".FFF") is optional. The seconds portion
15140 ** (":SS.FFF") is option. The year and date can be omitted as long
15141 ** as there is a time string. The time string can be omitted as long
15142 ** as there is a year and date.
15144 static int parseDateOrTime(
15145 sqlite3_context *context,
15146 const char *zDate,
15147 DateTime *p
15149 double r;
15150 if( parseYyyyMmDd(zDate,p)==0 ){
15151 return 0;
15152 }else if( parseHhMmSs(zDate, p)==0 ){
15153 return 0;
15154 }else if( sqlite3StrICmp(zDate,"now")==0){
15155 return setDateTimeToCurrent(context, p);
15156 }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
15157 p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
15158 p->validJD = 1;
15159 return 0;
15161 return 1;
15165 ** Compute the Year, Month, and Day from the julian day number.
15167 static void computeYMD(DateTime *p){
15168 int Z, A, B, C, D, E, X1;
15169 if( p->validYMD ) return;
15170 if( !p->validJD ){
15171 p->Y = 2000;
15172 p->M = 1;
15173 p->D = 1;
15174 }else{
15175 Z = (int)((p->iJD + 43200000)/86400000);
15176 A = (int)((Z - 1867216.25)/36524.25);
15177 A = Z + 1 + A - (A/4);
15178 B = A + 1524;
15179 C = (int)((B - 122.1)/365.25);
15180 D = (36525*C)/100;
15181 E = (int)((B-D)/30.6001);
15182 X1 = (int)(30.6001*E);
15183 p->D = B - D - X1;
15184 p->M = E<14 ? E-1 : E-13;
15185 p->Y = p->M>2 ? C - 4716 : C - 4715;
15187 p->validYMD = 1;
15191 ** Compute the Hour, Minute, and Seconds from the julian day number.
15193 static void computeHMS(DateTime *p){
15194 int s;
15195 if( p->validHMS ) return;
15196 computeJD(p);
15197 s = (int)((p->iJD + 43200000) % 86400000);
15198 p->s = s/1000.0;
15199 s = (int)p->s;
15200 p->s -= s;
15201 p->h = s/3600;
15202 s -= p->h*3600;
15203 p->m = s/60;
15204 p->s += s - p->m*60;
15205 p->validHMS = 1;
15209 ** Compute both YMD and HMS
15211 static void computeYMD_HMS(DateTime *p){
15212 computeYMD(p);
15213 computeHMS(p);
15217 ** Clear the YMD and HMS and the TZ
15219 static void clearYMD_HMS_TZ(DateTime *p){
15220 p->validYMD = 0;
15221 p->validHMS = 0;
15222 p->validTZ = 0;
15226 ** On recent Windows platforms, the localtime_s() function is available
15227 ** as part of the "Secure CRT". It is essentially equivalent to
15228 ** localtime_r() available under most POSIX platforms, except that the
15229 ** order of the parameters is reversed.
15231 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
15233 ** If the user has not indicated to use localtime_r() or localtime_s()
15234 ** already, check for an MSVC build environment that provides
15235 ** localtime_s().
15237 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
15238 defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
15239 #define HAVE_LOCALTIME_S 1
15240 #endif
15242 #ifndef SQLITE_OMIT_LOCALTIME
15244 ** The following routine implements the rough equivalent of localtime_r()
15245 ** using whatever operating-system specific localtime facility that
15246 ** is available. This routine returns 0 on success and
15247 ** non-zero on any kind of error.
15249 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
15250 ** routine will always fail.
15252 ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
15253 ** library function localtime_r() is used to assist in the calculation of
15254 ** local time.
15256 static int osLocaltime(time_t *t, struct tm *pTm){
15257 int rc;
15258 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
15259 && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
15260 struct tm *pX;
15261 #if SQLITE_THREADSAFE>0
15262 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15263 #endif
15264 sqlite3_mutex_enter(mutex);
15265 pX = localtime(t);
15266 #ifndef SQLITE_OMIT_BUILTIN_TEST
15267 if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
15268 #endif
15269 if( pX ) *pTm = *pX;
15270 sqlite3_mutex_leave(mutex);
15271 rc = pX==0;
15272 #else
15273 #ifndef SQLITE_OMIT_BUILTIN_TEST
15274 if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
15275 #endif
15276 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
15277 rc = localtime_r(t, pTm)==0;
15278 #else
15279 rc = localtime_s(pTm, t);
15280 #endif /* HAVE_LOCALTIME_R */
15281 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
15282 return rc;
15284 #endif /* SQLITE_OMIT_LOCALTIME */
15287 #ifndef SQLITE_OMIT_LOCALTIME
15289 ** Compute the difference (in milliseconds) between localtime and UTC
15290 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
15291 ** return this value and set *pRc to SQLITE_OK.
15293 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
15294 ** is undefined in this case.
15296 static sqlite3_int64 localtimeOffset(
15297 DateTime *p, /* Date at which to calculate offset */
15298 sqlite3_context *pCtx, /* Write error here if one occurs */
15299 int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
15301 DateTime x, y;
15302 time_t t;
15303 struct tm sLocal;
15305 /* Initialize the contents of sLocal to avoid a compiler warning. */
15306 memset(&sLocal, 0, sizeof(sLocal));
15308 x = *p;
15309 computeYMD_HMS(&x);
15310 if( x.Y<1971 || x.Y>=2038 ){
15311 /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
15312 ** works for years between 1970 and 2037. For dates outside this range,
15313 ** SQLite attempts to map the year into an equivalent year within this
15314 ** range, do the calculation, then map the year back.
15316 x.Y = 2000;
15317 x.M = 1;
15318 x.D = 1;
15319 x.h = 0;
15320 x.m = 0;
15321 x.s = 0.0;
15322 } else {
15323 int s = (int)(x.s + 0.5);
15324 x.s = s;
15326 x.tz = 0;
15327 x.validJD = 0;
15328 computeJD(&x);
15329 t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
15330 if( osLocaltime(&t, &sLocal) ){
15331 sqlite3_result_error(pCtx, "local time unavailable", -1);
15332 *pRc = SQLITE_ERROR;
15333 return 0;
15335 y.Y = sLocal.tm_year + 1900;
15336 y.M = sLocal.tm_mon + 1;
15337 y.D = sLocal.tm_mday;
15338 y.h = sLocal.tm_hour;
15339 y.m = sLocal.tm_min;
15340 y.s = sLocal.tm_sec;
15341 y.validYMD = 1;
15342 y.validHMS = 1;
15343 y.validJD = 0;
15344 y.validTZ = 0;
15345 computeJD(&y);
15346 *pRc = SQLITE_OK;
15347 return y.iJD - x.iJD;
15349 #endif /* SQLITE_OMIT_LOCALTIME */
15352 ** Process a modifier to a date-time stamp. The modifiers are
15353 ** as follows:
15355 ** NNN days
15356 ** NNN hours
15357 ** NNN minutes
15358 ** NNN.NNNN seconds
15359 ** NNN months
15360 ** NNN years
15361 ** start of month
15362 ** start of year
15363 ** start of week
15364 ** start of day
15365 ** weekday N
15366 ** unixepoch
15367 ** localtime
15368 ** utc
15370 ** Return 0 on success and 1 if there is any kind of error. If the error
15371 ** is in a system call (i.e. localtime()), then an error message is written
15372 ** to context pCtx. If the error is an unrecognized modifier, no error is
15373 ** written to pCtx.
15375 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
15376 int rc = 1;
15377 int n;
15378 double r;
15379 char *z, zBuf[30];
15380 z = zBuf;
15381 for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
15382 z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
15384 z[n] = 0;
15385 switch( z[0] ){
15386 #ifndef SQLITE_OMIT_LOCALTIME
15387 case 'l': {
15388 /* localtime
15390 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
15391 ** show local time.
15393 if( strcmp(z, "localtime")==0 ){
15394 computeJD(p);
15395 p->iJD += localtimeOffset(p, pCtx, &rc);
15396 clearYMD_HMS_TZ(p);
15398 break;
15400 #endif
15401 case 'u': {
15403 ** unixepoch
15405 ** Treat the current value of p->iJD as the number of
15406 ** seconds since 1970. Convert to a real julian day number.
15408 if( strcmp(z, "unixepoch")==0 && p->validJD ){
15409 p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
15410 clearYMD_HMS_TZ(p);
15411 rc = 0;
15413 #ifndef SQLITE_OMIT_LOCALTIME
15414 else if( strcmp(z, "utc")==0 ){
15415 sqlite3_int64 c1;
15416 computeJD(p);
15417 c1 = localtimeOffset(p, pCtx, &rc);
15418 if( rc==SQLITE_OK ){
15419 p->iJD -= c1;
15420 clearYMD_HMS_TZ(p);
15421 p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
15424 #endif
15425 break;
15427 case 'w': {
15429 ** weekday N
15431 ** Move the date to the same time on the next occurrence of
15432 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
15433 ** date is already on the appropriate weekday, this is a no-op.
15435 if( strncmp(z, "weekday ", 8)==0
15436 && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
15437 && (n=(int)r)==r && n>=0 && r<7 ){
15438 sqlite3_int64 Z;
15439 computeYMD_HMS(p);
15440 p->validTZ = 0;
15441 p->validJD = 0;
15442 computeJD(p);
15443 Z = ((p->iJD + 129600000)/86400000) % 7;
15444 if( Z>n ) Z -= 7;
15445 p->iJD += (n - Z)*86400000;
15446 clearYMD_HMS_TZ(p);
15447 rc = 0;
15449 break;
15451 case 's': {
15453 ** start of TTTTT
15455 ** Move the date backwards to the beginning of the current day,
15456 ** or month or year.
15458 if( strncmp(z, "start of ", 9)!=0 ) break;
15459 z += 9;
15460 computeYMD(p);
15461 p->validHMS = 1;
15462 p->h = p->m = 0;
15463 p->s = 0.0;
15464 p->validTZ = 0;
15465 p->validJD = 0;
15466 if( strcmp(z,"month")==0 ){
15467 p->D = 1;
15468 rc = 0;
15469 }else if( strcmp(z,"year")==0 ){
15470 computeYMD(p);
15471 p->M = 1;
15472 p->D = 1;
15473 rc = 0;
15474 }else if( strcmp(z,"day")==0 ){
15475 rc = 0;
15477 break;
15479 case '+':
15480 case '-':
15481 case '0':
15482 case '1':
15483 case '2':
15484 case '3':
15485 case '4':
15486 case '5':
15487 case '6':
15488 case '7':
15489 case '8':
15490 case '9': {
15491 double rRounder;
15492 for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
15493 if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
15494 rc = 1;
15495 break;
15497 if( z[n]==':' ){
15498 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
15499 ** specified number of hours, minutes, seconds, and fractional seconds
15500 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
15501 ** omitted.
15503 const char *z2 = z;
15504 DateTime tx;
15505 sqlite3_int64 day;
15506 if( !sqlite3Isdigit(*z2) ) z2++;
15507 memset(&tx, 0, sizeof(tx));
15508 if( parseHhMmSs(z2, &tx) ) break;
15509 computeJD(&tx);
15510 tx.iJD -= 43200000;
15511 day = tx.iJD/86400000;
15512 tx.iJD -= day*86400000;
15513 if( z[0]=='-' ) tx.iJD = -tx.iJD;
15514 computeJD(p);
15515 clearYMD_HMS_TZ(p);
15516 p->iJD += tx.iJD;
15517 rc = 0;
15518 break;
15520 z += n;
15521 while( sqlite3Isspace(*z) ) z++;
15522 n = sqlite3Strlen30(z);
15523 if( n>10 || n<3 ) break;
15524 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
15525 computeJD(p);
15526 rc = 0;
15527 rRounder = r<0 ? -0.5 : +0.5;
15528 if( n==3 && strcmp(z,"day")==0 ){
15529 p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
15530 }else if( n==4 && strcmp(z,"hour")==0 ){
15531 p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
15532 }else if( n==6 && strcmp(z,"minute")==0 ){
15533 p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
15534 }else if( n==6 && strcmp(z,"second")==0 ){
15535 p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
15536 }else if( n==5 && strcmp(z,"month")==0 ){
15537 int x, y;
15538 computeYMD_HMS(p);
15539 p->M += (int)r;
15540 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
15541 p->Y += x;
15542 p->M -= x*12;
15543 p->validJD = 0;
15544 computeJD(p);
15545 y = (int)r;
15546 if( y!=r ){
15547 p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
15549 }else if( n==4 && strcmp(z,"year")==0 ){
15550 int y = (int)r;
15551 computeYMD_HMS(p);
15552 p->Y += y;
15553 p->validJD = 0;
15554 computeJD(p);
15555 if( y!=r ){
15556 p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
15558 }else{
15559 rc = 1;
15561 clearYMD_HMS_TZ(p);
15562 break;
15564 default: {
15565 break;
15568 return rc;
15572 ** Process time function arguments. argv[0] is a date-time stamp.
15573 ** argv[1] and following are modifiers. Parse them all and write
15574 ** the resulting time into the DateTime structure p. Return 0
15575 ** on success and 1 if there are any errors.
15577 ** If there are zero parameters (if even argv[0] is undefined)
15578 ** then assume a default value of "now" for argv[0].
15580 static int isDate(
15581 sqlite3_context *context,
15582 int argc,
15583 sqlite3_value **argv,
15584 DateTime *p
15586 int i;
15587 const unsigned char *z;
15588 int eType;
15589 memset(p, 0, sizeof(*p));
15590 if( argc==0 ){
15591 return setDateTimeToCurrent(context, p);
15593 if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
15594 || eType==SQLITE_INTEGER ){
15595 p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
15596 p->validJD = 1;
15597 }else{
15598 z = sqlite3_value_text(argv[0]);
15599 if( !z || parseDateOrTime(context, (char*)z, p) ){
15600 return 1;
15603 for(i=1; i<argc; i++){
15604 z = sqlite3_value_text(argv[i]);
15605 if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
15607 return 0;
15612 ** The following routines implement the various date and time functions
15613 ** of SQLite.
15617 ** julianday( TIMESTRING, MOD, MOD, ...)
15619 ** Return the julian day number of the date specified in the arguments
15621 static void juliandayFunc(
15622 sqlite3_context *context,
15623 int argc,
15624 sqlite3_value **argv
15626 DateTime x;
15627 if( isDate(context, argc, argv, &x)==0 ){
15628 computeJD(&x);
15629 sqlite3_result_double(context, x.iJD/86400000.0);
15634 ** datetime( TIMESTRING, MOD, MOD, ...)
15636 ** Return YYYY-MM-DD HH:MM:SS
15638 static void datetimeFunc(
15639 sqlite3_context *context,
15640 int argc,
15641 sqlite3_value **argv
15643 DateTime x;
15644 if( isDate(context, argc, argv, &x)==0 ){
15645 char zBuf[100];
15646 computeYMD_HMS(&x);
15647 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
15648 x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
15649 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15654 ** time( TIMESTRING, MOD, MOD, ...)
15656 ** Return HH:MM:SS
15658 static void timeFunc(
15659 sqlite3_context *context,
15660 int argc,
15661 sqlite3_value **argv
15663 DateTime x;
15664 if( isDate(context, argc, argv, &x)==0 ){
15665 char zBuf[100];
15666 computeHMS(&x);
15667 sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
15668 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15673 ** date( TIMESTRING, MOD, MOD, ...)
15675 ** Return YYYY-MM-DD
15677 static void dateFunc(
15678 sqlite3_context *context,
15679 int argc,
15680 sqlite3_value **argv
15682 DateTime x;
15683 if( isDate(context, argc, argv, &x)==0 ){
15684 char zBuf[100];
15685 computeYMD(&x);
15686 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
15687 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15692 ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
15694 ** Return a string described by FORMAT. Conversions as follows:
15696 ** %d day of month
15697 ** %f ** fractional seconds SS.SSS
15698 ** %H hour 00-24
15699 ** %j day of year 000-366
15700 ** %J ** Julian day number
15701 ** %m month 01-12
15702 ** %M minute 00-59
15703 ** %s seconds since 1970-01-01
15704 ** %S seconds 00-59
15705 ** %w day of week 0-6 sunday==0
15706 ** %W week of year 00-53
15707 ** %Y year 0000-9999
15708 ** %% %
15710 static void strftimeFunc(
15711 sqlite3_context *context,
15712 int argc,
15713 sqlite3_value **argv
15715 DateTime x;
15716 u64 n;
15717 size_t i,j;
15718 char *z;
15719 sqlite3 *db;
15720 const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
15721 char zBuf[100];
15722 if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
15723 db = sqlite3_context_db_handle(context);
15724 for(i=0, n=1; zFmt[i]; i++, n++){
15725 if( zFmt[i]=='%' ){
15726 switch( zFmt[i+1] ){
15727 case 'd':
15728 case 'H':
15729 case 'm':
15730 case 'M':
15731 case 'S':
15732 case 'W':
15733 n++;
15734 /* fall thru */
15735 case 'w':
15736 case '%':
15737 break;
15738 case 'f':
15739 n += 8;
15740 break;
15741 case 'j':
15742 n += 3;
15743 break;
15744 case 'Y':
15745 n += 8;
15746 break;
15747 case 's':
15748 case 'J':
15749 n += 50;
15750 break;
15751 default:
15752 return; /* ERROR. return a NULL */
15754 i++;
15757 testcase( n==sizeof(zBuf)-1 );
15758 testcase( n==sizeof(zBuf) );
15759 testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
15760 testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
15761 if( n<sizeof(zBuf) ){
15762 z = zBuf;
15763 }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
15764 sqlite3_result_error_toobig(context);
15765 return;
15766 }else{
15767 z = sqlite3DbMallocRaw(db, (int)n);
15768 if( z==0 ){
15769 sqlite3_result_error_nomem(context);
15770 return;
15773 computeJD(&x);
15774 computeYMD_HMS(&x);
15775 for(i=j=0; zFmt[i]; i++){
15776 if( zFmt[i]!='%' ){
15777 z[j++] = zFmt[i];
15778 }else{
15779 i++;
15780 switch( zFmt[i] ){
15781 case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
15782 case 'f': {
15783 double s = x.s;
15784 if( s>59.999 ) s = 59.999;
15785 sqlite3_snprintf(7, &z[j],"%06.3f", s);
15786 j += sqlite3Strlen30(&z[j]);
15787 break;
15789 case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
15790 case 'W': /* Fall thru */
15791 case 'j': {
15792 int nDay; /* Number of days since 1st day of year */
15793 DateTime y = x;
15794 y.validJD = 0;
15795 y.M = 1;
15796 y.D = 1;
15797 computeJD(&y);
15798 nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
15799 if( zFmt[i]=='W' ){
15800 int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
15801 wd = (int)(((x.iJD+43200000)/86400000)%7);
15802 sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
15803 j += 2;
15804 }else{
15805 sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
15806 j += 3;
15808 break;
15810 case 'J': {
15811 sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
15812 j+=sqlite3Strlen30(&z[j]);
15813 break;
15815 case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
15816 case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
15817 case 's': {
15818 sqlite3_snprintf(30,&z[j],"%lld",
15819 (i64)(x.iJD/1000 - 21086676*(i64)10000));
15820 j += sqlite3Strlen30(&z[j]);
15821 break;
15823 case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
15824 case 'w': {
15825 z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
15826 break;
15828 case 'Y': {
15829 sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
15830 break;
15832 default: z[j++] = '%'; break;
15836 z[j] = 0;
15837 sqlite3_result_text(context, z, -1,
15838 z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
15842 ** current_time()
15844 ** This function returns the same value as time('now').
15846 static void ctimeFunc(
15847 sqlite3_context *context,
15848 int NotUsed,
15849 sqlite3_value **NotUsed2
15851 UNUSED_PARAMETER2(NotUsed, NotUsed2);
15852 timeFunc(context, 0, 0);
15856 ** current_date()
15858 ** This function returns the same value as date('now').
15860 static void cdateFunc(
15861 sqlite3_context *context,
15862 int NotUsed,
15863 sqlite3_value **NotUsed2
15865 UNUSED_PARAMETER2(NotUsed, NotUsed2);
15866 dateFunc(context, 0, 0);
15870 ** current_timestamp()
15872 ** This function returns the same value as datetime('now').
15874 static void ctimestampFunc(
15875 sqlite3_context *context,
15876 int NotUsed,
15877 sqlite3_value **NotUsed2
15879 UNUSED_PARAMETER2(NotUsed, NotUsed2);
15880 datetimeFunc(context, 0, 0);
15882 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
15884 #ifdef SQLITE_OMIT_DATETIME_FUNCS
15886 ** If the library is compiled to omit the full-scale date and time
15887 ** handling (to get a smaller binary), the following minimal version
15888 ** of the functions current_time(), current_date() and current_timestamp()
15889 ** are included instead. This is to support column declarations that
15890 ** include "DEFAULT CURRENT_TIME" etc.
15892 ** This function uses the C-library functions time(), gmtime()
15893 ** and strftime(). The format string to pass to strftime() is supplied
15894 ** as the user-data for the function.
15896 static void currentTimeFunc(
15897 sqlite3_context *context,
15898 int argc,
15899 sqlite3_value **argv
15901 time_t t;
15902 char *zFormat = (char *)sqlite3_user_data(context);
15903 sqlite3 *db;
15904 sqlite3_int64 iT;
15905 struct tm *pTm;
15906 struct tm sNow;
15907 char zBuf[20];
15909 UNUSED_PARAMETER(argc);
15910 UNUSED_PARAMETER(argv);
15912 iT = sqlite3StmtCurrentTime(context);
15913 if( iT<=0 ) return;
15914 t = iT/1000 - 10000*(sqlite3_int64)21086676;
15915 #ifdef HAVE_GMTIME_R
15916 pTm = gmtime_r(&t, &sNow);
15917 #else
15918 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
15919 pTm = gmtime(&t);
15920 if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
15921 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
15922 #endif
15923 if( pTm ){
15924 strftime(zBuf, 20, zFormat, &sNow);
15925 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15928 #endif
15931 ** This function registered all of the above C functions as SQL
15932 ** functions. This should be the only routine in this file with
15933 ** external linkage.
15935 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
15936 static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
15937 #ifndef SQLITE_OMIT_DATETIME_FUNCS
15938 FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
15939 FUNCTION(date, -1, 0, 0, dateFunc ),
15940 FUNCTION(time, -1, 0, 0, timeFunc ),
15941 FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
15942 FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
15943 FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
15944 FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
15945 FUNCTION(current_date, 0, 0, 0, cdateFunc ),
15946 #else
15947 STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
15948 STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
15949 STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
15950 #endif
15952 int i;
15953 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
15954 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
15956 for(i=0; i<ArraySize(aDateTimeFuncs); i++){
15957 sqlite3FuncDefInsert(pHash, &aFunc[i]);
15961 /************** End of date.c ************************************************/
15962 /************** Begin file os.c **********************************************/
15964 ** 2005 November 29
15966 ** The author disclaims copyright to this source code. In place of
15967 ** a legal notice, here is a blessing:
15969 ** May you do good and not evil.
15970 ** May you find forgiveness for yourself and forgive others.
15971 ** May you share freely, never taking more than you give.
15973 ******************************************************************************
15975 ** This file contains OS interface code that is common to all
15976 ** architectures.
15978 #define _SQLITE_OS_C_ 1
15979 #undef _SQLITE_OS_C_
15982 ** The default SQLite sqlite3_vfs implementations do not allocate
15983 ** memory (actually, os_unix.c allocates a small amount of memory
15984 ** from within OsOpen()), but some third-party implementations may.
15985 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
15986 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
15988 ** The following functions are instrumented for malloc() failure
15989 ** testing:
15991 ** sqlite3OsRead()
15992 ** sqlite3OsWrite()
15993 ** sqlite3OsSync()
15994 ** sqlite3OsFileSize()
15995 ** sqlite3OsLock()
15996 ** sqlite3OsCheckReservedLock()
15997 ** sqlite3OsFileControl()
15998 ** sqlite3OsShmMap()
15999 ** sqlite3OsOpen()
16000 ** sqlite3OsDelete()
16001 ** sqlite3OsAccess()
16002 ** sqlite3OsFullPathname()
16005 #if defined(SQLITE_TEST)
16006 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
16007 #define DO_OS_MALLOC_TEST(x) \
16008 if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
16009 void *pTstAlloc = sqlite3Malloc(10); \
16010 if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
16011 sqlite3_free(pTstAlloc); \
16013 #else
16014 #define DO_OS_MALLOC_TEST(x)
16015 #endif
16018 ** The following routines are convenience wrappers around methods
16019 ** of the sqlite3_file object. This is mostly just syntactic sugar. All
16020 ** of this would be completely automatic if SQLite were coded using
16021 ** C++ instead of plain old C.
16023 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
16024 int rc = SQLITE_OK;
16025 if( pId->pMethods ){
16026 rc = pId->pMethods->xClose(pId);
16027 pId->pMethods = 0;
16029 return rc;
16031 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
16032 DO_OS_MALLOC_TEST(id);
16033 return id->pMethods->xRead(id, pBuf, amt, offset);
16035 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
16036 DO_OS_MALLOC_TEST(id);
16037 return id->pMethods->xWrite(id, pBuf, amt, offset);
16039 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
16040 return id->pMethods->xTruncate(id, size);
16042 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
16043 DO_OS_MALLOC_TEST(id);
16044 return id->pMethods->xSync(id, flags);
16046 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
16047 DO_OS_MALLOC_TEST(id);
16048 return id->pMethods->xFileSize(id, pSize);
16050 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
16051 DO_OS_MALLOC_TEST(id);
16052 return id->pMethods->xLock(id, lockType);
16054 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
16055 return id->pMethods->xUnlock(id, lockType);
16057 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
16058 DO_OS_MALLOC_TEST(id);
16059 return id->pMethods->xCheckReservedLock(id, pResOut);
16063 ** Use sqlite3OsFileControl() when we are doing something that might fail
16064 ** and we need to know about the failures. Use sqlite3OsFileControlHint()
16065 ** when simply tossing information over the wall to the VFS and we do not
16066 ** really care if the VFS receives and understands the information since it
16067 ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
16068 ** routine has no return value since the return value would be meaningless.
16070 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
16071 #ifdef SQLITE_TEST
16072 if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
16073 /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
16074 ** is using a regular VFS, it is called after the corresponding
16075 ** transaction has been committed. Injecting a fault at this point
16076 ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
16077 ** but the transaction is committed anyway.
16079 ** The core must call OsFileControl() though, not OsFileControlHint(),
16080 ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
16081 ** means the commit really has failed and an error should be returned
16082 ** to the user. */
16083 DO_OS_MALLOC_TEST(id);
16085 #endif
16086 return id->pMethods->xFileControl(id, op, pArg);
16088 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
16089 (void)id->pMethods->xFileControl(id, op, pArg);
16092 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
16093 int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
16094 return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
16096 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
16097 return id->pMethods->xDeviceCharacteristics(id);
16099 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
16100 return id->pMethods->xShmLock(id, offset, n, flags);
16102 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
16103 id->pMethods->xShmBarrier(id);
16105 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
16106 return id->pMethods->xShmUnmap(id, deleteFlag);
16108 SQLITE_PRIVATE int sqlite3OsShmMap(
16109 sqlite3_file *id, /* Database file handle */
16110 int iPage,
16111 int pgsz,
16112 int bExtend, /* True to extend file if necessary */
16113 void volatile **pp /* OUT: Pointer to mapping */
16115 DO_OS_MALLOC_TEST(id);
16116 return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
16119 #if SQLITE_MAX_MMAP_SIZE>0
16120 /* The real implementation of xFetch and xUnfetch */
16121 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
16122 DO_OS_MALLOC_TEST(id);
16123 return id->pMethods->xFetch(id, iOff, iAmt, pp);
16125 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
16126 return id->pMethods->xUnfetch(id, iOff, p);
16128 #else
16129 /* No-op stubs to use when memory-mapped I/O is disabled */
16130 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
16131 *pp = 0;
16132 return SQLITE_OK;
16134 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
16135 return SQLITE_OK;
16137 #endif
16140 ** The next group of routines are convenience wrappers around the
16141 ** VFS methods.
16143 SQLITE_PRIVATE int sqlite3OsOpen(
16144 sqlite3_vfs *pVfs,
16145 const char *zPath,
16146 sqlite3_file *pFile,
16147 int flags,
16148 int *pFlagsOut
16150 int rc;
16151 DO_OS_MALLOC_TEST(0);
16152 /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
16153 ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
16154 ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
16155 ** reaching the VFS. */
16156 rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
16157 assert( rc==SQLITE_OK || pFile->pMethods==0 );
16158 return rc;
16160 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
16161 DO_OS_MALLOC_TEST(0);
16162 assert( dirSync==0 || dirSync==1 );
16163 return pVfs->xDelete(pVfs, zPath, dirSync);
16165 SQLITE_PRIVATE int sqlite3OsAccess(
16166 sqlite3_vfs *pVfs,
16167 const char *zPath,
16168 int flags,
16169 int *pResOut
16171 DO_OS_MALLOC_TEST(0);
16172 return pVfs->xAccess(pVfs, zPath, flags, pResOut);
16174 SQLITE_PRIVATE int sqlite3OsFullPathname(
16175 sqlite3_vfs *pVfs,
16176 const char *zPath,
16177 int nPathOut,
16178 char *zPathOut
16180 DO_OS_MALLOC_TEST(0);
16181 zPathOut[0] = 0;
16182 return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
16184 #ifndef SQLITE_OMIT_LOAD_EXTENSION
16185 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
16186 return pVfs->xDlOpen(pVfs, zPath);
16188 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
16189 pVfs->xDlError(pVfs, nByte, zBufOut);
16191 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
16192 return pVfs->xDlSym(pVfs, pHdle, zSym);
16194 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
16195 pVfs->xDlClose(pVfs, pHandle);
16197 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
16198 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
16199 return pVfs->xRandomness(pVfs, nByte, zBufOut);
16201 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
16202 return pVfs->xSleep(pVfs, nMicro);
16204 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
16205 int rc;
16206 /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
16207 ** method to get the current date and time if that method is available
16208 ** (if iVersion is 2 or greater and the function pointer is not NULL) and
16209 ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
16210 ** unavailable.
16212 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
16213 rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
16214 }else{
16215 double r;
16216 rc = pVfs->xCurrentTime(pVfs, &r);
16217 *pTimeOut = (sqlite3_int64)(r*86400000.0);
16219 return rc;
16222 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
16223 sqlite3_vfs *pVfs,
16224 const char *zFile,
16225 sqlite3_file **ppFile,
16226 int flags,
16227 int *pOutFlags
16229 int rc = SQLITE_NOMEM;
16230 sqlite3_file *pFile;
16231 pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
16232 if( pFile ){
16233 rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
16234 if( rc!=SQLITE_OK ){
16235 sqlite3_free(pFile);
16236 }else{
16237 *ppFile = pFile;
16240 return rc;
16242 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
16243 int rc = SQLITE_OK;
16244 assert( pFile );
16245 rc = sqlite3OsClose(pFile);
16246 sqlite3_free(pFile);
16247 return rc;
16251 ** This function is a wrapper around the OS specific implementation of
16252 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
16253 ** ability to simulate a malloc failure, so that the handling of an
16254 ** error in sqlite3_os_init() by the upper layers can be tested.
16256 SQLITE_PRIVATE int sqlite3OsInit(void){
16257 void *p = sqlite3_malloc(10);
16258 if( p==0 ) return SQLITE_NOMEM;
16259 sqlite3_free(p);
16260 return sqlite3_os_init();
16264 ** The list of all registered VFS implementations.
16266 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
16267 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
16270 ** Locate a VFS by name. If no name is given, simply return the
16271 ** first VFS on the list.
16273 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
16274 sqlite3_vfs *pVfs = 0;
16275 #if SQLITE_THREADSAFE
16276 sqlite3_mutex *mutex;
16277 #endif
16278 #ifndef SQLITE_OMIT_AUTOINIT
16279 int rc = sqlite3_initialize();
16280 if( rc ) return 0;
16281 #endif
16282 #if SQLITE_THREADSAFE
16283 mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
16284 #endif
16285 sqlite3_mutex_enter(mutex);
16286 for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
16287 if( zVfs==0 ) break;
16288 if( strcmp(zVfs, pVfs->zName)==0 ) break;
16290 sqlite3_mutex_leave(mutex);
16291 return pVfs;
16295 ** Unlink a VFS from the linked list
16297 static void vfsUnlink(sqlite3_vfs *pVfs){
16298 assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
16299 if( pVfs==0 ){
16300 /* No-op */
16301 }else if( vfsList==pVfs ){
16302 vfsList = pVfs->pNext;
16303 }else if( vfsList ){
16304 sqlite3_vfs *p = vfsList;
16305 while( p->pNext && p->pNext!=pVfs ){
16306 p = p->pNext;
16308 if( p->pNext==pVfs ){
16309 p->pNext = pVfs->pNext;
16315 ** Register a VFS with the system. It is harmless to register the same
16316 ** VFS multiple times. The new VFS becomes the default if makeDflt is
16317 ** true.
16319 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
16320 MUTEX_LOGIC(sqlite3_mutex *mutex;)
16321 #ifndef SQLITE_OMIT_AUTOINIT
16322 int rc = sqlite3_initialize();
16323 if( rc ) return rc;
16324 #endif
16325 MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
16326 sqlite3_mutex_enter(mutex);
16327 vfsUnlink(pVfs);
16328 if( makeDflt || vfsList==0 ){
16329 pVfs->pNext = vfsList;
16330 vfsList = pVfs;
16331 }else{
16332 pVfs->pNext = vfsList->pNext;
16333 vfsList->pNext = pVfs;
16335 assert(vfsList);
16336 sqlite3_mutex_leave(mutex);
16337 return SQLITE_OK;
16341 ** Unregister a VFS so that it is no longer accessible.
16343 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
16344 #if SQLITE_THREADSAFE
16345 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
16346 #endif
16347 sqlite3_mutex_enter(mutex);
16348 vfsUnlink(pVfs);
16349 sqlite3_mutex_leave(mutex);
16350 return SQLITE_OK;
16353 /************** End of os.c **************************************************/
16354 /************** Begin file fault.c *******************************************/
16356 ** 2008 Jan 22
16358 ** The author disclaims copyright to this source code. In place of
16359 ** a legal notice, here is a blessing:
16361 ** May you do good and not evil.
16362 ** May you find forgiveness for yourself and forgive others.
16363 ** May you share freely, never taking more than you give.
16365 *************************************************************************
16367 ** This file contains code to support the concept of "benign"
16368 ** malloc failures (when the xMalloc() or xRealloc() method of the
16369 ** sqlite3_mem_methods structure fails to allocate a block of memory
16370 ** and returns 0).
16372 ** Most malloc failures are non-benign. After they occur, SQLite
16373 ** abandons the current operation and returns an error code (usually
16374 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
16375 ** fatal. For example, if a malloc fails while resizing a hash table, this
16376 ** is completely recoverable simply by not carrying out the resize. The
16377 ** hash table will continue to function normally. So a malloc failure
16378 ** during a hash table resize is a benign fault.
16382 #ifndef SQLITE_OMIT_BUILTIN_TEST
16385 ** Global variables.
16387 typedef struct BenignMallocHooks BenignMallocHooks;
16388 static SQLITE_WSD struct BenignMallocHooks {
16389 void (*xBenignBegin)(void);
16390 void (*xBenignEnd)(void);
16391 } sqlite3Hooks = { 0, 0 };
16393 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
16394 ** structure. If writable static data is unsupported on the target,
16395 ** we have to locate the state vector at run-time. In the more common
16396 ** case where writable static data is supported, wsdHooks can refer directly
16397 ** to the "sqlite3Hooks" state vector declared above.
16399 #ifdef SQLITE_OMIT_WSD
16400 # define wsdHooksInit \
16401 BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
16402 # define wsdHooks x[0]
16403 #else
16404 # define wsdHooksInit
16405 # define wsdHooks sqlite3Hooks
16406 #endif
16410 ** Register hooks to call when sqlite3BeginBenignMalloc() and
16411 ** sqlite3EndBenignMalloc() are called, respectively.
16413 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
16414 void (*xBenignBegin)(void),
16415 void (*xBenignEnd)(void)
16417 wsdHooksInit;
16418 wsdHooks.xBenignBegin = xBenignBegin;
16419 wsdHooks.xBenignEnd = xBenignEnd;
16423 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
16424 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
16425 ** indicates that subsequent malloc failures are non-benign.
16427 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
16428 wsdHooksInit;
16429 if( wsdHooks.xBenignBegin ){
16430 wsdHooks.xBenignBegin();
16433 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
16434 wsdHooksInit;
16435 if( wsdHooks.xBenignEnd ){
16436 wsdHooks.xBenignEnd();
16440 #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
16442 /************** End of fault.c ***********************************************/
16443 /************** Begin file mem0.c ********************************************/
16445 ** 2008 October 28
16447 ** The author disclaims copyright to this source code. In place of
16448 ** a legal notice, here is a blessing:
16450 ** May you do good and not evil.
16451 ** May you find forgiveness for yourself and forgive others.
16452 ** May you share freely, never taking more than you give.
16454 *************************************************************************
16456 ** This file contains a no-op memory allocation drivers for use when
16457 ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
16458 ** here always fail. SQLite will not operate with these drivers. These
16459 ** are merely placeholders. Real drivers must be substituted using
16460 ** sqlite3_config() before SQLite will operate.
16464 ** This version of the memory allocator is the default. It is
16465 ** used when no other memory allocator is specified using compile-time
16466 ** macros.
16468 #ifdef SQLITE_ZERO_MALLOC
16471 ** No-op versions of all memory allocation routines
16473 static void *sqlite3MemMalloc(int nByte){ return 0; }
16474 static void sqlite3MemFree(void *pPrior){ return; }
16475 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
16476 static int sqlite3MemSize(void *pPrior){ return 0; }
16477 static int sqlite3MemRoundup(int n){ return n; }
16478 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
16479 static void sqlite3MemShutdown(void *NotUsed){ return; }
16482 ** This routine is the only routine in this file with external linkage.
16484 ** Populate the low-level memory allocation function pointers in
16485 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
16487 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16488 static const sqlite3_mem_methods defaultMethods = {
16489 sqlite3MemMalloc,
16490 sqlite3MemFree,
16491 sqlite3MemRealloc,
16492 sqlite3MemSize,
16493 sqlite3MemRoundup,
16494 sqlite3MemInit,
16495 sqlite3MemShutdown,
16498 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16501 #endif /* SQLITE_ZERO_MALLOC */
16503 /************** End of mem0.c ************************************************/
16504 /************** Begin file mem1.c ********************************************/
16506 ** 2007 August 14
16508 ** The author disclaims copyright to this source code. In place of
16509 ** a legal notice, here is a blessing:
16511 ** May you do good and not evil.
16512 ** May you find forgiveness for yourself and forgive others.
16513 ** May you share freely, never taking more than you give.
16515 *************************************************************************
16517 ** This file contains low-level memory allocation drivers for when
16518 ** SQLite will use the standard C-library malloc/realloc/free interface
16519 ** to obtain the memory it needs.
16521 ** This file contains implementations of the low-level memory allocation
16522 ** routines specified in the sqlite3_mem_methods object. The content of
16523 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
16524 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
16525 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
16526 ** default configuration is to use memory allocation routines in this
16527 ** file.
16529 ** C-preprocessor macro summary:
16531 ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
16532 ** the malloc_usable_size() interface exists
16533 ** on the target platform. Or, this symbol
16534 ** can be set manually, if desired.
16535 ** If an equivalent interface exists by
16536 ** a different name, using a separate -D
16537 ** option to rename it.
16539 ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
16540 ** memory allocator. Set this symbol to enable
16541 ** building on older macs.
16543 ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
16544 ** _msize() on windows systems. This might
16545 ** be necessary when compiling for Delphi,
16546 ** for example.
16550 ** This version of the memory allocator is the default. It is
16551 ** used when no other memory allocator is specified using compile-time
16552 ** macros.
16554 #ifdef SQLITE_SYSTEM_MALLOC
16555 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
16558 ** Use the zone allocator available on apple products unless the
16559 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
16561 #include <sys/sysctl.h>
16562 #include <malloc/malloc.h>
16563 #include <libkern/OSAtomic.h>
16564 static malloc_zone_t* _sqliteZone_;
16565 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
16566 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
16567 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
16568 #define SQLITE_MALLOCSIZE(x) \
16569 (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
16571 #else /* if not __APPLE__ */
16574 ** Use standard C library malloc and free on non-Apple systems.
16575 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
16577 #define SQLITE_MALLOC(x) malloc(x)
16578 #define SQLITE_FREE(x) free(x)
16579 #define SQLITE_REALLOC(x,y) realloc((x),(y))
16582 ** The malloc.h header file is needed for malloc_usable_size() function
16583 ** on some systems (e.g. Linux).
16585 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE)
16586 # define SQLITE_USE_MALLOC_H
16587 # define SQLITE_USE_MALLOC_USABLE_SIZE
16589 ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
16590 ** use of _msize() is automatic, but can be disabled by compiling with
16591 ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
16592 ** the malloc.h header file.
16594 #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
16595 # define SQLITE_USE_MALLOC_H
16596 # define SQLITE_USE_MSIZE
16597 #endif
16600 ** Include the malloc.h header file, if necessary. Also set define macro
16601 ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
16602 ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
16603 ** The memory size function can always be overridden manually by defining
16604 ** the macro SQLITE_MALLOCSIZE to the desired function name.
16606 #if defined(SQLITE_USE_MALLOC_H)
16607 # include <malloc.h>
16608 # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
16609 # if !defined(SQLITE_MALLOCSIZE)
16610 # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
16611 # endif
16612 # elif defined(SQLITE_USE_MSIZE)
16613 # if !defined(SQLITE_MALLOCSIZE)
16614 # define SQLITE_MALLOCSIZE _msize
16615 # endif
16616 # endif
16617 #endif /* defined(SQLITE_USE_MALLOC_H) */
16619 #endif /* __APPLE__ or not __APPLE__ */
16622 ** Like malloc(), but remember the size of the allocation
16623 ** so that we can find it later using sqlite3MemSize().
16625 ** For this low-level routine, we are guaranteed that nByte>0 because
16626 ** cases of nByte<=0 will be intercepted and dealt with by higher level
16627 ** routines.
16629 static void *sqlite3MemMalloc(int nByte){
16630 #ifdef SQLITE_MALLOCSIZE
16631 void *p = SQLITE_MALLOC( nByte );
16632 if( p==0 ){
16633 testcase( sqlite3GlobalConfig.xLog!=0 );
16634 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
16636 return p;
16637 #else
16638 sqlite3_int64 *p;
16639 assert( nByte>0 );
16640 nByte = ROUND8(nByte);
16641 p = SQLITE_MALLOC( nByte+8 );
16642 if( p ){
16643 p[0] = nByte;
16644 p++;
16645 }else{
16646 testcase( sqlite3GlobalConfig.xLog!=0 );
16647 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
16649 return (void *)p;
16650 #endif
16654 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
16655 ** or sqlite3MemRealloc().
16657 ** For this low-level routine, we already know that pPrior!=0 since
16658 ** cases where pPrior==0 will have been intecepted and dealt with
16659 ** by higher-level routines.
16661 static void sqlite3MemFree(void *pPrior){
16662 #ifdef SQLITE_MALLOCSIZE
16663 SQLITE_FREE(pPrior);
16664 #else
16665 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
16666 assert( pPrior!=0 );
16667 p--;
16668 SQLITE_FREE(p);
16669 #endif
16673 ** Report the allocated size of a prior return from xMalloc()
16674 ** or xRealloc().
16676 static int sqlite3MemSize(void *pPrior){
16677 #ifdef SQLITE_MALLOCSIZE
16678 return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
16679 #else
16680 sqlite3_int64 *p;
16681 if( pPrior==0 ) return 0;
16682 p = (sqlite3_int64*)pPrior;
16683 p--;
16684 return (int)p[0];
16685 #endif
16689 ** Like realloc(). Resize an allocation previously obtained from
16690 ** sqlite3MemMalloc().
16692 ** For this low-level interface, we know that pPrior!=0. Cases where
16693 ** pPrior==0 while have been intercepted by higher-level routine and
16694 ** redirected to xMalloc. Similarly, we know that nByte>0 because
16695 ** cases where nByte<=0 will have been intercepted by higher-level
16696 ** routines and redirected to xFree.
16698 static void *sqlite3MemRealloc(void *pPrior, int nByte){
16699 #ifdef SQLITE_MALLOCSIZE
16700 void *p = SQLITE_REALLOC(pPrior, nByte);
16701 if( p==0 ){
16702 testcase( sqlite3GlobalConfig.xLog!=0 );
16703 sqlite3_log(SQLITE_NOMEM,
16704 "failed memory resize %u to %u bytes",
16705 SQLITE_MALLOCSIZE(pPrior), nByte);
16707 return p;
16708 #else
16709 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
16710 assert( pPrior!=0 && nByte>0 );
16711 assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
16712 p--;
16713 p = SQLITE_REALLOC(p, nByte+8 );
16714 if( p ){
16715 p[0] = nByte;
16716 p++;
16717 }else{
16718 testcase( sqlite3GlobalConfig.xLog!=0 );
16719 sqlite3_log(SQLITE_NOMEM,
16720 "failed memory resize %u to %u bytes",
16721 sqlite3MemSize(pPrior), nByte);
16723 return (void*)p;
16724 #endif
16728 ** Round up a request size to the next valid allocation size.
16730 static int sqlite3MemRoundup(int n){
16731 return ROUND8(n);
16735 ** Initialize this module.
16737 static int sqlite3MemInit(void *NotUsed){
16738 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
16739 int cpuCount;
16740 size_t len;
16741 if( _sqliteZone_ ){
16742 return SQLITE_OK;
16744 len = sizeof(cpuCount);
16745 /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
16746 sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
16747 if( cpuCount>1 ){
16748 /* defer MT decisions to system malloc */
16749 _sqliteZone_ = malloc_default_zone();
16750 }else{
16751 /* only 1 core, use our own zone to contention over global locks,
16752 ** e.g. we have our own dedicated locks */
16753 bool success;
16754 malloc_zone_t* newzone = malloc_create_zone(4096, 0);
16755 malloc_set_zone_name(newzone, "Sqlite_Heap");
16757 success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
16758 (void * volatile *)&_sqliteZone_);
16759 }while(!_sqliteZone_);
16760 if( !success ){
16761 /* somebody registered a zone first */
16762 malloc_destroy_zone(newzone);
16765 #endif
16766 UNUSED_PARAMETER(NotUsed);
16767 return SQLITE_OK;
16771 ** Deinitialize this module.
16773 static void sqlite3MemShutdown(void *NotUsed){
16774 UNUSED_PARAMETER(NotUsed);
16775 return;
16779 ** This routine is the only routine in this file with external linkage.
16781 ** Populate the low-level memory allocation function pointers in
16782 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
16784 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16785 static const sqlite3_mem_methods defaultMethods = {
16786 sqlite3MemMalloc,
16787 sqlite3MemFree,
16788 sqlite3MemRealloc,
16789 sqlite3MemSize,
16790 sqlite3MemRoundup,
16791 sqlite3MemInit,
16792 sqlite3MemShutdown,
16795 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16798 #endif /* SQLITE_SYSTEM_MALLOC */
16800 /************** End of mem1.c ************************************************/
16801 /************** Begin file mem2.c ********************************************/
16803 ** 2007 August 15
16805 ** The author disclaims copyright to this source code. In place of
16806 ** a legal notice, here is a blessing:
16808 ** May you do good and not evil.
16809 ** May you find forgiveness for yourself and forgive others.
16810 ** May you share freely, never taking more than you give.
16812 *************************************************************************
16814 ** This file contains low-level memory allocation drivers for when
16815 ** SQLite will use the standard C-library malloc/realloc/free interface
16816 ** to obtain the memory it needs while adding lots of additional debugging
16817 ** information to each allocation in order to help detect and fix memory
16818 ** leaks and memory usage errors.
16820 ** This file contains implementations of the low-level memory allocation
16821 ** routines specified in the sqlite3_mem_methods object.
16825 ** This version of the memory allocator is used only if the
16826 ** SQLITE_MEMDEBUG macro is defined
16828 #ifdef SQLITE_MEMDEBUG
16831 ** The backtrace functionality is only available with GLIBC
16833 #ifdef __GLIBC__
16834 extern int backtrace(void**,int);
16835 extern void backtrace_symbols_fd(void*const*,int,int);
16836 #else
16837 # define backtrace(A,B) 1
16838 # define backtrace_symbols_fd(A,B,C)
16839 #endif
16840 /* #include <stdio.h> */
16843 ** Each memory allocation looks like this:
16845 ** ------------------------------------------------------------------------
16846 ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
16847 ** ------------------------------------------------------------------------
16849 ** The application code sees only a pointer to the allocation. We have
16850 ** to back up from the allocation pointer to find the MemBlockHdr. The
16851 ** MemBlockHdr tells us the size of the allocation and the number of
16852 ** backtrace pointers. There is also a guard word at the end of the
16853 ** MemBlockHdr.
16855 struct MemBlockHdr {
16856 i64 iSize; /* Size of this allocation */
16857 struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
16858 char nBacktrace; /* Number of backtraces on this alloc */
16859 char nBacktraceSlots; /* Available backtrace slots */
16860 u8 nTitle; /* Bytes of title; includes '\0' */
16861 u8 eType; /* Allocation type code */
16862 int iForeGuard; /* Guard word for sanity */
16866 ** Guard words
16868 #define FOREGUARD 0x80F5E153
16869 #define REARGUARD 0xE4676B53
16872 ** Number of malloc size increments to track.
16874 #define NCSIZE 1000
16877 ** All of the static variables used by this module are collected
16878 ** into a single structure named "mem". This is to keep the
16879 ** static variables organized and to reduce namespace pollution
16880 ** when this module is combined with other in the amalgamation.
16882 static struct {
16885 ** Mutex to control access to the memory allocation subsystem.
16887 sqlite3_mutex *mutex;
16890 ** Head and tail of a linked list of all outstanding allocations
16892 struct MemBlockHdr *pFirst;
16893 struct MemBlockHdr *pLast;
16896 ** The number of levels of backtrace to save in new allocations.
16898 int nBacktrace;
16899 void (*xBacktrace)(int, int, void **);
16902 ** Title text to insert in front of each block
16904 int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
16905 char zTitle[100]; /* The title text */
16908 ** sqlite3MallocDisallow() increments the following counter.
16909 ** sqlite3MallocAllow() decrements it.
16911 int disallow; /* Do not allow memory allocation */
16914 ** Gather statistics on the sizes of memory allocations.
16915 ** nAlloc[i] is the number of allocation attempts of i*8
16916 ** bytes. i==NCSIZE is the number of allocation attempts for
16917 ** sizes more than NCSIZE*8 bytes.
16919 int nAlloc[NCSIZE]; /* Total number of allocations */
16920 int nCurrent[NCSIZE]; /* Current number of allocations */
16921 int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
16923 } mem;
16927 ** Adjust memory usage statistics
16929 static void adjustStats(int iSize, int increment){
16930 int i = ROUND8(iSize)/8;
16931 if( i>NCSIZE-1 ){
16932 i = NCSIZE - 1;
16934 if( increment>0 ){
16935 mem.nAlloc[i]++;
16936 mem.nCurrent[i]++;
16937 if( mem.nCurrent[i]>mem.mxCurrent[i] ){
16938 mem.mxCurrent[i] = mem.nCurrent[i];
16940 }else{
16941 mem.nCurrent[i]--;
16942 assert( mem.nCurrent[i]>=0 );
16947 ** Given an allocation, find the MemBlockHdr for that allocation.
16949 ** This routine checks the guards at either end of the allocation and
16950 ** if they are incorrect it asserts.
16952 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
16953 struct MemBlockHdr *p;
16954 int *pInt;
16955 u8 *pU8;
16956 int nReserve;
16958 p = (struct MemBlockHdr*)pAllocation;
16959 p--;
16960 assert( p->iForeGuard==(int)FOREGUARD );
16961 nReserve = ROUND8(p->iSize);
16962 pInt = (int*)pAllocation;
16963 pU8 = (u8*)pAllocation;
16964 assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
16965 /* This checks any of the "extra" bytes allocated due
16966 ** to rounding up to an 8 byte boundary to ensure
16967 ** they haven't been overwritten.
16969 while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
16970 return p;
16974 ** Return the number of bytes currently allocated at address p.
16976 static int sqlite3MemSize(void *p){
16977 struct MemBlockHdr *pHdr;
16978 if( !p ){
16979 return 0;
16981 pHdr = sqlite3MemsysGetHeader(p);
16982 return (int)pHdr->iSize;
16986 ** Initialize the memory allocation subsystem.
16988 static int sqlite3MemInit(void *NotUsed){
16989 UNUSED_PARAMETER(NotUsed);
16990 assert( (sizeof(struct MemBlockHdr)&7) == 0 );
16991 if( !sqlite3GlobalConfig.bMemstat ){
16992 /* If memory status is enabled, then the malloc.c wrapper will already
16993 ** hold the STATIC_MEM mutex when the routines here are invoked. */
16994 mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16996 return SQLITE_OK;
17000 ** Deinitialize the memory allocation subsystem.
17002 static void sqlite3MemShutdown(void *NotUsed){
17003 UNUSED_PARAMETER(NotUsed);
17004 mem.mutex = 0;
17008 ** Round up a request size to the next valid allocation size.
17010 static int sqlite3MemRoundup(int n){
17011 return ROUND8(n);
17015 ** Fill a buffer with pseudo-random bytes. This is used to preset
17016 ** the content of a new memory allocation to unpredictable values and
17017 ** to clear the content of a freed allocation to unpredictable values.
17019 static void randomFill(char *pBuf, int nByte){
17020 unsigned int x, y, r;
17021 x = SQLITE_PTR_TO_INT(pBuf);
17022 y = nByte | 1;
17023 while( nByte >= 4 ){
17024 x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
17025 y = y*1103515245 + 12345;
17026 r = x ^ y;
17027 *(int*)pBuf = r;
17028 pBuf += 4;
17029 nByte -= 4;
17031 while( nByte-- > 0 ){
17032 x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
17033 y = y*1103515245 + 12345;
17034 r = x ^ y;
17035 *(pBuf++) = r & 0xff;
17040 ** Allocate nByte bytes of memory.
17042 static void *sqlite3MemMalloc(int nByte){
17043 struct MemBlockHdr *pHdr;
17044 void **pBt;
17045 char *z;
17046 int *pInt;
17047 void *p = 0;
17048 int totalSize;
17049 int nReserve;
17050 sqlite3_mutex_enter(mem.mutex);
17051 assert( mem.disallow==0 );
17052 nReserve = ROUND8(nByte);
17053 totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
17054 mem.nBacktrace*sizeof(void*) + mem.nTitle;
17055 p = malloc(totalSize);
17056 if( p ){
17057 z = p;
17058 pBt = (void**)&z[mem.nTitle];
17059 pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
17060 pHdr->pNext = 0;
17061 pHdr->pPrev = mem.pLast;
17062 if( mem.pLast ){
17063 mem.pLast->pNext = pHdr;
17064 }else{
17065 mem.pFirst = pHdr;
17067 mem.pLast = pHdr;
17068 pHdr->iForeGuard = FOREGUARD;
17069 pHdr->eType = MEMTYPE_HEAP;
17070 pHdr->nBacktraceSlots = mem.nBacktrace;
17071 pHdr->nTitle = mem.nTitle;
17072 if( mem.nBacktrace ){
17073 void *aAddr[40];
17074 pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
17075 memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
17076 assert(pBt[0]);
17077 if( mem.xBacktrace ){
17078 mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
17080 }else{
17081 pHdr->nBacktrace = 0;
17083 if( mem.nTitle ){
17084 memcpy(z, mem.zTitle, mem.nTitle);
17086 pHdr->iSize = nByte;
17087 adjustStats(nByte, +1);
17088 pInt = (int*)&pHdr[1];
17089 pInt[nReserve/sizeof(int)] = REARGUARD;
17090 randomFill((char*)pInt, nByte);
17091 memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
17092 p = (void*)pInt;
17094 sqlite3_mutex_leave(mem.mutex);
17095 return p;
17099 ** Free memory.
17101 static void sqlite3MemFree(void *pPrior){
17102 struct MemBlockHdr *pHdr;
17103 void **pBt;
17104 char *z;
17105 assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
17106 || mem.mutex!=0 );
17107 pHdr = sqlite3MemsysGetHeader(pPrior);
17108 pBt = (void**)pHdr;
17109 pBt -= pHdr->nBacktraceSlots;
17110 sqlite3_mutex_enter(mem.mutex);
17111 if( pHdr->pPrev ){
17112 assert( pHdr->pPrev->pNext==pHdr );
17113 pHdr->pPrev->pNext = pHdr->pNext;
17114 }else{
17115 assert( mem.pFirst==pHdr );
17116 mem.pFirst = pHdr->pNext;
17118 if( pHdr->pNext ){
17119 assert( pHdr->pNext->pPrev==pHdr );
17120 pHdr->pNext->pPrev = pHdr->pPrev;
17121 }else{
17122 assert( mem.pLast==pHdr );
17123 mem.pLast = pHdr->pPrev;
17125 z = (char*)pBt;
17126 z -= pHdr->nTitle;
17127 adjustStats((int)pHdr->iSize, -1);
17128 randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
17129 (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
17130 free(z);
17131 sqlite3_mutex_leave(mem.mutex);
17135 ** Change the size of an existing memory allocation.
17137 ** For this debugging implementation, we *always* make a copy of the
17138 ** allocation into a new place in memory. In this way, if the
17139 ** higher level code is using pointer to the old allocation, it is
17140 ** much more likely to break and we are much more liking to find
17141 ** the error.
17143 static void *sqlite3MemRealloc(void *pPrior, int nByte){
17144 struct MemBlockHdr *pOldHdr;
17145 void *pNew;
17146 assert( mem.disallow==0 );
17147 assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
17148 pOldHdr = sqlite3MemsysGetHeader(pPrior);
17149 pNew = sqlite3MemMalloc(nByte);
17150 if( pNew ){
17151 memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
17152 if( nByte>pOldHdr->iSize ){
17153 randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
17155 sqlite3MemFree(pPrior);
17157 return pNew;
17161 ** Populate the low-level memory allocation function pointers in
17162 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
17164 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
17165 static const sqlite3_mem_methods defaultMethods = {
17166 sqlite3MemMalloc,
17167 sqlite3MemFree,
17168 sqlite3MemRealloc,
17169 sqlite3MemSize,
17170 sqlite3MemRoundup,
17171 sqlite3MemInit,
17172 sqlite3MemShutdown,
17175 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
17179 ** Set the "type" of an allocation.
17181 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
17182 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
17183 struct MemBlockHdr *pHdr;
17184 pHdr = sqlite3MemsysGetHeader(p);
17185 assert( pHdr->iForeGuard==FOREGUARD );
17186 pHdr->eType = eType;
17191 ** Return TRUE if the mask of type in eType matches the type of the
17192 ** allocation p. Also return true if p==NULL.
17194 ** This routine is designed for use within an assert() statement, to
17195 ** verify the type of an allocation. For example:
17197 ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
17199 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
17200 int rc = 1;
17201 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
17202 struct MemBlockHdr *pHdr;
17203 pHdr = sqlite3MemsysGetHeader(p);
17204 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
17205 if( (pHdr->eType&eType)==0 ){
17206 rc = 0;
17209 return rc;
17213 ** Return TRUE if the mask of type in eType matches no bits of the type of the
17214 ** allocation p. Also return true if p==NULL.
17216 ** This routine is designed for use within an assert() statement, to
17217 ** verify the type of an allocation. For example:
17219 ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
17221 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
17222 int rc = 1;
17223 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
17224 struct MemBlockHdr *pHdr;
17225 pHdr = sqlite3MemsysGetHeader(p);
17226 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
17227 if( (pHdr->eType&eType)!=0 ){
17228 rc = 0;
17231 return rc;
17235 ** Set the number of backtrace levels kept for each allocation.
17236 ** A value of zero turns off backtracing. The number is always rounded
17237 ** up to a multiple of 2.
17239 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
17240 if( depth<0 ){ depth = 0; }
17241 if( depth>20 ){ depth = 20; }
17242 depth = (depth+1)&0xfe;
17243 mem.nBacktrace = depth;
17246 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
17247 mem.xBacktrace = xBacktrace;
17251 ** Set the title string for subsequent allocations.
17253 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
17254 unsigned int n = sqlite3Strlen30(zTitle) + 1;
17255 sqlite3_mutex_enter(mem.mutex);
17256 if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
17257 memcpy(mem.zTitle, zTitle, n);
17258 mem.zTitle[n] = 0;
17259 mem.nTitle = ROUND8(n);
17260 sqlite3_mutex_leave(mem.mutex);
17263 SQLITE_PRIVATE void sqlite3MemdebugSync(){
17264 struct MemBlockHdr *pHdr;
17265 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
17266 void **pBt = (void**)pHdr;
17267 pBt -= pHdr->nBacktraceSlots;
17268 mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
17273 ** Open the file indicated and write a log of all unfreed memory
17274 ** allocations into that log.
17276 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
17277 FILE *out;
17278 struct MemBlockHdr *pHdr;
17279 void **pBt;
17280 int i;
17281 out = fopen(zFilename, "w");
17282 if( out==0 ){
17283 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17284 zFilename);
17285 return;
17287 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
17288 char *z = (char*)pHdr;
17289 z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
17290 fprintf(out, "**** %lld bytes at %p from %s ****\n",
17291 pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
17292 if( pHdr->nBacktrace ){
17293 fflush(out);
17294 pBt = (void**)pHdr;
17295 pBt -= pHdr->nBacktraceSlots;
17296 backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
17297 fprintf(out, "\n");
17300 fprintf(out, "COUNTS:\n");
17301 for(i=0; i<NCSIZE-1; i++){
17302 if( mem.nAlloc[i] ){
17303 fprintf(out, " %5d: %10d %10d %10d\n",
17304 i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
17307 if( mem.nAlloc[NCSIZE-1] ){
17308 fprintf(out, " %5d: %10d %10d %10d\n",
17309 NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
17310 mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
17312 fclose(out);
17316 ** Return the number of times sqlite3MemMalloc() has been called.
17318 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
17319 int i;
17320 int nTotal = 0;
17321 for(i=0; i<NCSIZE; i++){
17322 nTotal += mem.nAlloc[i];
17324 return nTotal;
17328 #endif /* SQLITE_MEMDEBUG */
17330 /************** End of mem2.c ************************************************/
17331 /************** Begin file mem3.c ********************************************/
17333 ** 2007 October 14
17335 ** The author disclaims copyright to this source code. In place of
17336 ** a legal notice, here is a blessing:
17338 ** May you do good and not evil.
17339 ** May you find forgiveness for yourself and forgive others.
17340 ** May you share freely, never taking more than you give.
17342 *************************************************************************
17343 ** This file contains the C functions that implement a memory
17344 ** allocation subsystem for use by SQLite.
17346 ** This version of the memory allocation subsystem omits all
17347 ** use of malloc(). The SQLite user supplies a block of memory
17348 ** before calling sqlite3_initialize() from which allocations
17349 ** are made and returned by the xMalloc() and xRealloc()
17350 ** implementations. Once sqlite3_initialize() has been called,
17351 ** the amount of memory available to SQLite is fixed and cannot
17352 ** be changed.
17354 ** This version of the memory allocation subsystem is included
17355 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
17359 ** This version of the memory allocator is only built into the library
17360 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
17361 ** mean that the library will use a memory-pool by default, just that
17362 ** it is available. The mempool allocator is activated by calling
17363 ** sqlite3_config().
17365 #ifdef SQLITE_ENABLE_MEMSYS3
17368 ** Maximum size (in Mem3Blocks) of a "small" chunk.
17370 #define MX_SMALL 10
17374 ** Number of freelist hash slots
17376 #define N_HASH 61
17379 ** A memory allocation (also called a "chunk") consists of two or
17380 ** more blocks where each block is 8 bytes. The first 8 bytes are
17381 ** a header that is not returned to the user.
17383 ** A chunk is two or more blocks that is either checked out or
17384 ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
17385 ** size of the allocation in blocks if the allocation is free.
17386 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
17387 ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
17388 ** is true if the previous chunk is checked out and false if the
17389 ** previous chunk is free. The u.hdr.prevSize field is the size of
17390 ** the previous chunk in blocks if the previous chunk is on the
17391 ** freelist. If the previous chunk is checked out, then
17392 ** u.hdr.prevSize can be part of the data for that chunk and should
17393 ** not be read or written.
17395 ** We often identify a chunk by its index in mem3.aPool[]. When
17396 ** this is done, the chunk index refers to the second block of
17397 ** the chunk. In this way, the first chunk has an index of 1.
17398 ** A chunk index of 0 means "no such chunk" and is the equivalent
17399 ** of a NULL pointer.
17401 ** The second block of free chunks is of the form u.list. The
17402 ** two fields form a double-linked list of chunks of related sizes.
17403 ** Pointers to the head of the list are stored in mem3.aiSmall[]
17404 ** for smaller chunks and mem3.aiHash[] for larger chunks.
17406 ** The second block of a chunk is user data if the chunk is checked
17407 ** out. If a chunk is checked out, the user data may extend into
17408 ** the u.hdr.prevSize value of the following chunk.
17410 typedef struct Mem3Block Mem3Block;
17411 struct Mem3Block {
17412 union {
17413 struct {
17414 u32 prevSize; /* Size of previous chunk in Mem3Block elements */
17415 u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
17416 } hdr;
17417 struct {
17418 u32 next; /* Index in mem3.aPool[] of next free chunk */
17419 u32 prev; /* Index in mem3.aPool[] of previous free chunk */
17420 } list;
17421 } u;
17425 ** All of the static variables used by this module are collected
17426 ** into a single structure named "mem3". This is to keep the
17427 ** static variables organized and to reduce namespace pollution
17428 ** when this module is combined with other in the amalgamation.
17430 static SQLITE_WSD struct Mem3Global {
17432 ** Memory available for allocation. nPool is the size of the array
17433 ** (in Mem3Blocks) pointed to by aPool less 2.
17435 u32 nPool;
17436 Mem3Block *aPool;
17439 ** True if we are evaluating an out-of-memory callback.
17441 int alarmBusy;
17444 ** Mutex to control access to the memory allocation subsystem.
17446 sqlite3_mutex *mutex;
17449 ** The minimum amount of free space that we have seen.
17451 u32 mnMaster;
17454 ** iMaster is the index of the master chunk. Most new allocations
17455 ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
17456 ** of the current master. iMaster is 0 if there is not master chunk.
17457 ** The master chunk is not in either the aiHash[] or aiSmall[].
17459 u32 iMaster;
17460 u32 szMaster;
17463 ** Array of lists of free blocks according to the block size
17464 ** for smaller chunks, or a hash on the block size for larger
17465 ** chunks.
17467 u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
17468 u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
17469 } mem3 = { 97535575 };
17471 #define mem3 GLOBAL(struct Mem3Global, mem3)
17474 ** Unlink the chunk at mem3.aPool[i] from list it is currently
17475 ** on. *pRoot is the list that i is a member of.
17477 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
17478 u32 next = mem3.aPool[i].u.list.next;
17479 u32 prev = mem3.aPool[i].u.list.prev;
17480 assert( sqlite3_mutex_held(mem3.mutex) );
17481 if( prev==0 ){
17482 *pRoot = next;
17483 }else{
17484 mem3.aPool[prev].u.list.next = next;
17486 if( next ){
17487 mem3.aPool[next].u.list.prev = prev;
17489 mem3.aPool[i].u.list.next = 0;
17490 mem3.aPool[i].u.list.prev = 0;
17494 ** Unlink the chunk at index i from
17495 ** whatever list is currently a member of.
17497 static void memsys3Unlink(u32 i){
17498 u32 size, hash;
17499 assert( sqlite3_mutex_held(mem3.mutex) );
17500 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
17501 assert( i>=1 );
17502 size = mem3.aPool[i-1].u.hdr.size4x/4;
17503 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
17504 assert( size>=2 );
17505 if( size <= MX_SMALL ){
17506 memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
17507 }else{
17508 hash = size % N_HASH;
17509 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
17514 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
17515 ** at *pRoot.
17517 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
17518 assert( sqlite3_mutex_held(mem3.mutex) );
17519 mem3.aPool[i].u.list.next = *pRoot;
17520 mem3.aPool[i].u.list.prev = 0;
17521 if( *pRoot ){
17522 mem3.aPool[*pRoot].u.list.prev = i;
17524 *pRoot = i;
17528 ** Link the chunk at index i into either the appropriate
17529 ** small chunk list, or into the large chunk hash table.
17531 static void memsys3Link(u32 i){
17532 u32 size, hash;
17533 assert( sqlite3_mutex_held(mem3.mutex) );
17534 assert( i>=1 );
17535 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
17536 size = mem3.aPool[i-1].u.hdr.size4x/4;
17537 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
17538 assert( size>=2 );
17539 if( size <= MX_SMALL ){
17540 memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
17541 }else{
17542 hash = size % N_HASH;
17543 memsys3LinkIntoList(i, &mem3.aiHash[hash]);
17548 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
17549 ** will already be held (obtained by code in malloc.c) if
17550 ** sqlite3GlobalConfig.bMemStat is true.
17552 static void memsys3Enter(void){
17553 if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
17554 mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17556 sqlite3_mutex_enter(mem3.mutex);
17558 static void memsys3Leave(void){
17559 sqlite3_mutex_leave(mem3.mutex);
17563 ** Called when we are unable to satisfy an allocation of nBytes.
17565 static void memsys3OutOfMemory(int nByte){
17566 if( !mem3.alarmBusy ){
17567 mem3.alarmBusy = 1;
17568 assert( sqlite3_mutex_held(mem3.mutex) );
17569 sqlite3_mutex_leave(mem3.mutex);
17570 sqlite3_release_memory(nByte);
17571 sqlite3_mutex_enter(mem3.mutex);
17572 mem3.alarmBusy = 0;
17578 ** Chunk i is a free chunk that has been unlinked. Adjust its
17579 ** size parameters for check-out and return a pointer to the
17580 ** user portion of the chunk.
17582 static void *memsys3Checkout(u32 i, u32 nBlock){
17583 u32 x;
17584 assert( sqlite3_mutex_held(mem3.mutex) );
17585 assert( i>=1 );
17586 assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
17587 assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
17588 x = mem3.aPool[i-1].u.hdr.size4x;
17589 mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
17590 mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
17591 mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
17592 return &mem3.aPool[i];
17596 ** Carve a piece off of the end of the mem3.iMaster free chunk.
17597 ** Return a pointer to the new allocation. Or, if the master chunk
17598 ** is not large enough, return 0.
17600 static void *memsys3FromMaster(u32 nBlock){
17601 assert( sqlite3_mutex_held(mem3.mutex) );
17602 assert( mem3.szMaster>=nBlock );
17603 if( nBlock>=mem3.szMaster-1 ){
17604 /* Use the entire master */
17605 void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
17606 mem3.iMaster = 0;
17607 mem3.szMaster = 0;
17608 mem3.mnMaster = 0;
17609 return p;
17610 }else{
17611 /* Split the master block. Return the tail. */
17612 u32 newi, x;
17613 newi = mem3.iMaster + mem3.szMaster - nBlock;
17614 assert( newi > mem3.iMaster+1 );
17615 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
17616 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
17617 mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
17618 mem3.szMaster -= nBlock;
17619 mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
17620 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17621 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17622 if( mem3.szMaster < mem3.mnMaster ){
17623 mem3.mnMaster = mem3.szMaster;
17625 return (void*)&mem3.aPool[newi];
17630 ** *pRoot is the head of a list of free chunks of the same size
17631 ** or same size hash. In other words, *pRoot is an entry in either
17632 ** mem3.aiSmall[] or mem3.aiHash[].
17634 ** This routine examines all entries on the given list and tries
17635 ** to coalesce each entries with adjacent free chunks.
17637 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
17638 ** the current mem3.iMaster with the new larger chunk. In order for
17639 ** this mem3.iMaster replacement to work, the master chunk must be
17640 ** linked into the hash tables. That is not the normal state of
17641 ** affairs, of course. The calling routine must link the master
17642 ** chunk before invoking this routine, then must unlink the (possibly
17643 ** changed) master chunk once this routine has finished.
17645 static void memsys3Merge(u32 *pRoot){
17646 u32 iNext, prev, size, i, x;
17648 assert( sqlite3_mutex_held(mem3.mutex) );
17649 for(i=*pRoot; i>0; i=iNext){
17650 iNext = mem3.aPool[i].u.list.next;
17651 size = mem3.aPool[i-1].u.hdr.size4x;
17652 assert( (size&1)==0 );
17653 if( (size&2)==0 ){
17654 memsys3UnlinkFromList(i, pRoot);
17655 assert( i > mem3.aPool[i-1].u.hdr.prevSize );
17656 prev = i - mem3.aPool[i-1].u.hdr.prevSize;
17657 if( prev==iNext ){
17658 iNext = mem3.aPool[prev].u.list.next;
17660 memsys3Unlink(prev);
17661 size = i + size/4 - prev;
17662 x = mem3.aPool[prev-1].u.hdr.size4x & 2;
17663 mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
17664 mem3.aPool[prev+size-1].u.hdr.prevSize = size;
17665 memsys3Link(prev);
17666 i = prev;
17667 }else{
17668 size /= 4;
17670 if( size>mem3.szMaster ){
17671 mem3.iMaster = i;
17672 mem3.szMaster = size;
17678 ** Return a block of memory of at least nBytes in size.
17679 ** Return NULL if unable.
17681 ** This function assumes that the necessary mutexes, if any, are
17682 ** already held by the caller. Hence "Unsafe".
17684 static void *memsys3MallocUnsafe(int nByte){
17685 u32 i;
17686 u32 nBlock;
17687 u32 toFree;
17689 assert( sqlite3_mutex_held(mem3.mutex) );
17690 assert( sizeof(Mem3Block)==8 );
17691 if( nByte<=12 ){
17692 nBlock = 2;
17693 }else{
17694 nBlock = (nByte + 11)/8;
17696 assert( nBlock>=2 );
17698 /* STEP 1:
17699 ** Look for an entry of the correct size in either the small
17700 ** chunk table or in the large chunk hash table. This is
17701 ** successful most of the time (about 9 times out of 10).
17703 if( nBlock <= MX_SMALL ){
17704 i = mem3.aiSmall[nBlock-2];
17705 if( i>0 ){
17706 memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
17707 return memsys3Checkout(i, nBlock);
17709 }else{
17710 int hash = nBlock % N_HASH;
17711 for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
17712 if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
17713 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
17714 return memsys3Checkout(i, nBlock);
17719 /* STEP 2:
17720 ** Try to satisfy the allocation by carving a piece off of the end
17721 ** of the master chunk. This step usually works if step 1 fails.
17723 if( mem3.szMaster>=nBlock ){
17724 return memsys3FromMaster(nBlock);
17728 /* STEP 3:
17729 ** Loop through the entire memory pool. Coalesce adjacent free
17730 ** chunks. Recompute the master chunk as the largest free chunk.
17731 ** Then try again to satisfy the allocation by carving a piece off
17732 ** of the end of the master chunk. This step happens very
17733 ** rarely (we hope!)
17735 for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
17736 memsys3OutOfMemory(toFree);
17737 if( mem3.iMaster ){
17738 memsys3Link(mem3.iMaster);
17739 mem3.iMaster = 0;
17740 mem3.szMaster = 0;
17742 for(i=0; i<N_HASH; i++){
17743 memsys3Merge(&mem3.aiHash[i]);
17745 for(i=0; i<MX_SMALL-1; i++){
17746 memsys3Merge(&mem3.aiSmall[i]);
17748 if( mem3.szMaster ){
17749 memsys3Unlink(mem3.iMaster);
17750 if( mem3.szMaster>=nBlock ){
17751 return memsys3FromMaster(nBlock);
17756 /* If none of the above worked, then we fail. */
17757 return 0;
17761 ** Free an outstanding memory allocation.
17763 ** This function assumes that the necessary mutexes, if any, are
17764 ** already held by the caller. Hence "Unsafe".
17766 static void memsys3FreeUnsafe(void *pOld){
17767 Mem3Block *p = (Mem3Block*)pOld;
17768 int i;
17769 u32 size, x;
17770 assert( sqlite3_mutex_held(mem3.mutex) );
17771 assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
17772 i = p - mem3.aPool;
17773 assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
17774 size = mem3.aPool[i-1].u.hdr.size4x/4;
17775 assert( i+size<=mem3.nPool+1 );
17776 mem3.aPool[i-1].u.hdr.size4x &= ~1;
17777 mem3.aPool[i+size-1].u.hdr.prevSize = size;
17778 mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
17779 memsys3Link(i);
17781 /* Try to expand the master using the newly freed chunk */
17782 if( mem3.iMaster ){
17783 while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
17784 size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
17785 mem3.iMaster -= size;
17786 mem3.szMaster += size;
17787 memsys3Unlink(mem3.iMaster);
17788 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17789 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17790 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
17792 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17793 while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
17794 memsys3Unlink(mem3.iMaster+mem3.szMaster);
17795 mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
17796 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17797 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
17803 ** Return the size of an outstanding allocation, in bytes. The
17804 ** size returned omits the 8-byte header overhead. This only
17805 ** works for chunks that are currently checked out.
17807 static int memsys3Size(void *p){
17808 Mem3Block *pBlock;
17809 if( p==0 ) return 0;
17810 pBlock = (Mem3Block*)p;
17811 assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
17812 return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
17816 ** Round up a request size to the next valid allocation size.
17818 static int memsys3Roundup(int n){
17819 if( n<=12 ){
17820 return 12;
17821 }else{
17822 return ((n+11)&~7) - 4;
17827 ** Allocate nBytes of memory.
17829 static void *memsys3Malloc(int nBytes){
17830 sqlite3_int64 *p;
17831 assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
17832 memsys3Enter();
17833 p = memsys3MallocUnsafe(nBytes);
17834 memsys3Leave();
17835 return (void*)p;
17839 ** Free memory.
17841 static void memsys3Free(void *pPrior){
17842 assert( pPrior );
17843 memsys3Enter();
17844 memsys3FreeUnsafe(pPrior);
17845 memsys3Leave();
17849 ** Change the size of an existing memory allocation
17851 static void *memsys3Realloc(void *pPrior, int nBytes){
17852 int nOld;
17853 void *p;
17854 if( pPrior==0 ){
17855 return sqlite3_malloc(nBytes);
17857 if( nBytes<=0 ){
17858 sqlite3_free(pPrior);
17859 return 0;
17861 nOld = memsys3Size(pPrior);
17862 if( nBytes<=nOld && nBytes>=nOld-128 ){
17863 return pPrior;
17865 memsys3Enter();
17866 p = memsys3MallocUnsafe(nBytes);
17867 if( p ){
17868 if( nOld<nBytes ){
17869 memcpy(p, pPrior, nOld);
17870 }else{
17871 memcpy(p, pPrior, nBytes);
17873 memsys3FreeUnsafe(pPrior);
17875 memsys3Leave();
17876 return p;
17880 ** Initialize this module.
17882 static int memsys3Init(void *NotUsed){
17883 UNUSED_PARAMETER(NotUsed);
17884 if( !sqlite3GlobalConfig.pHeap ){
17885 return SQLITE_ERROR;
17888 /* Store a pointer to the memory block in global structure mem3. */
17889 assert( sizeof(Mem3Block)==8 );
17890 mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
17891 mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
17893 /* Initialize the master block. */
17894 mem3.szMaster = mem3.nPool;
17895 mem3.mnMaster = mem3.szMaster;
17896 mem3.iMaster = 1;
17897 mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
17898 mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
17899 mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
17901 return SQLITE_OK;
17905 ** Deinitialize this module.
17907 static void memsys3Shutdown(void *NotUsed){
17908 UNUSED_PARAMETER(NotUsed);
17909 mem3.mutex = 0;
17910 return;
17916 ** Open the file indicated and write a log of all unfreed memory
17917 ** allocations into that log.
17919 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
17920 #ifdef SQLITE_DEBUG
17921 FILE *out;
17922 u32 i, j;
17923 u32 size;
17924 if( zFilename==0 || zFilename[0]==0 ){
17925 out = stdout;
17926 }else{
17927 out = fopen(zFilename, "w");
17928 if( out==0 ){
17929 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17930 zFilename);
17931 return;
17934 memsys3Enter();
17935 fprintf(out, "CHUNKS:\n");
17936 for(i=1; i<=mem3.nPool; i+=size/4){
17937 size = mem3.aPool[i-1].u.hdr.size4x;
17938 if( size/4<=1 ){
17939 fprintf(out, "%p size error\n", &mem3.aPool[i]);
17940 assert( 0 );
17941 break;
17943 if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
17944 fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
17945 assert( 0 );
17946 break;
17948 if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
17949 fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
17950 assert( 0 );
17951 break;
17953 if( size&1 ){
17954 fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
17955 }else{
17956 fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
17957 i==mem3.iMaster ? " **master**" : "");
17960 for(i=0; i<MX_SMALL-1; i++){
17961 if( mem3.aiSmall[i]==0 ) continue;
17962 fprintf(out, "small(%2d):", i);
17963 for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
17964 fprintf(out, " %p(%d)", &mem3.aPool[j],
17965 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
17967 fprintf(out, "\n");
17969 for(i=0; i<N_HASH; i++){
17970 if( mem3.aiHash[i]==0 ) continue;
17971 fprintf(out, "hash(%2d):", i);
17972 for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
17973 fprintf(out, " %p(%d)", &mem3.aPool[j],
17974 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
17976 fprintf(out, "\n");
17978 fprintf(out, "master=%d\n", mem3.iMaster);
17979 fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
17980 fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
17981 sqlite3_mutex_leave(mem3.mutex);
17982 if( out==stdout ){
17983 fflush(stdout);
17984 }else{
17985 fclose(out);
17987 #else
17988 UNUSED_PARAMETER(zFilename);
17989 #endif
17993 ** This routine is the only routine in this file with external
17994 ** linkage.
17996 ** Populate the low-level memory allocation function pointers in
17997 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
17998 ** arguments specify the block of memory to manage.
18000 ** This routine is only called by sqlite3_config(), and therefore
18001 ** is not required to be threadsafe (it is not).
18003 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
18004 static const sqlite3_mem_methods mempoolMethods = {
18005 memsys3Malloc,
18006 memsys3Free,
18007 memsys3Realloc,
18008 memsys3Size,
18009 memsys3Roundup,
18010 memsys3Init,
18011 memsys3Shutdown,
18014 return &mempoolMethods;
18017 #endif /* SQLITE_ENABLE_MEMSYS3 */
18019 /************** End of mem3.c ************************************************/
18020 /************** Begin file mem5.c ********************************************/
18022 ** 2007 October 14
18024 ** The author disclaims copyright to this source code. In place of
18025 ** a legal notice, here is a blessing:
18027 ** May you do good and not evil.
18028 ** May you find forgiveness for yourself and forgive others.
18029 ** May you share freely, never taking more than you give.
18031 *************************************************************************
18032 ** This file contains the C functions that implement a memory
18033 ** allocation subsystem for use by SQLite.
18035 ** This version of the memory allocation subsystem omits all
18036 ** use of malloc(). The application gives SQLite a block of memory
18037 ** before calling sqlite3_initialize() from which allocations
18038 ** are made and returned by the xMalloc() and xRealloc()
18039 ** implementations. Once sqlite3_initialize() has been called,
18040 ** the amount of memory available to SQLite is fixed and cannot
18041 ** be changed.
18043 ** This version of the memory allocation subsystem is included
18044 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
18046 ** This memory allocator uses the following algorithm:
18048 ** 1. All memory allocations sizes are rounded up to a power of 2.
18050 ** 2. If two adjacent free blocks are the halves of a larger block,
18051 ** then the two blocks are coalesced into the single larger block.
18053 ** 3. New memory is allocated from the first available free block.
18055 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
18056 ** Concerning Dynamic Storage Allocation". Journal of the Association for
18057 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
18059 ** Let n be the size of the largest allocation divided by the minimum
18060 ** allocation size (after rounding all sizes up to a power of 2.) Let M
18061 ** be the maximum amount of memory ever outstanding at one time. Let
18062 ** N be the total amount of memory available for allocation. Robson
18063 ** proved that this memory allocator will never breakdown due to
18064 ** fragmentation as long as the following constraint holds:
18066 ** N >= M*(1 + log2(n)/2) - n + 1
18068 ** The sqlite3_status() logic tracks the maximum values of n and M so
18069 ** that an application can, at any time, verify this constraint.
18073 ** This version of the memory allocator is used only when
18074 ** SQLITE_ENABLE_MEMSYS5 is defined.
18076 #ifdef SQLITE_ENABLE_MEMSYS5
18079 ** A minimum allocation is an instance of the following structure.
18080 ** Larger allocations are an array of these structures where the
18081 ** size of the array is a power of 2.
18083 ** The size of this object must be a power of two. That fact is
18084 ** verified in memsys5Init().
18086 typedef struct Mem5Link Mem5Link;
18087 struct Mem5Link {
18088 int next; /* Index of next free chunk */
18089 int prev; /* Index of previous free chunk */
18093 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
18094 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
18095 ** it is not actually possible to reach this limit.
18097 #define LOGMAX 30
18100 ** Masks used for mem5.aCtrl[] elements.
18102 #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
18103 #define CTRL_FREE 0x20 /* True if not checked out */
18106 ** All of the static variables used by this module are collected
18107 ** into a single structure named "mem5". This is to keep the
18108 ** static variables organized and to reduce namespace pollution
18109 ** when this module is combined with other in the amalgamation.
18111 static SQLITE_WSD struct Mem5Global {
18113 ** Memory available for allocation
18115 int szAtom; /* Smallest possible allocation in bytes */
18116 int nBlock; /* Number of szAtom sized blocks in zPool */
18117 u8 *zPool; /* Memory available to be allocated */
18120 ** Mutex to control access to the memory allocation subsystem.
18122 sqlite3_mutex *mutex;
18125 ** Performance statistics
18127 u64 nAlloc; /* Total number of calls to malloc */
18128 u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
18129 u64 totalExcess; /* Total internal fragmentation */
18130 u32 currentOut; /* Current checkout, including internal fragmentation */
18131 u32 currentCount; /* Current number of distinct checkouts */
18132 u32 maxOut; /* Maximum instantaneous currentOut */
18133 u32 maxCount; /* Maximum instantaneous currentCount */
18134 u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
18137 ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
18138 ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
18139 ** and so forth.
18141 int aiFreelist[LOGMAX+1];
18144 ** Space for tracking which blocks are checked out and the size
18145 ** of each block. One byte per block.
18147 u8 *aCtrl;
18149 } mem5;
18152 ** Access the static variable through a macro for SQLITE_OMIT_WSD.
18154 #define mem5 GLOBAL(struct Mem5Global, mem5)
18157 ** Assuming mem5.zPool is divided up into an array of Mem5Link
18158 ** structures, return a pointer to the idx-th such link.
18160 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
18163 ** Unlink the chunk at mem5.aPool[i] from list it is currently
18164 ** on. It should be found on mem5.aiFreelist[iLogsize].
18166 static void memsys5Unlink(int i, int iLogsize){
18167 int next, prev;
18168 assert( i>=0 && i<mem5.nBlock );
18169 assert( iLogsize>=0 && iLogsize<=LOGMAX );
18170 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
18172 next = MEM5LINK(i)->next;
18173 prev = MEM5LINK(i)->prev;
18174 if( prev<0 ){
18175 mem5.aiFreelist[iLogsize] = next;
18176 }else{
18177 MEM5LINK(prev)->next = next;
18179 if( next>=0 ){
18180 MEM5LINK(next)->prev = prev;
18185 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
18186 ** free list.
18188 static void memsys5Link(int i, int iLogsize){
18189 int x;
18190 assert( sqlite3_mutex_held(mem5.mutex) );
18191 assert( i>=0 && i<mem5.nBlock );
18192 assert( iLogsize>=0 && iLogsize<=LOGMAX );
18193 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
18195 x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
18196 MEM5LINK(i)->prev = -1;
18197 if( x>=0 ){
18198 assert( x<mem5.nBlock );
18199 MEM5LINK(x)->prev = i;
18201 mem5.aiFreelist[iLogsize] = i;
18205 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
18206 ** will already be held (obtained by code in malloc.c) if
18207 ** sqlite3GlobalConfig.bMemStat is true.
18209 static void memsys5Enter(void){
18210 sqlite3_mutex_enter(mem5.mutex);
18212 static void memsys5Leave(void){
18213 sqlite3_mutex_leave(mem5.mutex);
18217 ** Return the size of an outstanding allocation, in bytes. The
18218 ** size returned omits the 8-byte header overhead. This only
18219 ** works for chunks that are currently checked out.
18221 static int memsys5Size(void *p){
18222 int iSize = 0;
18223 if( p ){
18224 int i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
18225 assert( i>=0 && i<mem5.nBlock );
18226 iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
18228 return iSize;
18232 ** Return a block of memory of at least nBytes in size.
18233 ** Return NULL if unable. Return NULL if nBytes==0.
18235 ** The caller guarantees that nByte is positive.
18237 ** The caller has obtained a mutex prior to invoking this
18238 ** routine so there is never any chance that two or more
18239 ** threads can be in this routine at the same time.
18241 static void *memsys5MallocUnsafe(int nByte){
18242 int i; /* Index of a mem5.aPool[] slot */
18243 int iBin; /* Index into mem5.aiFreelist[] */
18244 int iFullSz; /* Size of allocation rounded up to power of 2 */
18245 int iLogsize; /* Log2 of iFullSz/POW2_MIN */
18247 /* nByte must be a positive */
18248 assert( nByte>0 );
18250 /* Keep track of the maximum allocation request. Even unfulfilled
18251 ** requests are counted */
18252 if( (u32)nByte>mem5.maxRequest ){
18253 mem5.maxRequest = nByte;
18256 /* Abort if the requested allocation size is larger than the largest
18257 ** power of two that we can represent using 32-bit signed integers.
18259 if( nByte > 0x40000000 ){
18260 return 0;
18263 /* Round nByte up to the next valid power of two */
18264 for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
18266 /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
18267 ** block. If not, then split a block of the next larger power of
18268 ** two in order to create a new free block of size iLogsize.
18270 for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
18271 if( iBin>LOGMAX ){
18272 testcase( sqlite3GlobalConfig.xLog!=0 );
18273 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
18274 return 0;
18276 i = mem5.aiFreelist[iBin];
18277 memsys5Unlink(i, iBin);
18278 while( iBin>iLogsize ){
18279 int newSize;
18281 iBin--;
18282 newSize = 1 << iBin;
18283 mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
18284 memsys5Link(i+newSize, iBin);
18286 mem5.aCtrl[i] = iLogsize;
18288 /* Update allocator performance statistics. */
18289 mem5.nAlloc++;
18290 mem5.totalAlloc += iFullSz;
18291 mem5.totalExcess += iFullSz - nByte;
18292 mem5.currentCount++;
18293 mem5.currentOut += iFullSz;
18294 if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
18295 if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
18297 #ifdef SQLITE_DEBUG
18298 /* Make sure the allocated memory does not assume that it is set to zero
18299 ** or retains a value from a previous allocation */
18300 memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
18301 #endif
18303 /* Return a pointer to the allocated memory. */
18304 return (void*)&mem5.zPool[i*mem5.szAtom];
18308 ** Free an outstanding memory allocation.
18310 static void memsys5FreeUnsafe(void *pOld){
18311 u32 size, iLogsize;
18312 int iBlock;
18314 /* Set iBlock to the index of the block pointed to by pOld in
18315 ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
18317 iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
18319 /* Check that the pointer pOld points to a valid, non-free block. */
18320 assert( iBlock>=0 && iBlock<mem5.nBlock );
18321 assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
18322 assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
18324 iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
18325 size = 1<<iLogsize;
18326 assert( iBlock+size-1<(u32)mem5.nBlock );
18328 mem5.aCtrl[iBlock] |= CTRL_FREE;
18329 mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
18330 assert( mem5.currentCount>0 );
18331 assert( mem5.currentOut>=(size*mem5.szAtom) );
18332 mem5.currentCount--;
18333 mem5.currentOut -= size*mem5.szAtom;
18334 assert( mem5.currentOut>0 || mem5.currentCount==0 );
18335 assert( mem5.currentCount>0 || mem5.currentOut==0 );
18337 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
18338 while( ALWAYS(iLogsize<LOGMAX) ){
18339 int iBuddy;
18340 if( (iBlock>>iLogsize) & 1 ){
18341 iBuddy = iBlock - size;
18342 }else{
18343 iBuddy = iBlock + size;
18345 assert( iBuddy>=0 );
18346 if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
18347 if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
18348 memsys5Unlink(iBuddy, iLogsize);
18349 iLogsize++;
18350 if( iBuddy<iBlock ){
18351 mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
18352 mem5.aCtrl[iBlock] = 0;
18353 iBlock = iBuddy;
18354 }else{
18355 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
18356 mem5.aCtrl[iBuddy] = 0;
18358 size *= 2;
18361 #ifdef SQLITE_DEBUG
18362 /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
18363 ** not used after being freed */
18364 memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
18365 #endif
18367 memsys5Link(iBlock, iLogsize);
18371 ** Allocate nBytes of memory.
18373 static void *memsys5Malloc(int nBytes){
18374 sqlite3_int64 *p = 0;
18375 if( nBytes>0 ){
18376 memsys5Enter();
18377 p = memsys5MallocUnsafe(nBytes);
18378 memsys5Leave();
18380 return (void*)p;
18384 ** Free memory.
18386 ** The outer layer memory allocator prevents this routine from
18387 ** being called with pPrior==0.
18389 static void memsys5Free(void *pPrior){
18390 assert( pPrior!=0 );
18391 memsys5Enter();
18392 memsys5FreeUnsafe(pPrior);
18393 memsys5Leave();
18397 ** Change the size of an existing memory allocation.
18399 ** The outer layer memory allocator prevents this routine from
18400 ** being called with pPrior==0.
18402 ** nBytes is always a value obtained from a prior call to
18403 ** memsys5Round(). Hence nBytes is always a non-negative power
18404 ** of two. If nBytes==0 that means that an oversize allocation
18405 ** (an allocation larger than 0x40000000) was requested and this
18406 ** routine should return 0 without freeing pPrior.
18408 static void *memsys5Realloc(void *pPrior, int nBytes){
18409 int nOld;
18410 void *p;
18411 assert( pPrior!=0 );
18412 assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
18413 assert( nBytes>=0 );
18414 if( nBytes==0 ){
18415 return 0;
18417 nOld = memsys5Size(pPrior);
18418 if( nBytes<=nOld ){
18419 return pPrior;
18421 memsys5Enter();
18422 p = memsys5MallocUnsafe(nBytes);
18423 if( p ){
18424 memcpy(p, pPrior, nOld);
18425 memsys5FreeUnsafe(pPrior);
18427 memsys5Leave();
18428 return p;
18432 ** Round up a request size to the next valid allocation size. If
18433 ** the allocation is too large to be handled by this allocation system,
18434 ** return 0.
18436 ** All allocations must be a power of two and must be expressed by a
18437 ** 32-bit signed integer. Hence the largest allocation is 0x40000000
18438 ** or 1073741824 bytes.
18440 static int memsys5Roundup(int n){
18441 int iFullSz;
18442 if( n > 0x40000000 ) return 0;
18443 for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
18444 return iFullSz;
18448 ** Return the ceiling of the logarithm base 2 of iValue.
18450 ** Examples: memsys5Log(1) -> 0
18451 ** memsys5Log(2) -> 1
18452 ** memsys5Log(4) -> 2
18453 ** memsys5Log(5) -> 3
18454 ** memsys5Log(8) -> 3
18455 ** memsys5Log(9) -> 4
18457 static int memsys5Log(int iValue){
18458 int iLog;
18459 for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
18460 return iLog;
18464 ** Initialize the memory allocator.
18466 ** This routine is not threadsafe. The caller must be holding a mutex
18467 ** to prevent multiple threads from entering at the same time.
18469 static int memsys5Init(void *NotUsed){
18470 int ii; /* Loop counter */
18471 int nByte; /* Number of bytes of memory available to this allocator */
18472 u8 *zByte; /* Memory usable by this allocator */
18473 int nMinLog; /* Log base 2 of minimum allocation size in bytes */
18474 int iOffset; /* An offset into mem5.aCtrl[] */
18476 UNUSED_PARAMETER(NotUsed);
18478 /* For the purposes of this routine, disable the mutex */
18479 mem5.mutex = 0;
18481 /* The size of a Mem5Link object must be a power of two. Verify that
18482 ** this is case.
18484 assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
18486 nByte = sqlite3GlobalConfig.nHeap;
18487 zByte = (u8*)sqlite3GlobalConfig.pHeap;
18488 assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
18490 /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
18491 nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
18492 mem5.szAtom = (1<<nMinLog);
18493 while( (int)sizeof(Mem5Link)>mem5.szAtom ){
18494 mem5.szAtom = mem5.szAtom << 1;
18497 mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
18498 mem5.zPool = zByte;
18499 mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
18501 for(ii=0; ii<=LOGMAX; ii++){
18502 mem5.aiFreelist[ii] = -1;
18505 iOffset = 0;
18506 for(ii=LOGMAX; ii>=0; ii--){
18507 int nAlloc = (1<<ii);
18508 if( (iOffset+nAlloc)<=mem5.nBlock ){
18509 mem5.aCtrl[iOffset] = ii | CTRL_FREE;
18510 memsys5Link(iOffset, ii);
18511 iOffset += nAlloc;
18513 assert((iOffset+nAlloc)>mem5.nBlock);
18516 /* If a mutex is required for normal operation, allocate one */
18517 if( sqlite3GlobalConfig.bMemstat==0 ){
18518 mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18521 return SQLITE_OK;
18525 ** Deinitialize this module.
18527 static void memsys5Shutdown(void *NotUsed){
18528 UNUSED_PARAMETER(NotUsed);
18529 mem5.mutex = 0;
18530 return;
18533 #ifdef SQLITE_TEST
18535 ** Open the file indicated and write a log of all unfreed memory
18536 ** allocations into that log.
18538 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
18539 FILE *out;
18540 int i, j, n;
18541 int nMinLog;
18543 if( zFilename==0 || zFilename[0]==0 ){
18544 out = stdout;
18545 }else{
18546 out = fopen(zFilename, "w");
18547 if( out==0 ){
18548 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
18549 zFilename);
18550 return;
18553 memsys5Enter();
18554 nMinLog = memsys5Log(mem5.szAtom);
18555 for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
18556 for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
18557 fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
18559 fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
18560 fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
18561 fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
18562 fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
18563 fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
18564 fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
18565 fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
18566 fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
18567 memsys5Leave();
18568 if( out==stdout ){
18569 fflush(stdout);
18570 }else{
18571 fclose(out);
18574 #endif
18577 ** This routine is the only routine in this file with external
18578 ** linkage. It returns a pointer to a static sqlite3_mem_methods
18579 ** struct populated with the memsys5 methods.
18581 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
18582 static const sqlite3_mem_methods memsys5Methods = {
18583 memsys5Malloc,
18584 memsys5Free,
18585 memsys5Realloc,
18586 memsys5Size,
18587 memsys5Roundup,
18588 memsys5Init,
18589 memsys5Shutdown,
18592 return &memsys5Methods;
18595 #endif /* SQLITE_ENABLE_MEMSYS5 */
18597 /************** End of mem5.c ************************************************/
18598 /************** Begin file mutex.c *******************************************/
18600 ** 2007 August 14
18602 ** The author disclaims copyright to this source code. In place of
18603 ** a legal notice, here is a blessing:
18605 ** May you do good and not evil.
18606 ** May you find forgiveness for yourself and forgive others.
18607 ** May you share freely, never taking more than you give.
18609 *************************************************************************
18610 ** This file contains the C functions that implement mutexes.
18612 ** This file contains code that is common across all mutex implementations.
18615 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
18617 ** For debugging purposes, record when the mutex subsystem is initialized
18618 ** and uninitialized so that we can assert() if there is an attempt to
18619 ** allocate a mutex while the system is uninitialized.
18621 static SQLITE_WSD int mutexIsInit = 0;
18622 #endif /* SQLITE_DEBUG */
18625 #ifndef SQLITE_MUTEX_OMIT
18627 ** Initialize the mutex system.
18629 SQLITE_PRIVATE int sqlite3MutexInit(void){
18630 int rc = SQLITE_OK;
18631 if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
18632 /* If the xMutexAlloc method has not been set, then the user did not
18633 ** install a mutex implementation via sqlite3_config() prior to
18634 ** sqlite3_initialize() being called. This block copies pointers to
18635 ** the default implementation into the sqlite3GlobalConfig structure.
18637 sqlite3_mutex_methods const *pFrom;
18638 sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
18640 if( sqlite3GlobalConfig.bCoreMutex ){
18641 pFrom = sqlite3DefaultMutex();
18642 }else{
18643 pFrom = sqlite3NoopMutex();
18645 memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
18646 memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
18647 sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
18648 pTo->xMutexAlloc = pFrom->xMutexAlloc;
18650 rc = sqlite3GlobalConfig.mutex.xMutexInit();
18652 #ifdef SQLITE_DEBUG
18653 GLOBAL(int, mutexIsInit) = 1;
18654 #endif
18656 return rc;
18660 ** Shutdown the mutex system. This call frees resources allocated by
18661 ** sqlite3MutexInit().
18663 SQLITE_PRIVATE int sqlite3MutexEnd(void){
18664 int rc = SQLITE_OK;
18665 if( sqlite3GlobalConfig.mutex.xMutexEnd ){
18666 rc = sqlite3GlobalConfig.mutex.xMutexEnd();
18669 #ifdef SQLITE_DEBUG
18670 GLOBAL(int, mutexIsInit) = 0;
18671 #endif
18673 return rc;
18677 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
18679 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
18680 #ifndef SQLITE_OMIT_AUTOINIT
18681 if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
18682 #endif
18683 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
18686 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
18687 if( !sqlite3GlobalConfig.bCoreMutex ){
18688 return 0;
18690 assert( GLOBAL(int, mutexIsInit) );
18691 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
18695 ** Free a dynamic mutex.
18697 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
18698 if( p ){
18699 sqlite3GlobalConfig.mutex.xMutexFree(p);
18704 ** Obtain the mutex p. If some other thread already has the mutex, block
18705 ** until it can be obtained.
18707 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
18708 if( p ){
18709 sqlite3GlobalConfig.mutex.xMutexEnter(p);
18714 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
18715 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
18717 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
18718 int rc = SQLITE_OK;
18719 if( p ){
18720 return sqlite3GlobalConfig.mutex.xMutexTry(p);
18722 return rc;
18726 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
18727 ** entered by the same thread. The behavior is undefined if the mutex
18728 ** is not currently entered. If a NULL pointer is passed as an argument
18729 ** this function is a no-op.
18731 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
18732 if( p ){
18733 sqlite3GlobalConfig.mutex.xMutexLeave(p);
18737 #ifndef NDEBUG
18739 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18740 ** intended for use inside assert() statements.
18742 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
18743 return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
18745 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
18746 return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
18748 #endif
18750 #endif /* !defined(SQLITE_MUTEX_OMIT) */
18752 /************** End of mutex.c ***********************************************/
18753 /************** Begin file mutex_noop.c **************************************/
18755 ** 2008 October 07
18757 ** The author disclaims copyright to this source code. In place of
18758 ** a legal notice, here is a blessing:
18760 ** May you do good and not evil.
18761 ** May you find forgiveness for yourself and forgive others.
18762 ** May you share freely, never taking more than you give.
18764 *************************************************************************
18765 ** This file contains the C functions that implement mutexes.
18767 ** This implementation in this file does not provide any mutual
18768 ** exclusion and is thus suitable for use only in applications
18769 ** that use SQLite in a single thread. The routines defined
18770 ** here are place-holders. Applications can substitute working
18771 ** mutex routines at start-time using the
18773 ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
18775 ** interface.
18777 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
18778 ** that does error checking on mutexes to make sure they are being
18779 ** called correctly.
18782 #ifndef SQLITE_MUTEX_OMIT
18784 #ifndef SQLITE_DEBUG
18786 ** Stub routines for all mutex methods.
18788 ** This routines provide no mutual exclusion or error checking.
18790 static int noopMutexInit(void){ return SQLITE_OK; }
18791 static int noopMutexEnd(void){ return SQLITE_OK; }
18792 static sqlite3_mutex *noopMutexAlloc(int id){
18793 UNUSED_PARAMETER(id);
18794 return (sqlite3_mutex*)8;
18796 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
18797 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
18798 static int noopMutexTry(sqlite3_mutex *p){
18799 UNUSED_PARAMETER(p);
18800 return SQLITE_OK;
18802 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
18804 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
18805 static const sqlite3_mutex_methods sMutex = {
18806 noopMutexInit,
18807 noopMutexEnd,
18808 noopMutexAlloc,
18809 noopMutexFree,
18810 noopMutexEnter,
18811 noopMutexTry,
18812 noopMutexLeave,
18818 return &sMutex;
18820 #endif /* !SQLITE_DEBUG */
18822 #ifdef SQLITE_DEBUG
18824 ** In this implementation, error checking is provided for testing
18825 ** and debugging purposes. The mutexes still do not provide any
18826 ** mutual exclusion.
18830 ** The mutex object
18832 typedef struct sqlite3_debug_mutex {
18833 int id; /* The mutex type */
18834 int cnt; /* Number of entries without a matching leave */
18835 } sqlite3_debug_mutex;
18838 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18839 ** intended for use inside assert() statements.
18841 static int debugMutexHeld(sqlite3_mutex *pX){
18842 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18843 return p==0 || p->cnt>0;
18845 static int debugMutexNotheld(sqlite3_mutex *pX){
18846 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18847 return p==0 || p->cnt==0;
18851 ** Initialize and deinitialize the mutex subsystem.
18853 static int debugMutexInit(void){ return SQLITE_OK; }
18854 static int debugMutexEnd(void){ return SQLITE_OK; }
18857 ** The sqlite3_mutex_alloc() routine allocates a new
18858 ** mutex and returns a pointer to it. If it returns NULL
18859 ** that means that a mutex could not be allocated.
18861 static sqlite3_mutex *debugMutexAlloc(int id){
18862 static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_APP3 - 1];
18863 sqlite3_debug_mutex *pNew = 0;
18864 switch( id ){
18865 case SQLITE_MUTEX_FAST:
18866 case SQLITE_MUTEX_RECURSIVE: {
18867 pNew = sqlite3Malloc(sizeof(*pNew));
18868 if( pNew ){
18869 pNew->id = id;
18870 pNew->cnt = 0;
18872 break;
18874 default: {
18875 assert( id-2 >= 0 );
18876 assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
18877 pNew = &aStatic[id-2];
18878 pNew->id = id;
18879 break;
18882 return (sqlite3_mutex*)pNew;
18886 ** This routine deallocates a previously allocated mutex.
18888 static void debugMutexFree(sqlite3_mutex *pX){
18889 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18890 assert( p->cnt==0 );
18891 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18892 sqlite3_free(p);
18896 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18897 ** to enter a mutex. If another thread is already within the mutex,
18898 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18899 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
18900 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
18901 ** be entered multiple times by the same thread. In such cases the,
18902 ** mutex must be exited an equal number of times before another thread
18903 ** can enter. If the same thread tries to enter any other kind of mutex
18904 ** more than once, the behavior is undefined.
18906 static void debugMutexEnter(sqlite3_mutex *pX){
18907 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18908 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18909 p->cnt++;
18911 static int debugMutexTry(sqlite3_mutex *pX){
18912 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18913 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18914 p->cnt++;
18915 return SQLITE_OK;
18919 ** The sqlite3_mutex_leave() routine exits a mutex that was
18920 ** previously entered by the same thread. The behavior
18921 ** is undefined if the mutex is not currently entered or
18922 ** is not currently allocated. SQLite will never do either.
18924 static void debugMutexLeave(sqlite3_mutex *pX){
18925 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18926 assert( debugMutexHeld(pX) );
18927 p->cnt--;
18928 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18931 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
18932 static const sqlite3_mutex_methods sMutex = {
18933 debugMutexInit,
18934 debugMutexEnd,
18935 debugMutexAlloc,
18936 debugMutexFree,
18937 debugMutexEnter,
18938 debugMutexTry,
18939 debugMutexLeave,
18941 debugMutexHeld,
18942 debugMutexNotheld
18945 return &sMutex;
18947 #endif /* SQLITE_DEBUG */
18950 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
18951 ** is used regardless of the run-time threadsafety setting.
18953 #ifdef SQLITE_MUTEX_NOOP
18954 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18955 return sqlite3NoopMutex();
18957 #endif /* defined(SQLITE_MUTEX_NOOP) */
18958 #endif /* !defined(SQLITE_MUTEX_OMIT) */
18960 /************** End of mutex_noop.c ******************************************/
18961 /************** Begin file mutex_unix.c **************************************/
18963 ** 2007 August 28
18965 ** The author disclaims copyright to this source code. In place of
18966 ** a legal notice, here is a blessing:
18968 ** May you do good and not evil.
18969 ** May you find forgiveness for yourself and forgive others.
18970 ** May you share freely, never taking more than you give.
18972 *************************************************************************
18973 ** This file contains the C functions that implement mutexes for pthreads
18977 ** The code in this file is only used if we are compiling threadsafe
18978 ** under unix with pthreads.
18980 ** Note that this implementation requires a version of pthreads that
18981 ** supports recursive mutexes.
18983 #ifdef SQLITE_MUTEX_PTHREADS
18985 #include <pthread.h>
18988 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
18989 ** are necessary under two condidtions: (1) Debug builds and (2) using
18990 ** home-grown mutexes. Encapsulate these conditions into a single #define.
18992 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
18993 # define SQLITE_MUTEX_NREF 1
18994 #else
18995 # define SQLITE_MUTEX_NREF 0
18996 #endif
18999 ** Each recursive mutex is an instance of the following structure.
19001 struct sqlite3_mutex {
19002 pthread_mutex_t mutex; /* Mutex controlling the lock */
19003 #if SQLITE_MUTEX_NREF
19004 int id; /* Mutex type */
19005 volatile int nRef; /* Number of entrances */
19006 volatile pthread_t owner; /* Thread that is within this mutex */
19007 int trace; /* True to trace changes */
19008 #endif
19010 #if SQLITE_MUTEX_NREF
19011 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
19012 #else
19013 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
19014 #endif
19017 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
19018 ** intended for use only inside assert() statements. On some platforms,
19019 ** there might be race conditions that can cause these routines to
19020 ** deliver incorrect results. In particular, if pthread_equal() is
19021 ** not an atomic operation, then these routines might delivery
19022 ** incorrect results. On most platforms, pthread_equal() is a
19023 ** comparison of two integers and is therefore atomic. But we are
19024 ** told that HPUX is not such a platform. If so, then these routines
19025 ** will not always work correctly on HPUX.
19027 ** On those platforms where pthread_equal() is not atomic, SQLite
19028 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
19029 ** make sure no assert() statements are evaluated and hence these
19030 ** routines are never called.
19032 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
19033 static int pthreadMutexHeld(sqlite3_mutex *p){
19034 return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
19036 static int pthreadMutexNotheld(sqlite3_mutex *p){
19037 return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
19039 #endif
19042 ** Initialize and deinitialize the mutex subsystem.
19044 static int pthreadMutexInit(void){ return SQLITE_OK; }
19045 static int pthreadMutexEnd(void){ return SQLITE_OK; }
19048 ** The sqlite3_mutex_alloc() routine allocates a new
19049 ** mutex and returns a pointer to it. If it returns NULL
19050 ** that means that a mutex could not be allocated. SQLite
19051 ** will unwind its stack and return an error. The argument
19052 ** to sqlite3_mutex_alloc() is one of these integer constants:
19054 ** <ul>
19055 ** <li> SQLITE_MUTEX_FAST
19056 ** <li> SQLITE_MUTEX_RECURSIVE
19057 ** <li> SQLITE_MUTEX_STATIC_MASTER
19058 ** <li> SQLITE_MUTEX_STATIC_MEM
19059 ** <li> SQLITE_MUTEX_STATIC_OPEN
19060 ** <li> SQLITE_MUTEX_STATIC_PRNG
19061 ** <li> SQLITE_MUTEX_STATIC_LRU
19062 ** <li> SQLITE_MUTEX_STATIC_PMEM
19063 ** <li> SQLITE_MUTEX_STATIC_APP1
19064 ** <li> SQLITE_MUTEX_STATIC_APP2
19065 ** <li> SQLITE_MUTEX_STATIC_APP3
19066 ** </ul>
19068 ** The first two constants cause sqlite3_mutex_alloc() to create
19069 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
19070 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
19071 ** The mutex implementation does not need to make a distinction
19072 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
19073 ** not want to. But SQLite will only request a recursive mutex in
19074 ** cases where it really needs one. If a faster non-recursive mutex
19075 ** implementation is available on the host platform, the mutex subsystem
19076 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
19078 ** The other allowed parameters to sqlite3_mutex_alloc() each return
19079 ** a pointer to a static preexisting mutex. Six static mutexes are
19080 ** used by the current version of SQLite. Future versions of SQLite
19081 ** may add additional static mutexes. Static mutexes are for internal
19082 ** use by SQLite only. Applications that use SQLite mutexes should
19083 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
19084 ** SQLITE_MUTEX_RECURSIVE.
19086 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
19087 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
19088 ** returns a different mutex on every call. But for the static
19089 ** mutex types, the same mutex is returned on every call that has
19090 ** the same type number.
19092 static sqlite3_mutex *pthreadMutexAlloc(int iType){
19093 static sqlite3_mutex staticMutexes[] = {
19094 SQLITE3_MUTEX_INITIALIZER,
19095 SQLITE3_MUTEX_INITIALIZER,
19096 SQLITE3_MUTEX_INITIALIZER,
19097 SQLITE3_MUTEX_INITIALIZER,
19098 SQLITE3_MUTEX_INITIALIZER,
19099 SQLITE3_MUTEX_INITIALIZER,
19100 SQLITE3_MUTEX_INITIALIZER,
19101 SQLITE3_MUTEX_INITIALIZER,
19102 SQLITE3_MUTEX_INITIALIZER
19104 sqlite3_mutex *p;
19105 switch( iType ){
19106 case SQLITE_MUTEX_RECURSIVE: {
19107 p = sqlite3MallocZero( sizeof(*p) );
19108 if( p ){
19109 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19110 /* If recursive mutexes are not available, we will have to
19111 ** build our own. See below. */
19112 pthread_mutex_init(&p->mutex, 0);
19113 #else
19114 /* Use a recursive mutex if it is available */
19115 pthread_mutexattr_t recursiveAttr;
19116 pthread_mutexattr_init(&recursiveAttr);
19117 pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
19118 pthread_mutex_init(&p->mutex, &recursiveAttr);
19119 pthread_mutexattr_destroy(&recursiveAttr);
19120 #endif
19121 #if SQLITE_MUTEX_NREF
19122 p->id = iType;
19123 #endif
19125 break;
19127 case SQLITE_MUTEX_FAST: {
19128 p = sqlite3MallocZero( sizeof(*p) );
19129 if( p ){
19130 #if SQLITE_MUTEX_NREF
19131 p->id = iType;
19132 #endif
19133 pthread_mutex_init(&p->mutex, 0);
19135 break;
19137 default: {
19138 assert( iType-2 >= 0 );
19139 assert( iType-2 < ArraySize(staticMutexes) );
19140 p = &staticMutexes[iType-2];
19141 #if SQLITE_MUTEX_NREF
19142 p->id = iType;
19143 #endif
19144 break;
19147 return p;
19152 ** This routine deallocates a previously
19153 ** allocated mutex. SQLite is careful to deallocate every
19154 ** mutex that it allocates.
19156 static void pthreadMutexFree(sqlite3_mutex *p){
19157 assert( p->nRef==0 );
19158 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
19159 pthread_mutex_destroy(&p->mutex);
19160 sqlite3_free(p);
19164 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
19165 ** to enter a mutex. If another thread is already within the mutex,
19166 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
19167 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
19168 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
19169 ** be entered multiple times by the same thread. In such cases the,
19170 ** mutex must be exited an equal number of times before another thread
19171 ** can enter. If the same thread tries to enter any other kind of mutex
19172 ** more than once, the behavior is undefined.
19174 static void pthreadMutexEnter(sqlite3_mutex *p){
19175 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
19177 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19178 /* If recursive mutexes are not available, then we have to grow
19179 ** our own. This implementation assumes that pthread_equal()
19180 ** is atomic - that it cannot be deceived into thinking self
19181 ** and p->owner are equal if p->owner changes between two values
19182 ** that are not equal to self while the comparison is taking place.
19183 ** This implementation also assumes a coherent cache - that
19184 ** separate processes cannot read different values from the same
19185 ** address at the same time. If either of these two conditions
19186 ** are not met, then the mutexes will fail and problems will result.
19189 pthread_t self = pthread_self();
19190 if( p->nRef>0 && pthread_equal(p->owner, self) ){
19191 p->nRef++;
19192 }else{
19193 pthread_mutex_lock(&p->mutex);
19194 assert( p->nRef==0 );
19195 p->owner = self;
19196 p->nRef = 1;
19199 #else
19200 /* Use the built-in recursive mutexes if they are available.
19202 pthread_mutex_lock(&p->mutex);
19203 #if SQLITE_MUTEX_NREF
19204 assert( p->nRef>0 || p->owner==0 );
19205 p->owner = pthread_self();
19206 p->nRef++;
19207 #endif
19208 #endif
19210 #ifdef SQLITE_DEBUG
19211 if( p->trace ){
19212 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19214 #endif
19216 static int pthreadMutexTry(sqlite3_mutex *p){
19217 int rc;
19218 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
19220 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19221 /* If recursive mutexes are not available, then we have to grow
19222 ** our own. This implementation assumes that pthread_equal()
19223 ** is atomic - that it cannot be deceived into thinking self
19224 ** and p->owner are equal if p->owner changes between two values
19225 ** that are not equal to self while the comparison is taking place.
19226 ** This implementation also assumes a coherent cache - that
19227 ** separate processes cannot read different values from the same
19228 ** address at the same time. If either of these two conditions
19229 ** are not met, then the mutexes will fail and problems will result.
19232 pthread_t self = pthread_self();
19233 if( p->nRef>0 && pthread_equal(p->owner, self) ){
19234 p->nRef++;
19235 rc = SQLITE_OK;
19236 }else if( pthread_mutex_trylock(&p->mutex)==0 ){
19237 assert( p->nRef==0 );
19238 p->owner = self;
19239 p->nRef = 1;
19240 rc = SQLITE_OK;
19241 }else{
19242 rc = SQLITE_BUSY;
19245 #else
19246 /* Use the built-in recursive mutexes if they are available.
19248 if( pthread_mutex_trylock(&p->mutex)==0 ){
19249 #if SQLITE_MUTEX_NREF
19250 p->owner = pthread_self();
19251 p->nRef++;
19252 #endif
19253 rc = SQLITE_OK;
19254 }else{
19255 rc = SQLITE_BUSY;
19257 #endif
19259 #ifdef SQLITE_DEBUG
19260 if( rc==SQLITE_OK && p->trace ){
19261 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19263 #endif
19264 return rc;
19268 ** The sqlite3_mutex_leave() routine exits a mutex that was
19269 ** previously entered by the same thread. The behavior
19270 ** is undefined if the mutex is not currently entered or
19271 ** is not currently allocated. SQLite will never do either.
19273 static void pthreadMutexLeave(sqlite3_mutex *p){
19274 assert( pthreadMutexHeld(p) );
19275 #if SQLITE_MUTEX_NREF
19276 p->nRef--;
19277 if( p->nRef==0 ) p->owner = 0;
19278 #endif
19279 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
19281 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19282 if( p->nRef==0 ){
19283 pthread_mutex_unlock(&p->mutex);
19285 #else
19286 pthread_mutex_unlock(&p->mutex);
19287 #endif
19289 #ifdef SQLITE_DEBUG
19290 if( p->trace ){
19291 printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19293 #endif
19296 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
19297 static const sqlite3_mutex_methods sMutex = {
19298 pthreadMutexInit,
19299 pthreadMutexEnd,
19300 pthreadMutexAlloc,
19301 pthreadMutexFree,
19302 pthreadMutexEnter,
19303 pthreadMutexTry,
19304 pthreadMutexLeave,
19305 #ifdef SQLITE_DEBUG
19306 pthreadMutexHeld,
19307 pthreadMutexNotheld
19308 #else
19311 #endif
19314 return &sMutex;
19317 #endif /* SQLITE_MUTEX_PTHREADS */
19319 /************** End of mutex_unix.c ******************************************/
19320 /************** Begin file mutex_w32.c ***************************************/
19322 ** 2007 August 14
19324 ** The author disclaims copyright to this source code. In place of
19325 ** a legal notice, here is a blessing:
19327 ** May you do good and not evil.
19328 ** May you find forgiveness for yourself and forgive others.
19329 ** May you share freely, never taking more than you give.
19331 *************************************************************************
19332 ** This file contains the C functions that implement mutexes for Win32.
19335 #if SQLITE_OS_WIN
19337 ** Include code that is common to all os_*.c files
19339 /************** Include os_common.h in the middle of mutex_w32.c *************/
19340 /************** Begin file os_common.h ***************************************/
19342 ** 2004 May 22
19344 ** The author disclaims copyright to this source code. In place of
19345 ** a legal notice, here is a blessing:
19347 ** May you do good and not evil.
19348 ** May you find forgiveness for yourself and forgive others.
19349 ** May you share freely, never taking more than you give.
19351 ******************************************************************************
19353 ** This file contains macros and a little bit of code that is common to
19354 ** all of the platform-specific files (os_*.c) and is #included into those
19355 ** files.
19357 ** This file should be #included by the os_*.c files only. It is not a
19358 ** general purpose header file.
19360 #ifndef _OS_COMMON_H_
19361 #define _OS_COMMON_H_
19364 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
19365 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
19366 ** switch. The following code should catch this problem at compile-time.
19368 #ifdef MEMORY_DEBUG
19369 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
19370 #endif
19372 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
19373 # ifndef SQLITE_DEBUG_OS_TRACE
19374 # define SQLITE_DEBUG_OS_TRACE 0
19375 # endif
19376 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
19377 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
19378 #else
19379 # define OSTRACE(X)
19380 #endif
19383 ** Macros for performance tracing. Normally turned off. Only works
19384 ** on i486 hardware.
19386 #ifdef SQLITE_PERFORMANCE_TRACE
19389 ** hwtime.h contains inline assembler code for implementing
19390 ** high-performance timing routines.
19392 /************** Include hwtime.h in the middle of os_common.h ****************/
19393 /************** Begin file hwtime.h ******************************************/
19395 ** 2008 May 27
19397 ** The author disclaims copyright to this source code. In place of
19398 ** a legal notice, here is a blessing:
19400 ** May you do good and not evil.
19401 ** May you find forgiveness for yourself and forgive others.
19402 ** May you share freely, never taking more than you give.
19404 ******************************************************************************
19406 ** This file contains inline asm code for retrieving "high-performance"
19407 ** counters for x86 class CPUs.
19409 #ifndef _HWTIME_H_
19410 #define _HWTIME_H_
19413 ** The following routine only works on pentium-class (or newer) processors.
19414 ** It uses the RDTSC opcode to read the cycle count value out of the
19415 ** processor and returns that value. This can be used for high-res
19416 ** profiling.
19418 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
19419 (defined(i386) || defined(__i386__) || defined(_M_IX86))
19421 #if defined(__GNUC__)
19423 __inline__ sqlite_uint64 sqlite3Hwtime(void){
19424 unsigned int lo, hi;
19425 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
19426 return (sqlite_uint64)hi << 32 | lo;
19429 #elif defined(_MSC_VER)
19431 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
19432 __asm {
19433 rdtsc
19434 ret ; return value at EDX:EAX
19438 #endif
19440 #elif (defined(__GNUC__) && defined(__x86_64__))
19442 __inline__ sqlite_uint64 sqlite3Hwtime(void){
19443 unsigned long val;
19444 __asm__ __volatile__ ("rdtsc" : "=A" (val));
19445 return val;
19448 #elif (defined(__GNUC__) && defined(__ppc__))
19450 __inline__ sqlite_uint64 sqlite3Hwtime(void){
19451 unsigned long long retval;
19452 unsigned long junk;
19453 __asm__ __volatile__ ("\n\
19454 1: mftbu %1\n\
19455 mftb %L0\n\
19456 mftbu %0\n\
19457 cmpw %0,%1\n\
19458 bne 1b"
19459 : "=r" (retval), "=r" (junk));
19460 return retval;
19463 #else
19465 #error Need implementation of sqlite3Hwtime() for your platform.
19468 ** To compile without implementing sqlite3Hwtime() for your platform,
19469 ** you can remove the above #error and use the following
19470 ** stub function. You will lose timing support for many
19471 ** of the debugging and testing utilities, but it should at
19472 ** least compile and run.
19474 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
19476 #endif
19478 #endif /* !defined(_HWTIME_H_) */
19480 /************** End of hwtime.h **********************************************/
19481 /************** Continuing where we left off in os_common.h ******************/
19483 static sqlite_uint64 g_start;
19484 static sqlite_uint64 g_elapsed;
19485 #define TIMER_START g_start=sqlite3Hwtime()
19486 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
19487 #define TIMER_ELAPSED g_elapsed
19488 #else
19489 #define TIMER_START
19490 #define TIMER_END
19491 #define TIMER_ELAPSED ((sqlite_uint64)0)
19492 #endif
19495 ** If we compile with the SQLITE_TEST macro set, then the following block
19496 ** of code will give us the ability to simulate a disk I/O error. This
19497 ** is used for testing the I/O recovery logic.
19499 #ifdef SQLITE_TEST
19500 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
19501 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
19502 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
19503 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
19504 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
19505 SQLITE_API int sqlite3_diskfull_pending = 0;
19506 SQLITE_API int sqlite3_diskfull = 0;
19507 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
19508 #define SimulateIOError(CODE) \
19509 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
19510 || sqlite3_io_error_pending-- == 1 ) \
19511 { local_ioerr(); CODE; }
19512 static void local_ioerr(){
19513 IOTRACE(("IOERR\n"));
19514 sqlite3_io_error_hit++;
19515 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
19517 #define SimulateDiskfullError(CODE) \
19518 if( sqlite3_diskfull_pending ){ \
19519 if( sqlite3_diskfull_pending == 1 ){ \
19520 local_ioerr(); \
19521 sqlite3_diskfull = 1; \
19522 sqlite3_io_error_hit = 1; \
19523 CODE; \
19524 }else{ \
19525 sqlite3_diskfull_pending--; \
19528 #else
19529 #define SimulateIOErrorBenign(X)
19530 #define SimulateIOError(A)
19531 #define SimulateDiskfullError(A)
19532 #endif
19535 ** When testing, keep a count of the number of open files.
19537 #ifdef SQLITE_TEST
19538 SQLITE_API int sqlite3_open_file_count = 0;
19539 #define OpenCounter(X) sqlite3_open_file_count+=(X)
19540 #else
19541 #define OpenCounter(X)
19542 #endif
19544 #endif /* !defined(_OS_COMMON_H_) */
19546 /************** End of os_common.h *******************************************/
19547 /************** Continuing where we left off in mutex_w32.c ******************/
19550 ** Include the header file for the Windows VFS.
19552 /************** Include os_win.h in the middle of mutex_w32.c ****************/
19553 /************** Begin file os_win.h ******************************************/
19555 ** 2013 November 25
19557 ** The author disclaims copyright to this source code. In place of
19558 ** a legal notice, here is a blessing:
19560 ** May you do good and not evil.
19561 ** May you find forgiveness for yourself and forgive others.
19562 ** May you share freely, never taking more than you give.
19564 ******************************************************************************
19566 ** This file contains code that is specific to Windows.
19568 #ifndef _OS_WIN_H_
19569 #define _OS_WIN_H_
19572 ** Include the primary Windows SDK header file.
19574 #include "windows.h"
19576 #ifdef __CYGWIN__
19577 # include <sys/cygwin.h>
19578 # include <errno.h> /* amalgamator: dontcache */
19579 #endif
19582 ** Determine if we are dealing with Windows NT.
19584 ** We ought to be able to determine if we are compiling for Windows 9x or
19585 ** Windows NT using the _WIN32_WINNT macro as follows:
19587 ** #if defined(_WIN32_WINNT)
19588 ** # define SQLITE_OS_WINNT 1
19589 ** #else
19590 ** # define SQLITE_OS_WINNT 0
19591 ** #endif
19593 ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
19594 ** it ought to, so the above test does not work. We'll just assume that
19595 ** everything is Windows NT unless the programmer explicitly says otherwise
19596 ** by setting SQLITE_OS_WINNT to 0.
19598 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
19599 # define SQLITE_OS_WINNT 1
19600 #endif
19603 ** Determine if we are dealing with Windows CE - which has a much reduced
19604 ** API.
19606 #if defined(_WIN32_WCE)
19607 # define SQLITE_OS_WINCE 1
19608 #else
19609 # define SQLITE_OS_WINCE 0
19610 #endif
19613 ** Determine if we are dealing with WinRT, which provides only a subset of
19614 ** the full Win32 API.
19616 #if !defined(SQLITE_OS_WINRT)
19617 # define SQLITE_OS_WINRT 0
19618 #endif
19621 ** For WinCE, some API function parameters do not appear to be declared as
19622 ** volatile.
19624 #if SQLITE_OS_WINCE
19625 # define SQLITE_WIN32_VOLATILE
19626 #else
19627 # define SQLITE_WIN32_VOLATILE volatile
19628 #endif
19630 #endif /* _OS_WIN_H_ */
19632 /************** End of os_win.h **********************************************/
19633 /************** Continuing where we left off in mutex_w32.c ******************/
19634 #endif
19637 ** The code in this file is only used if we are compiling multithreaded
19638 ** on a Win32 system.
19640 #ifdef SQLITE_MUTEX_W32
19643 ** Each recursive mutex is an instance of the following structure.
19645 struct sqlite3_mutex {
19646 CRITICAL_SECTION mutex; /* Mutex controlling the lock */
19647 int id; /* Mutex type */
19648 #ifdef SQLITE_DEBUG
19649 volatile int nRef; /* Number of enterances */
19650 volatile DWORD owner; /* Thread holding this mutex */
19651 volatile int trace; /* True to trace changes */
19652 #endif
19656 ** These are the initializer values used when declaring a "static" mutex
19657 ** on Win32. It should be noted that all mutexes require initialization
19658 ** on the Win32 platform.
19660 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
19662 #ifdef SQLITE_DEBUG
19663 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
19664 0L, (DWORD)0, 0 }
19665 #else
19666 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
19667 #endif
19669 #ifdef SQLITE_DEBUG
19671 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
19672 ** intended for use only inside assert() statements.
19674 static int winMutexHeld(sqlite3_mutex *p){
19675 return p->nRef!=0 && p->owner==GetCurrentThreadId();
19678 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
19679 return p->nRef==0 || p->owner!=tid;
19682 static int winMutexNotheld(sqlite3_mutex *p){
19683 DWORD tid = GetCurrentThreadId();
19684 return winMutexNotheld2(p, tid);
19686 #endif
19689 ** Initialize and deinitialize the mutex subsystem.
19691 static sqlite3_mutex winMutex_staticMutexes[] = {
19692 SQLITE3_MUTEX_INITIALIZER,
19693 SQLITE3_MUTEX_INITIALIZER,
19694 SQLITE3_MUTEX_INITIALIZER,
19695 SQLITE3_MUTEX_INITIALIZER,
19696 SQLITE3_MUTEX_INITIALIZER,
19697 SQLITE3_MUTEX_INITIALIZER,
19698 SQLITE3_MUTEX_INITIALIZER,
19699 SQLITE3_MUTEX_INITIALIZER,
19700 SQLITE3_MUTEX_INITIALIZER
19703 static int winMutex_isInit = 0;
19704 static int winMutex_isNt = -1; /* <0 means "need to query" */
19706 /* As the winMutexInit() and winMutexEnd() functions are called as part
19707 ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
19708 ** "interlocked" magic used here is probably not strictly necessary.
19710 static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
19712 SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
19713 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
19715 static int winMutexInit(void){
19716 /* The first to increment to 1 does actual initialization */
19717 if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
19718 int i;
19719 for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
19720 #if SQLITE_OS_WINRT
19721 InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
19722 #else
19723 InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
19724 #endif
19726 winMutex_isInit = 1;
19727 }else{
19728 /* Another thread is (in the process of) initializing the static
19729 ** mutexes */
19730 while( !winMutex_isInit ){
19731 sqlite3_win32_sleep(1);
19734 return SQLITE_OK;
19737 static int winMutexEnd(void){
19738 /* The first to decrement to 0 does actual shutdown
19739 ** (which should be the last to shutdown.) */
19740 if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
19741 if( winMutex_isInit==1 ){
19742 int i;
19743 for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
19744 DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
19746 winMutex_isInit = 0;
19749 return SQLITE_OK;
19753 ** The sqlite3_mutex_alloc() routine allocates a new
19754 ** mutex and returns a pointer to it. If it returns NULL
19755 ** that means that a mutex could not be allocated. SQLite
19756 ** will unwind its stack and return an error. The argument
19757 ** to sqlite3_mutex_alloc() is one of these integer constants:
19759 ** <ul>
19760 ** <li> SQLITE_MUTEX_FAST
19761 ** <li> SQLITE_MUTEX_RECURSIVE
19762 ** <li> SQLITE_MUTEX_STATIC_MASTER
19763 ** <li> SQLITE_MUTEX_STATIC_MEM
19764 ** <li> SQLITE_MUTEX_STATIC_OPEN
19765 ** <li> SQLITE_MUTEX_STATIC_PRNG
19766 ** <li> SQLITE_MUTEX_STATIC_LRU
19767 ** <li> SQLITE_MUTEX_STATIC_PMEM
19768 ** <li> SQLITE_MUTEX_STATIC_APP1
19769 ** <li> SQLITE_MUTEX_STATIC_APP2
19770 ** <li> SQLITE_MUTEX_STATIC_APP3
19771 ** </ul>
19773 ** The first two constants cause sqlite3_mutex_alloc() to create
19774 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
19775 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
19776 ** The mutex implementation does not need to make a distinction
19777 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
19778 ** not want to. But SQLite will only request a recursive mutex in
19779 ** cases where it really needs one. If a faster non-recursive mutex
19780 ** implementation is available on the host platform, the mutex subsystem
19781 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
19783 ** The other allowed parameters to sqlite3_mutex_alloc() each return
19784 ** a pointer to a static preexisting mutex. Six static mutexes are
19785 ** used by the current version of SQLite. Future versions of SQLite
19786 ** may add additional static mutexes. Static mutexes are for internal
19787 ** use by SQLite only. Applications that use SQLite mutexes should
19788 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
19789 ** SQLITE_MUTEX_RECURSIVE.
19791 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
19792 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
19793 ** returns a different mutex on every call. But for the static
19794 ** mutex types, the same mutex is returned on every call that has
19795 ** the same type number.
19797 static sqlite3_mutex *winMutexAlloc(int iType){
19798 sqlite3_mutex *p;
19800 switch( iType ){
19801 case SQLITE_MUTEX_FAST:
19802 case SQLITE_MUTEX_RECURSIVE: {
19803 p = sqlite3MallocZero( sizeof(*p) );
19804 if( p ){
19805 #ifdef SQLITE_DEBUG
19806 p->id = iType;
19807 #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
19808 p->trace = 1;
19809 #endif
19810 #endif
19811 #if SQLITE_OS_WINRT
19812 InitializeCriticalSectionEx(&p->mutex, 0, 0);
19813 #else
19814 InitializeCriticalSection(&p->mutex);
19815 #endif
19817 break;
19819 default: {
19820 assert( iType-2 >= 0 );
19821 assert( iType-2 < ArraySize(winMutex_staticMutexes) );
19822 assert( winMutex_isInit==1 );
19823 p = &winMutex_staticMutexes[iType-2];
19824 #ifdef SQLITE_DEBUG
19825 p->id = iType;
19826 #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
19827 p->trace = 1;
19828 #endif
19829 #endif
19830 break;
19833 return p;
19838 ** This routine deallocates a previously
19839 ** allocated mutex. SQLite is careful to deallocate every
19840 ** mutex that it allocates.
19842 static void winMutexFree(sqlite3_mutex *p){
19843 assert( p );
19844 #ifdef SQLITE_DEBUG
19845 assert( p->nRef==0 && p->owner==0 );
19846 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
19847 #endif
19848 assert( winMutex_isInit==1 );
19849 DeleteCriticalSection(&p->mutex);
19850 sqlite3_free(p);
19854 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
19855 ** to enter a mutex. If another thread is already within the mutex,
19856 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
19857 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
19858 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
19859 ** be entered multiple times by the same thread. In such cases the,
19860 ** mutex must be exited an equal number of times before another thread
19861 ** can enter. If the same thread tries to enter any other kind of mutex
19862 ** more than once, the behavior is undefined.
19864 static void winMutexEnter(sqlite3_mutex *p){
19865 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
19866 DWORD tid = GetCurrentThreadId();
19867 #endif
19868 #ifdef SQLITE_DEBUG
19869 assert( p );
19870 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
19871 #else
19872 assert( p );
19873 #endif
19874 assert( winMutex_isInit==1 );
19875 EnterCriticalSection(&p->mutex);
19876 #ifdef SQLITE_DEBUG
19877 assert( p->nRef>0 || p->owner==0 );
19878 p->owner = tid;
19879 p->nRef++;
19880 if( p->trace ){
19881 OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
19882 tid, p, p->trace, p->nRef));
19884 #endif
19887 static int winMutexTry(sqlite3_mutex *p){
19888 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
19889 DWORD tid = GetCurrentThreadId();
19890 #endif
19891 int rc = SQLITE_BUSY;
19892 assert( p );
19893 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
19895 ** The sqlite3_mutex_try() routine is very rarely used, and when it
19896 ** is used it is merely an optimization. So it is OK for it to always
19897 ** fail.
19899 ** The TryEnterCriticalSection() interface is only available on WinNT.
19900 ** And some windows compilers complain if you try to use it without
19901 ** first doing some #defines that prevent SQLite from building on Win98.
19902 ** For that reason, we will omit this optimization for now. See
19903 ** ticket #2685.
19905 #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
19906 assert( winMutex_isInit==1 );
19907 assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
19908 if( winMutex_isNt<0 ){
19909 winMutex_isNt = sqlite3_win32_is_nt();
19911 assert( winMutex_isNt==0 || winMutex_isNt==1 );
19912 if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
19913 #ifdef SQLITE_DEBUG
19914 p->owner = tid;
19915 p->nRef++;
19916 #endif
19917 rc = SQLITE_OK;
19919 #else
19920 UNUSED_PARAMETER(p);
19921 #endif
19922 #ifdef SQLITE_DEBUG
19923 if( p->trace ){
19924 OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
19925 tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
19927 #endif
19928 return rc;
19932 ** The sqlite3_mutex_leave() routine exits a mutex that was
19933 ** previously entered by the same thread. The behavior
19934 ** is undefined if the mutex is not currently entered or
19935 ** is not currently allocated. SQLite will never do either.
19937 static void winMutexLeave(sqlite3_mutex *p){
19938 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
19939 DWORD tid = GetCurrentThreadId();
19940 #endif
19941 assert( p );
19942 #ifdef SQLITE_DEBUG
19943 assert( p->nRef>0 );
19944 assert( p->owner==tid );
19945 p->nRef--;
19946 if( p->nRef==0 ) p->owner = 0;
19947 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
19948 #endif
19949 assert( winMutex_isInit==1 );
19950 LeaveCriticalSection(&p->mutex);
19951 #ifdef SQLITE_DEBUG
19952 if( p->trace ){
19953 OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
19954 tid, p, p->trace, p->nRef));
19956 #endif
19959 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
19960 static const sqlite3_mutex_methods sMutex = {
19961 winMutexInit,
19962 winMutexEnd,
19963 winMutexAlloc,
19964 winMutexFree,
19965 winMutexEnter,
19966 winMutexTry,
19967 winMutexLeave,
19968 #ifdef SQLITE_DEBUG
19969 winMutexHeld,
19970 winMutexNotheld
19971 #else
19974 #endif
19976 return &sMutex;
19979 #endif /* SQLITE_MUTEX_W32 */
19981 /************** End of mutex_w32.c *******************************************/
19982 /************** Begin file malloc.c ******************************************/
19984 ** 2001 September 15
19986 ** The author disclaims copyright to this source code. In place of
19987 ** a legal notice, here is a blessing:
19989 ** May you do good and not evil.
19990 ** May you find forgiveness for yourself and forgive others.
19991 ** May you share freely, never taking more than you give.
19993 *************************************************************************
19995 ** Memory allocation functions used throughout sqlite.
19997 /* #include <stdarg.h> */
20000 ** Attempt to release up to n bytes of non-essential memory currently
20001 ** held by SQLite. An example of non-essential memory is memory used to
20002 ** cache database pages that are not currently in use.
20004 SQLITE_API int sqlite3_release_memory(int n){
20005 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20006 return sqlite3PcacheReleaseMemory(n);
20007 #else
20008 /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
20009 ** is a no-op returning zero if SQLite is not compiled with
20010 ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
20011 UNUSED_PARAMETER(n);
20012 return 0;
20013 #endif
20017 ** An instance of the following object records the location of
20018 ** each unused scratch buffer.
20020 typedef struct ScratchFreeslot {
20021 struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
20022 } ScratchFreeslot;
20025 ** State information local to the memory allocation subsystem.
20027 static SQLITE_WSD struct Mem0Global {
20028 sqlite3_mutex *mutex; /* Mutex to serialize access */
20031 ** The alarm callback and its arguments. The mem0.mutex lock will
20032 ** be held while the callback is running. Recursive calls into
20033 ** the memory subsystem are allowed, but no new callbacks will be
20034 ** issued.
20036 sqlite3_int64 alarmThreshold;
20037 void (*alarmCallback)(void*, sqlite3_int64,int);
20038 void *alarmArg;
20041 ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
20042 ** (so that a range test can be used to determine if an allocation
20043 ** being freed came from pScratch) and a pointer to the list of
20044 ** unused scratch allocations.
20046 void *pScratchEnd;
20047 ScratchFreeslot *pScratchFree;
20048 u32 nScratchFree;
20051 ** True if heap is nearly "full" where "full" is defined by the
20052 ** sqlite3_soft_heap_limit() setting.
20054 int nearlyFull;
20055 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
20057 #define mem0 GLOBAL(struct Mem0Global, mem0)
20060 ** This routine runs when the memory allocator sees that the
20061 ** total memory allocation is about to exceed the soft heap
20062 ** limit.
20064 static void softHeapLimitEnforcer(
20065 void *NotUsed,
20066 sqlite3_int64 NotUsed2,
20067 int allocSize
20069 UNUSED_PARAMETER2(NotUsed, NotUsed2);
20070 sqlite3_release_memory(allocSize);
20074 ** Change the alarm callback
20076 static int sqlite3MemoryAlarm(
20077 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
20078 void *pArg,
20079 sqlite3_int64 iThreshold
20081 int nUsed;
20082 sqlite3_mutex_enter(mem0.mutex);
20083 mem0.alarmCallback = xCallback;
20084 mem0.alarmArg = pArg;
20085 mem0.alarmThreshold = iThreshold;
20086 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
20087 mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
20088 sqlite3_mutex_leave(mem0.mutex);
20089 return SQLITE_OK;
20092 #ifndef SQLITE_OMIT_DEPRECATED
20094 ** Deprecated external interface. Internal/core SQLite code
20095 ** should call sqlite3MemoryAlarm.
20097 SQLITE_API int sqlite3_memory_alarm(
20098 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
20099 void *pArg,
20100 sqlite3_int64 iThreshold
20102 return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
20104 #endif
20107 ** Set the soft heap-size limit for the library. Passing a zero or
20108 ** negative value indicates no limit.
20110 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
20111 sqlite3_int64 priorLimit;
20112 sqlite3_int64 excess;
20113 #ifndef SQLITE_OMIT_AUTOINIT
20114 int rc = sqlite3_initialize();
20115 if( rc ) return -1;
20116 #endif
20117 sqlite3_mutex_enter(mem0.mutex);
20118 priorLimit = mem0.alarmThreshold;
20119 sqlite3_mutex_leave(mem0.mutex);
20120 if( n<0 ) return priorLimit;
20121 if( n>0 ){
20122 sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
20123 }else{
20124 sqlite3MemoryAlarm(0, 0, 0);
20126 excess = sqlite3_memory_used() - n;
20127 if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
20128 return priorLimit;
20130 SQLITE_API void sqlite3_soft_heap_limit(int n){
20131 if( n<0 ) n = 0;
20132 sqlite3_soft_heap_limit64(n);
20136 ** Initialize the memory allocation subsystem.
20138 SQLITE_PRIVATE int sqlite3MallocInit(void){
20139 if( sqlite3GlobalConfig.m.xMalloc==0 ){
20140 sqlite3MemSetDefault();
20142 memset(&mem0, 0, sizeof(mem0));
20143 if( sqlite3GlobalConfig.bCoreMutex ){
20144 mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
20146 if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
20147 && sqlite3GlobalConfig.nScratch>0 ){
20148 int i, n, sz;
20149 ScratchFreeslot *pSlot;
20150 sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
20151 sqlite3GlobalConfig.szScratch = sz;
20152 pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
20153 n = sqlite3GlobalConfig.nScratch;
20154 mem0.pScratchFree = pSlot;
20155 mem0.nScratchFree = n;
20156 for(i=0; i<n-1; i++){
20157 pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
20158 pSlot = pSlot->pNext;
20160 pSlot->pNext = 0;
20161 mem0.pScratchEnd = (void*)&pSlot[1];
20162 }else{
20163 mem0.pScratchEnd = 0;
20164 sqlite3GlobalConfig.pScratch = 0;
20165 sqlite3GlobalConfig.szScratch = 0;
20166 sqlite3GlobalConfig.nScratch = 0;
20168 if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
20169 || sqlite3GlobalConfig.nPage<1 ){
20170 sqlite3GlobalConfig.pPage = 0;
20171 sqlite3GlobalConfig.szPage = 0;
20172 sqlite3GlobalConfig.nPage = 0;
20174 return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
20178 ** Return true if the heap is currently under memory pressure - in other
20179 ** words if the amount of heap used is close to the limit set by
20180 ** sqlite3_soft_heap_limit().
20182 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
20183 return mem0.nearlyFull;
20187 ** Deinitialize the memory allocation subsystem.
20189 SQLITE_PRIVATE void sqlite3MallocEnd(void){
20190 if( sqlite3GlobalConfig.m.xShutdown ){
20191 sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
20193 memset(&mem0, 0, sizeof(mem0));
20197 ** Return the amount of memory currently checked out.
20199 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
20200 int n, mx;
20201 sqlite3_int64 res;
20202 sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
20203 res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
20204 return res;
20208 ** Return the maximum amount of memory that has ever been
20209 ** checked out since either the beginning of this process
20210 ** or since the most recent reset.
20212 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
20213 int n, mx;
20214 sqlite3_int64 res;
20215 sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
20216 res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
20217 return res;
20221 ** Trigger the alarm
20223 static void sqlite3MallocAlarm(int nByte){
20224 void (*xCallback)(void*,sqlite3_int64,int);
20225 sqlite3_int64 nowUsed;
20226 void *pArg;
20227 if( mem0.alarmCallback==0 ) return;
20228 xCallback = mem0.alarmCallback;
20229 nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
20230 pArg = mem0.alarmArg;
20231 mem0.alarmCallback = 0;
20232 sqlite3_mutex_leave(mem0.mutex);
20233 xCallback(pArg, nowUsed, nByte);
20234 sqlite3_mutex_enter(mem0.mutex);
20235 mem0.alarmCallback = xCallback;
20236 mem0.alarmArg = pArg;
20240 ** Do a memory allocation with statistics and alarms. Assume the
20241 ** lock is already held.
20243 static int mallocWithAlarm(int n, void **pp){
20244 int nFull;
20245 void *p;
20246 assert( sqlite3_mutex_held(mem0.mutex) );
20247 nFull = sqlite3GlobalConfig.m.xRoundup(n);
20248 sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
20249 if( mem0.alarmCallback!=0 ){
20250 int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
20251 if( nUsed >= mem0.alarmThreshold - nFull ){
20252 mem0.nearlyFull = 1;
20253 sqlite3MallocAlarm(nFull);
20254 }else{
20255 mem0.nearlyFull = 0;
20258 p = sqlite3GlobalConfig.m.xMalloc(nFull);
20259 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20260 if( p==0 && mem0.alarmCallback ){
20261 sqlite3MallocAlarm(nFull);
20262 p = sqlite3GlobalConfig.m.xMalloc(nFull);
20264 #endif
20265 if( p ){
20266 nFull = sqlite3MallocSize(p);
20267 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
20268 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
20270 *pp = p;
20271 return nFull;
20275 ** Allocate memory. This routine is like sqlite3_malloc() except that it
20276 ** assumes the memory subsystem has already been initialized.
20278 SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
20279 void *p;
20280 if( n==0 || n>=0x7fffff00 ){
20281 /* A memory allocation of a number of bytes which is near the maximum
20282 ** signed integer value might cause an integer overflow inside of the
20283 ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
20284 ** 255 bytes of overhead. SQLite itself will never use anything near
20285 ** this amount. The only way to reach the limit is with sqlite3_malloc() */
20286 p = 0;
20287 }else if( sqlite3GlobalConfig.bMemstat ){
20288 sqlite3_mutex_enter(mem0.mutex);
20289 mallocWithAlarm((int)n, &p);
20290 sqlite3_mutex_leave(mem0.mutex);
20291 }else{
20292 p = sqlite3GlobalConfig.m.xMalloc((int)n);
20294 assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
20295 return p;
20299 ** This version of the memory allocation is for use by the application.
20300 ** First make sure the memory subsystem is initialized, then do the
20301 ** allocation.
20303 SQLITE_API void *sqlite3_malloc(int n){
20304 #ifndef SQLITE_OMIT_AUTOINIT
20305 if( sqlite3_initialize() ) return 0;
20306 #endif
20307 return n<=0 ? 0 : sqlite3Malloc(n);
20309 SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
20310 #ifndef SQLITE_OMIT_AUTOINIT
20311 if( sqlite3_initialize() ) return 0;
20312 #endif
20313 return sqlite3Malloc(n);
20317 ** Each thread may only have a single outstanding allocation from
20318 ** xScratchMalloc(). We verify this constraint in the single-threaded
20319 ** case by setting scratchAllocOut to 1 when an allocation
20320 ** is outstanding clearing it when the allocation is freed.
20322 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
20323 static int scratchAllocOut = 0;
20324 #endif
20328 ** Allocate memory that is to be used and released right away.
20329 ** This routine is similar to alloca() in that it is not intended
20330 ** for situations where the memory might be held long-term. This
20331 ** routine is intended to get memory to old large transient data
20332 ** structures that would not normally fit on the stack of an
20333 ** embedded processor.
20335 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
20336 void *p;
20337 assert( n>0 );
20339 sqlite3_mutex_enter(mem0.mutex);
20340 sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
20341 if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
20342 p = mem0.pScratchFree;
20343 mem0.pScratchFree = mem0.pScratchFree->pNext;
20344 mem0.nScratchFree--;
20345 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
20346 sqlite3_mutex_leave(mem0.mutex);
20347 }else{
20348 sqlite3_mutex_leave(mem0.mutex);
20349 p = sqlite3Malloc(n);
20350 if( sqlite3GlobalConfig.bMemstat && p ){
20351 sqlite3_mutex_enter(mem0.mutex);
20352 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
20353 sqlite3_mutex_leave(mem0.mutex);
20355 sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
20357 assert( sqlite3_mutex_notheld(mem0.mutex) );
20360 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
20361 /* Verify that no more than two scratch allocations per thread
20362 ** are outstanding at one time. (This is only checked in the
20363 ** single-threaded case since checking in the multi-threaded case
20364 ** would be much more complicated.) */
20365 assert( scratchAllocOut<=1 );
20366 if( p ) scratchAllocOut++;
20367 #endif
20369 return p;
20371 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
20372 if( p ){
20374 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
20375 /* Verify that no more than two scratch allocation per thread
20376 ** is outstanding at one time. (This is only checked in the
20377 ** single-threaded case since checking in the multi-threaded case
20378 ** would be much more complicated.) */
20379 assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
20380 scratchAllocOut--;
20381 #endif
20383 if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
20384 /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
20385 ScratchFreeslot *pSlot;
20386 pSlot = (ScratchFreeslot*)p;
20387 sqlite3_mutex_enter(mem0.mutex);
20388 pSlot->pNext = mem0.pScratchFree;
20389 mem0.pScratchFree = pSlot;
20390 mem0.nScratchFree++;
20391 assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
20392 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
20393 sqlite3_mutex_leave(mem0.mutex);
20394 }else{
20395 /* Release memory back to the heap */
20396 assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
20397 assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
20398 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
20399 if( sqlite3GlobalConfig.bMemstat ){
20400 int iSize = sqlite3MallocSize(p);
20401 sqlite3_mutex_enter(mem0.mutex);
20402 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
20403 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
20404 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
20405 sqlite3GlobalConfig.m.xFree(p);
20406 sqlite3_mutex_leave(mem0.mutex);
20407 }else{
20408 sqlite3GlobalConfig.m.xFree(p);
20415 ** TRUE if p is a lookaside memory allocation from db
20417 #ifndef SQLITE_OMIT_LOOKASIDE
20418 static int isLookaside(sqlite3 *db, void *p){
20419 return p>=db->lookaside.pStart && p<db->lookaside.pEnd;
20421 #else
20422 #define isLookaside(A,B) 0
20423 #endif
20426 ** Return the size of a memory allocation previously obtained from
20427 ** sqlite3Malloc() or sqlite3_malloc().
20429 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
20430 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20431 return sqlite3GlobalConfig.m.xSize(p);
20433 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
20434 if( db==0 ){
20435 assert( sqlite3MemdebugNoType(p, ~MEMTYPE_HEAP) );
20436 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20437 return sqlite3MallocSize(p);
20438 }else{
20439 assert( sqlite3_mutex_held(db->mutex) );
20440 if( isLookaside(db, p) ){
20441 return db->lookaside.sz;
20442 }else{
20443 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20444 assert( sqlite3MemdebugNoType(p, ~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20445 return sqlite3GlobalConfig.m.xSize(p);
20449 SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
20450 assert( sqlite3MemdebugNoType(p, ~MEMTYPE_HEAP) );
20451 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20452 return (sqlite3_uint64)sqlite3GlobalConfig.m.xSize(p);
20456 ** Free memory previously obtained from sqlite3Malloc().
20458 SQLITE_API void sqlite3_free(void *p){
20459 if( p==0 ) return; /* IMP: R-49053-54554 */
20460 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20461 assert( sqlite3MemdebugNoType(p, ~MEMTYPE_HEAP) );
20462 if( sqlite3GlobalConfig.bMemstat ){
20463 sqlite3_mutex_enter(mem0.mutex);
20464 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
20465 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
20466 sqlite3GlobalConfig.m.xFree(p);
20467 sqlite3_mutex_leave(mem0.mutex);
20468 }else{
20469 sqlite3GlobalConfig.m.xFree(p);
20474 ** Add the size of memory allocation "p" to the count in
20475 ** *db->pnBytesFreed.
20477 static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
20478 *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
20482 ** Free memory that might be associated with a particular database
20483 ** connection.
20485 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
20486 assert( db==0 || sqlite3_mutex_held(db->mutex) );
20487 if( p==0 ) return;
20488 if( db ){
20489 if( db->pnBytesFreed ){
20490 measureAllocationSize(db, p);
20491 return;
20493 if( isLookaside(db, p) ){
20494 LookasideSlot *pBuf = (LookasideSlot*)p;
20495 #if SQLITE_DEBUG
20496 /* Trash all content in the buffer being freed */
20497 memset(p, 0xaa, db->lookaside.sz);
20498 #endif
20499 pBuf->pNext = db->lookaside.pFree;
20500 db->lookaside.pFree = pBuf;
20501 db->lookaside.nOut--;
20502 return;
20505 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20506 assert( sqlite3MemdebugNoType(p, ~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20507 assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
20508 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
20509 sqlite3_free(p);
20513 ** Change the size of an existing memory allocation
20515 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
20516 int nOld, nNew, nDiff;
20517 void *pNew;
20518 assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
20519 assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
20520 if( pOld==0 ){
20521 return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
20523 if( nBytes==0 ){
20524 sqlite3_free(pOld); /* IMP: R-26507-47431 */
20525 return 0;
20527 if( nBytes>=0x7fffff00 ){
20528 /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
20529 return 0;
20531 nOld = sqlite3MallocSize(pOld);
20532 /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
20533 ** argument to xRealloc is always a value returned by a prior call to
20534 ** xRoundup. */
20535 nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
20536 if( nOld==nNew ){
20537 pNew = pOld;
20538 }else if( sqlite3GlobalConfig.bMemstat ){
20539 sqlite3_mutex_enter(mem0.mutex);
20540 sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
20541 nDiff = nNew - nOld;
20542 if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
20543 mem0.alarmThreshold-nDiff ){
20544 sqlite3MallocAlarm(nDiff);
20546 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
20547 if( pNew==0 && mem0.alarmCallback ){
20548 sqlite3MallocAlarm((int)nBytes);
20549 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
20551 if( pNew ){
20552 nNew = sqlite3MallocSize(pNew);
20553 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
20555 sqlite3_mutex_leave(mem0.mutex);
20556 }else{
20557 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
20559 assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
20560 return pNew;
20564 ** The public interface to sqlite3Realloc. Make sure that the memory
20565 ** subsystem is initialized prior to invoking sqliteRealloc.
20567 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
20568 #ifndef SQLITE_OMIT_AUTOINIT
20569 if( sqlite3_initialize() ) return 0;
20570 #endif
20571 if( n<0 ) n = 0; /* IMP: R-26507-47431 */
20572 return sqlite3Realloc(pOld, n);
20574 SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
20575 #ifndef SQLITE_OMIT_AUTOINIT
20576 if( sqlite3_initialize() ) return 0;
20577 #endif
20578 return sqlite3Realloc(pOld, n);
20583 ** Allocate and zero memory.
20585 SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
20586 void *p = sqlite3Malloc(n);
20587 if( p ){
20588 memset(p, 0, (size_t)n);
20590 return p;
20594 ** Allocate and zero memory. If the allocation fails, make
20595 ** the mallocFailed flag in the connection pointer.
20597 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
20598 void *p = sqlite3DbMallocRaw(db, n);
20599 if( p ){
20600 memset(p, 0, (size_t)n);
20602 return p;
20606 ** Allocate and zero memory. If the allocation fails, make
20607 ** the mallocFailed flag in the connection pointer.
20609 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
20610 ** failure on the same database connection) then always return 0.
20611 ** Hence for a particular database connection, once malloc starts
20612 ** failing, it fails consistently until mallocFailed is reset.
20613 ** This is an important assumption. There are many places in the
20614 ** code that do things like this:
20616 ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
20617 ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
20618 ** if( b ) a[10] = 9;
20620 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
20621 ** that all prior mallocs (ex: "a") worked too.
20623 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
20624 void *p;
20625 assert( db==0 || sqlite3_mutex_held(db->mutex) );
20626 assert( db==0 || db->pnBytesFreed==0 );
20627 #ifndef SQLITE_OMIT_LOOKASIDE
20628 if( db ){
20629 LookasideSlot *pBuf;
20630 if( db->mallocFailed ){
20631 return 0;
20633 if( db->lookaside.bEnabled ){
20634 if( n>db->lookaside.sz ){
20635 db->lookaside.anStat[1]++;
20636 }else if( (pBuf = db->lookaside.pFree)==0 ){
20637 db->lookaside.anStat[2]++;
20638 }else{
20639 db->lookaside.pFree = pBuf->pNext;
20640 db->lookaside.nOut++;
20641 db->lookaside.anStat[0]++;
20642 if( db->lookaside.nOut>db->lookaside.mxOut ){
20643 db->lookaside.mxOut = db->lookaside.nOut;
20645 return (void*)pBuf;
20649 #else
20650 if( db && db->mallocFailed ){
20651 return 0;
20653 #endif
20654 p = sqlite3Malloc(n);
20655 if( !p && db ){
20656 db->mallocFailed = 1;
20658 sqlite3MemdebugSetType(p,
20659 (db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
20660 return p;
20664 ** Resize the block of memory pointed to by p to n bytes. If the
20665 ** resize fails, set the mallocFailed flag in the connection object.
20667 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
20668 void *pNew = 0;
20669 assert( db!=0 );
20670 assert( sqlite3_mutex_held(db->mutex) );
20671 if( db->mallocFailed==0 ){
20672 if( p==0 ){
20673 return sqlite3DbMallocRaw(db, n);
20675 if( isLookaside(db, p) ){
20676 if( n<=db->lookaside.sz ){
20677 return p;
20679 pNew = sqlite3DbMallocRaw(db, n);
20680 if( pNew ){
20681 memcpy(pNew, p, db->lookaside.sz);
20682 sqlite3DbFree(db, p);
20684 }else{
20685 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20686 assert( sqlite3MemdebugNoType(p, ~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20687 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
20688 pNew = sqlite3_realloc64(p, n);
20689 if( !pNew ){
20690 db->mallocFailed = 1;
20692 sqlite3MemdebugSetType(pNew,
20693 (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
20696 return pNew;
20700 ** Attempt to reallocate p. If the reallocation fails, then free p
20701 ** and set the mallocFailed flag in the database connection.
20703 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
20704 void *pNew;
20705 pNew = sqlite3DbRealloc(db, p, n);
20706 if( !pNew ){
20707 sqlite3DbFree(db, p);
20709 return pNew;
20713 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
20714 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
20715 ** is because when memory debugging is turned on, these two functions are
20716 ** called via macros that record the current file and line number in the
20717 ** ThreadData structure.
20719 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
20720 char *zNew;
20721 size_t n;
20722 if( z==0 ){
20723 return 0;
20725 n = sqlite3Strlen30(z) + 1;
20726 assert( (n&0x7fffffff)==n );
20727 zNew = sqlite3DbMallocRaw(db, (int)n);
20728 if( zNew ){
20729 memcpy(zNew, z, n);
20731 return zNew;
20733 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
20734 char *zNew;
20735 if( z==0 ){
20736 return 0;
20738 assert( (n&0x7fffffff)==n );
20739 zNew = sqlite3DbMallocRaw(db, n+1);
20740 if( zNew ){
20741 memcpy(zNew, z, (size_t)n);
20742 zNew[n] = 0;
20744 return zNew;
20748 ** Create a string from the zFromat argument and the va_list that follows.
20749 ** Store the string in memory obtained from sqliteMalloc() and make *pz
20750 ** point to that string.
20752 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
20753 va_list ap;
20754 char *z;
20756 va_start(ap, zFormat);
20757 z = sqlite3VMPrintf(db, zFormat, ap);
20758 va_end(ap);
20759 sqlite3DbFree(db, *pz);
20760 *pz = z;
20764 ** Take actions at the end of an API call to indicate an OOM error
20766 static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
20767 db->mallocFailed = 0;
20768 sqlite3Error(db, SQLITE_NOMEM);
20769 return SQLITE_NOMEM;
20773 ** This function must be called before exiting any API function (i.e.
20774 ** returning control to the user) that has called sqlite3_malloc or
20775 ** sqlite3_realloc.
20777 ** The returned value is normally a copy of the second argument to this
20778 ** function. However, if a malloc() failure has occurred since the previous
20779 ** invocation SQLITE_NOMEM is returned instead.
20781 ** If the first argument, db, is not NULL and a malloc() error has occurred,
20782 ** then the connection error-code (the value returned by sqlite3_errcode())
20783 ** is set to SQLITE_NOMEM.
20785 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
20786 /* If the db handle is not NULL, then we must hold the connection handle
20787 ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
20788 ** is unsafe, as is the call to sqlite3Error().
20790 assert( !db || sqlite3_mutex_held(db->mutex) );
20791 if( db==0 ) return rc & 0xff;
20792 if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
20793 return apiOomError(db);
20795 return rc & db->errMask;
20798 /************** End of malloc.c **********************************************/
20799 /************** Begin file printf.c ******************************************/
20801 ** The "printf" code that follows dates from the 1980's. It is in
20802 ** the public domain. The original comments are included here for
20803 ** completeness. They are very out-of-date but might be useful as
20804 ** an historical reference. Most of the "enhancements" have been backed
20805 ** out so that the functionality is now the same as standard printf().
20807 **************************************************************************
20809 ** This file contains code for a set of "printf"-like routines. These
20810 ** routines format strings much like the printf() from the standard C
20811 ** library, though the implementation here has enhancements to support
20812 ** SQLlite.
20816 ** If the strchrnul() library function is available, then set
20817 ** HAVE_STRCHRNUL. If that routine is not available, this module
20818 ** will supply its own. The built-in version is slower than
20819 ** the glibc version so the glibc version is definitely preferred.
20821 #if !defined(HAVE_STRCHRNUL)
20822 # define HAVE_STRCHRNUL 0
20823 #endif
20827 ** Conversion types fall into various categories as defined by the
20828 ** following enumeration.
20830 #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
20831 #define etFLOAT 2 /* Floating point. %f */
20832 #define etEXP 3 /* Exponentional notation. %e and %E */
20833 #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
20834 #define etSIZE 5 /* Return number of characters processed so far. %n */
20835 #define etSTRING 6 /* Strings. %s */
20836 #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
20837 #define etPERCENT 8 /* Percent symbol. %% */
20838 #define etCHARX 9 /* Characters. %c */
20839 /* The rest are extensions, not normally found in printf() */
20840 #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
20841 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
20842 NULL pointers replaced by SQL NULL. %Q */
20843 #define etTOKEN 12 /* a pointer to a Token structure */
20844 #define etSRCLIST 13 /* a pointer to a SrcList */
20845 #define etPOINTER 14 /* The %p conversion */
20846 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
20847 #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
20849 #define etINVALID 0 /* Any unrecognized conversion type */
20853 ** An "etByte" is an 8-bit unsigned value.
20855 typedef unsigned char etByte;
20858 ** Each builtin conversion character (ex: the 'd' in "%d") is described
20859 ** by an instance of the following structure
20861 typedef struct et_info { /* Information about each format field */
20862 char fmttype; /* The format field code letter */
20863 etByte base; /* The base for radix conversion */
20864 etByte flags; /* One or more of FLAG_ constants below */
20865 etByte type; /* Conversion paradigm */
20866 etByte charset; /* Offset into aDigits[] of the digits string */
20867 etByte prefix; /* Offset into aPrefix[] of the prefix string */
20868 } et_info;
20871 ** Allowed values for et_info.flags
20873 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
20874 #define FLAG_INTERN 2 /* True if for internal use only */
20875 #define FLAG_STRING 4 /* Allow infinity precision */
20879 ** The following table is searched linearly, so it is good to put the
20880 ** most frequently used conversion types first.
20882 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
20883 static const char aPrefix[] = "-x0\000X0";
20884 static const et_info fmtinfo[] = {
20885 { 'd', 10, 1, etRADIX, 0, 0 },
20886 { 's', 0, 4, etSTRING, 0, 0 },
20887 { 'g', 0, 1, etGENERIC, 30, 0 },
20888 { 'z', 0, 4, etDYNSTRING, 0, 0 },
20889 { 'q', 0, 4, etSQLESCAPE, 0, 0 },
20890 { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
20891 { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
20892 { 'c', 0, 0, etCHARX, 0, 0 },
20893 { 'o', 8, 0, etRADIX, 0, 2 },
20894 { 'u', 10, 0, etRADIX, 0, 0 },
20895 { 'x', 16, 0, etRADIX, 16, 1 },
20896 { 'X', 16, 0, etRADIX, 0, 4 },
20897 #ifndef SQLITE_OMIT_FLOATING_POINT
20898 { 'f', 0, 1, etFLOAT, 0, 0 },
20899 { 'e', 0, 1, etEXP, 30, 0 },
20900 { 'E', 0, 1, etEXP, 14, 0 },
20901 { 'G', 0, 1, etGENERIC, 14, 0 },
20902 #endif
20903 { 'i', 10, 1, etRADIX, 0, 0 },
20904 { 'n', 0, 0, etSIZE, 0, 0 },
20905 { '%', 0, 0, etPERCENT, 0, 0 },
20906 { 'p', 16, 0, etPOINTER, 0, 1 },
20908 /* All the rest have the FLAG_INTERN bit set and are thus for internal
20909 ** use only */
20910 { 'T', 0, 2, etTOKEN, 0, 0 },
20911 { 'S', 0, 2, etSRCLIST, 0, 0 },
20912 { 'r', 10, 3, etORDINAL, 0, 0 },
20916 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
20917 ** conversions will work.
20919 #ifndef SQLITE_OMIT_FLOATING_POINT
20921 ** "*val" is a double such that 0.1 <= *val < 10.0
20922 ** Return the ascii code for the leading digit of *val, then
20923 ** multiply "*val" by 10.0 to renormalize.
20925 ** Example:
20926 ** input: *val = 3.14159
20927 ** output: *val = 1.4159 function return = '3'
20929 ** The counter *cnt is incremented each time. After counter exceeds
20930 ** 16 (the number of significant digits in a 64-bit float) '0' is
20931 ** always returned.
20933 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
20934 int digit;
20935 LONGDOUBLE_TYPE d;
20936 if( (*cnt)<=0 ) return '0';
20937 (*cnt)--;
20938 digit = (int)*val;
20939 d = digit;
20940 digit += '0';
20941 *val = (*val - d)*10.0;
20942 return (char)digit;
20944 #endif /* SQLITE_OMIT_FLOATING_POINT */
20947 ** Set the StrAccum object to an error mode.
20949 static void setStrAccumError(StrAccum *p, u8 eError){
20950 p->accError = eError;
20951 p->nAlloc = 0;
20955 ** Extra argument values from a PrintfArguments object
20957 static sqlite3_int64 getIntArg(PrintfArguments *p){
20958 if( p->nArg<=p->nUsed ) return 0;
20959 return sqlite3_value_int64(p->apArg[p->nUsed++]);
20961 static double getDoubleArg(PrintfArguments *p){
20962 if( p->nArg<=p->nUsed ) return 0.0;
20963 return sqlite3_value_double(p->apArg[p->nUsed++]);
20965 static char *getTextArg(PrintfArguments *p){
20966 if( p->nArg<=p->nUsed ) return 0;
20967 return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
20972 ** On machines with a small stack size, you can redefine the
20973 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
20975 #ifndef SQLITE_PRINT_BUF_SIZE
20976 # define SQLITE_PRINT_BUF_SIZE 70
20977 #endif
20978 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
20981 ** Render a string given by "fmt" into the StrAccum object.
20983 SQLITE_PRIVATE void sqlite3VXPrintf(
20984 StrAccum *pAccum, /* Accumulate results here */
20985 u32 bFlags, /* SQLITE_PRINTF_* flags */
20986 const char *fmt, /* Format string */
20987 va_list ap /* arguments */
20989 int c; /* Next character in the format string */
20990 char *bufpt; /* Pointer to the conversion buffer */
20991 int precision; /* Precision of the current field */
20992 int length; /* Length of the field */
20993 int idx; /* A general purpose loop counter */
20994 int width; /* Width of the current field */
20995 etByte flag_leftjustify; /* True if "-" flag is present */
20996 etByte flag_plussign; /* True if "+" flag is present */
20997 etByte flag_blanksign; /* True if " " flag is present */
20998 etByte flag_alternateform; /* True if "#" flag is present */
20999 etByte flag_altform2; /* True if "!" flag is present */
21000 etByte flag_zeropad; /* True if field width constant starts with zero */
21001 etByte flag_long; /* True if "l" flag is present */
21002 etByte flag_longlong; /* True if the "ll" flag is present */
21003 etByte done; /* Loop termination flag */
21004 etByte xtype = 0; /* Conversion paradigm */
21005 u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
21006 u8 useIntern; /* Ok to use internal conversions (ex: %T) */
21007 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
21008 sqlite_uint64 longvalue; /* Value for integer types */
21009 LONGDOUBLE_TYPE realvalue; /* Value for real types */
21010 const et_info *infop; /* Pointer to the appropriate info structure */
21011 char *zOut; /* Rendering buffer */
21012 int nOut; /* Size of the rendering buffer */
21013 char *zExtra = 0; /* Malloced memory used by some conversion */
21014 #ifndef SQLITE_OMIT_FLOATING_POINT
21015 int exp, e2; /* exponent of real numbers */
21016 int nsd; /* Number of significant digits returned */
21017 double rounder; /* Used for rounding floating point values */
21018 etByte flag_dp; /* True if decimal point should be shown */
21019 etByte flag_rtz; /* True if trailing zeros should be removed */
21020 #endif
21021 PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
21022 char buf[etBUFSIZE]; /* Conversion buffer */
21024 bufpt = 0;
21025 if( bFlags ){
21026 if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
21027 pArgList = va_arg(ap, PrintfArguments*);
21029 useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
21030 }else{
21031 bArgList = useIntern = 0;
21033 for(; (c=(*fmt))!=0; ++fmt){
21034 if( c!='%' ){
21035 bufpt = (char *)fmt;
21036 #if HAVE_STRCHRNUL
21037 fmt = strchrnul(fmt, '%');
21038 #else
21039 do{ fmt++; }while( *fmt && *fmt != '%' );
21040 #endif
21041 sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
21042 if( *fmt==0 ) break;
21044 if( (c=(*++fmt))==0 ){
21045 sqlite3StrAccumAppend(pAccum, "%", 1);
21046 break;
21048 /* Find out what flags are present */
21049 flag_leftjustify = flag_plussign = flag_blanksign =
21050 flag_alternateform = flag_altform2 = flag_zeropad = 0;
21051 done = 0;
21053 switch( c ){
21054 case '-': flag_leftjustify = 1; break;
21055 case '+': flag_plussign = 1; break;
21056 case ' ': flag_blanksign = 1; break;
21057 case '#': flag_alternateform = 1; break;
21058 case '!': flag_altform2 = 1; break;
21059 case '0': flag_zeropad = 1; break;
21060 default: done = 1; break;
21062 }while( !done && (c=(*++fmt))!=0 );
21063 /* Get the field width */
21064 width = 0;
21065 if( c=='*' ){
21066 if( bArgList ){
21067 width = (int)getIntArg(pArgList);
21068 }else{
21069 width = va_arg(ap,int);
21071 if( width<0 ){
21072 flag_leftjustify = 1;
21073 width = -width;
21075 c = *++fmt;
21076 }else{
21077 while( c>='0' && c<='9' ){
21078 width = width*10 + c - '0';
21079 c = *++fmt;
21082 /* Get the precision */
21083 if( c=='.' ){
21084 precision = 0;
21085 c = *++fmt;
21086 if( c=='*' ){
21087 if( bArgList ){
21088 precision = (int)getIntArg(pArgList);
21089 }else{
21090 precision = va_arg(ap,int);
21092 if( precision<0 ) precision = -precision;
21093 c = *++fmt;
21094 }else{
21095 while( c>='0' && c<='9' ){
21096 precision = precision*10 + c - '0';
21097 c = *++fmt;
21100 }else{
21101 precision = -1;
21103 /* Get the conversion type modifier */
21104 if( c=='l' ){
21105 flag_long = 1;
21106 c = *++fmt;
21107 if( c=='l' ){
21108 flag_longlong = 1;
21109 c = *++fmt;
21110 }else{
21111 flag_longlong = 0;
21113 }else{
21114 flag_long = flag_longlong = 0;
21116 /* Fetch the info entry for the field */
21117 infop = &fmtinfo[0];
21118 xtype = etINVALID;
21119 for(idx=0; idx<ArraySize(fmtinfo); idx++){
21120 if( c==fmtinfo[idx].fmttype ){
21121 infop = &fmtinfo[idx];
21122 if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
21123 xtype = infop->type;
21124 }else{
21125 return;
21127 break;
21132 ** At this point, variables are initialized as follows:
21134 ** flag_alternateform TRUE if a '#' is present.
21135 ** flag_altform2 TRUE if a '!' is present.
21136 ** flag_plussign TRUE if a '+' is present.
21137 ** flag_leftjustify TRUE if a '-' is present or if the
21138 ** field width was negative.
21139 ** flag_zeropad TRUE if the width began with 0.
21140 ** flag_long TRUE if the letter 'l' (ell) prefixed
21141 ** the conversion character.
21142 ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
21143 ** the conversion character.
21144 ** flag_blanksign TRUE if a ' ' is present.
21145 ** width The specified field width. This is
21146 ** always non-negative. Zero is the default.
21147 ** precision The specified precision. The default
21148 ** is -1.
21149 ** xtype The class of the conversion.
21150 ** infop Pointer to the appropriate info struct.
21152 switch( xtype ){
21153 case etPOINTER:
21154 flag_longlong = sizeof(char*)==sizeof(i64);
21155 flag_long = sizeof(char*)==sizeof(long int);
21156 /* Fall through into the next case */
21157 case etORDINAL:
21158 case etRADIX:
21159 if( infop->flags & FLAG_SIGNED ){
21160 i64 v;
21161 if( bArgList ){
21162 v = getIntArg(pArgList);
21163 }else if( flag_longlong ){
21164 v = va_arg(ap,i64);
21165 }else if( flag_long ){
21166 v = va_arg(ap,long int);
21167 }else{
21168 v = va_arg(ap,int);
21170 if( v<0 ){
21171 if( v==SMALLEST_INT64 ){
21172 longvalue = ((u64)1)<<63;
21173 }else{
21174 longvalue = -v;
21176 prefix = '-';
21177 }else{
21178 longvalue = v;
21179 if( flag_plussign ) prefix = '+';
21180 else if( flag_blanksign ) prefix = ' ';
21181 else prefix = 0;
21183 }else{
21184 if( bArgList ){
21185 longvalue = (u64)getIntArg(pArgList);
21186 }else if( flag_longlong ){
21187 longvalue = va_arg(ap,u64);
21188 }else if( flag_long ){
21189 longvalue = va_arg(ap,unsigned long int);
21190 }else{
21191 longvalue = va_arg(ap,unsigned int);
21193 prefix = 0;
21195 if( longvalue==0 ) flag_alternateform = 0;
21196 if( flag_zeropad && precision<width-(prefix!=0) ){
21197 precision = width-(prefix!=0);
21199 if( precision<etBUFSIZE-10 ){
21200 nOut = etBUFSIZE;
21201 zOut = buf;
21202 }else{
21203 nOut = precision + 10;
21204 zOut = zExtra = sqlite3Malloc( nOut );
21205 if( zOut==0 ){
21206 setStrAccumError(pAccum, STRACCUM_NOMEM);
21207 return;
21210 bufpt = &zOut[nOut-1];
21211 if( xtype==etORDINAL ){
21212 static const char zOrd[] = "thstndrd";
21213 int x = (int)(longvalue % 10);
21214 if( x>=4 || (longvalue/10)%10==1 ){
21215 x = 0;
21217 *(--bufpt) = zOrd[x*2+1];
21218 *(--bufpt) = zOrd[x*2];
21221 const char *cset = &aDigits[infop->charset];
21222 u8 base = infop->base;
21223 do{ /* Convert to ascii */
21224 *(--bufpt) = cset[longvalue%base];
21225 longvalue = longvalue/base;
21226 }while( longvalue>0 );
21228 length = (int)(&zOut[nOut-1]-bufpt);
21229 for(idx=precision-length; idx>0; idx--){
21230 *(--bufpt) = '0'; /* Zero pad */
21232 if( prefix ) *(--bufpt) = prefix; /* Add sign */
21233 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
21234 const char *pre;
21235 char x;
21236 pre = &aPrefix[infop->prefix];
21237 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
21239 length = (int)(&zOut[nOut-1]-bufpt);
21240 break;
21241 case etFLOAT:
21242 case etEXP:
21243 case etGENERIC:
21244 if( bArgList ){
21245 realvalue = getDoubleArg(pArgList);
21246 }else{
21247 realvalue = va_arg(ap,double);
21249 #ifdef SQLITE_OMIT_FLOATING_POINT
21250 length = 0;
21251 #else
21252 if( precision<0 ) precision = 6; /* Set default precision */
21253 if( realvalue<0.0 ){
21254 realvalue = -realvalue;
21255 prefix = '-';
21256 }else{
21257 if( flag_plussign ) prefix = '+';
21258 else if( flag_blanksign ) prefix = ' ';
21259 else prefix = 0;
21261 if( xtype==etGENERIC && precision>0 ) precision--;
21262 for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
21263 if( xtype==etFLOAT ) realvalue += rounder;
21264 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
21265 exp = 0;
21266 if( sqlite3IsNaN((double)realvalue) ){
21267 bufpt = "NaN";
21268 length = 3;
21269 break;
21271 if( realvalue>0.0 ){
21272 LONGDOUBLE_TYPE scale = 1.0;
21273 while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
21274 while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
21275 while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
21276 while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
21277 realvalue /= scale;
21278 while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
21279 while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
21280 if( exp>350 ){
21281 if( prefix=='-' ){
21282 bufpt = "-Inf";
21283 }else if( prefix=='+' ){
21284 bufpt = "+Inf";
21285 }else{
21286 bufpt = "Inf";
21288 length = sqlite3Strlen30(bufpt);
21289 break;
21292 bufpt = buf;
21294 ** If the field type is etGENERIC, then convert to either etEXP
21295 ** or etFLOAT, as appropriate.
21297 if( xtype!=etFLOAT ){
21298 realvalue += rounder;
21299 if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
21301 if( xtype==etGENERIC ){
21302 flag_rtz = !flag_alternateform;
21303 if( exp<-4 || exp>precision ){
21304 xtype = etEXP;
21305 }else{
21306 precision = precision - exp;
21307 xtype = etFLOAT;
21309 }else{
21310 flag_rtz = flag_altform2;
21312 if( xtype==etEXP ){
21313 e2 = 0;
21314 }else{
21315 e2 = exp;
21317 if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){
21318 bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 );
21319 if( bufpt==0 ){
21320 setStrAccumError(pAccum, STRACCUM_NOMEM);
21321 return;
21324 zOut = bufpt;
21325 nsd = 16 + flag_altform2*10;
21326 flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
21327 /* The sign in front of the number */
21328 if( prefix ){
21329 *(bufpt++) = prefix;
21331 /* Digits prior to the decimal point */
21332 if( e2<0 ){
21333 *(bufpt++) = '0';
21334 }else{
21335 for(; e2>=0; e2--){
21336 *(bufpt++) = et_getdigit(&realvalue,&nsd);
21339 /* The decimal point */
21340 if( flag_dp ){
21341 *(bufpt++) = '.';
21343 /* "0" digits after the decimal point but before the first
21344 ** significant digit of the number */
21345 for(e2++; e2<0; precision--, e2++){
21346 assert( precision>0 );
21347 *(bufpt++) = '0';
21349 /* Significant digits after the decimal point */
21350 while( (precision--)>0 ){
21351 *(bufpt++) = et_getdigit(&realvalue,&nsd);
21353 /* Remove trailing zeros and the "." if no digits follow the "." */
21354 if( flag_rtz && flag_dp ){
21355 while( bufpt[-1]=='0' ) *(--bufpt) = 0;
21356 assert( bufpt>zOut );
21357 if( bufpt[-1]=='.' ){
21358 if( flag_altform2 ){
21359 *(bufpt++) = '0';
21360 }else{
21361 *(--bufpt) = 0;
21365 /* Add the "eNNN" suffix */
21366 if( xtype==etEXP ){
21367 *(bufpt++) = aDigits[infop->charset];
21368 if( exp<0 ){
21369 *(bufpt++) = '-'; exp = -exp;
21370 }else{
21371 *(bufpt++) = '+';
21373 if( exp>=100 ){
21374 *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
21375 exp %= 100;
21377 *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
21378 *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
21380 *bufpt = 0;
21382 /* The converted number is in buf[] and zero terminated. Output it.
21383 ** Note that the number is in the usual order, not reversed as with
21384 ** integer conversions. */
21385 length = (int)(bufpt-zOut);
21386 bufpt = zOut;
21388 /* Special case: Add leading zeros if the flag_zeropad flag is
21389 ** set and we are not left justified */
21390 if( flag_zeropad && !flag_leftjustify && length < width){
21391 int i;
21392 int nPad = width - length;
21393 for(i=width; i>=nPad; i--){
21394 bufpt[i] = bufpt[i-nPad];
21396 i = prefix!=0;
21397 while( nPad-- ) bufpt[i++] = '0';
21398 length = width;
21400 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
21401 break;
21402 case etSIZE:
21403 if( !bArgList ){
21404 *(va_arg(ap,int*)) = pAccum->nChar;
21406 length = width = 0;
21407 break;
21408 case etPERCENT:
21409 buf[0] = '%';
21410 bufpt = buf;
21411 length = 1;
21412 break;
21413 case etCHARX:
21414 if( bArgList ){
21415 bufpt = getTextArg(pArgList);
21416 c = bufpt ? bufpt[0] : 0;
21417 }else{
21418 c = va_arg(ap,int);
21420 if( precision>1 ){
21421 width -= precision-1;
21422 if( width>1 && !flag_leftjustify ){
21423 sqlite3AppendChar(pAccum, width-1, ' ');
21424 width = 0;
21426 sqlite3AppendChar(pAccum, precision-1, c);
21428 length = 1;
21429 buf[0] = c;
21430 bufpt = buf;
21431 break;
21432 case etSTRING:
21433 case etDYNSTRING:
21434 if( bArgList ){
21435 bufpt = getTextArg(pArgList);
21436 }else{
21437 bufpt = va_arg(ap,char*);
21439 if( bufpt==0 ){
21440 bufpt = "";
21441 }else if( xtype==etDYNSTRING && !bArgList ){
21442 zExtra = bufpt;
21444 if( precision>=0 ){
21445 for(length=0; length<precision && bufpt[length]; length++){}
21446 }else{
21447 length = sqlite3Strlen30(bufpt);
21449 break;
21450 case etSQLESCAPE:
21451 case etSQLESCAPE2:
21452 case etSQLESCAPE3: {
21453 int i, j, k, n, isnull;
21454 int needQuote;
21455 char ch;
21456 char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
21457 char *escarg;
21459 if( bArgList ){
21460 escarg = getTextArg(pArgList);
21461 }else{
21462 escarg = va_arg(ap,char*);
21464 isnull = escarg==0;
21465 if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
21466 k = precision;
21467 for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
21468 if( ch==q ) n++;
21470 needQuote = !isnull && xtype==etSQLESCAPE2;
21471 n += i + 1 + needQuote*2;
21472 if( n>etBUFSIZE ){
21473 bufpt = zExtra = sqlite3Malloc( n );
21474 if( bufpt==0 ){
21475 setStrAccumError(pAccum, STRACCUM_NOMEM);
21476 return;
21478 }else{
21479 bufpt = buf;
21481 j = 0;
21482 if( needQuote ) bufpt[j++] = q;
21483 k = i;
21484 for(i=0; i<k; i++){
21485 bufpt[j++] = ch = escarg[i];
21486 if( ch==q ) bufpt[j++] = ch;
21488 if( needQuote ) bufpt[j++] = q;
21489 bufpt[j] = 0;
21490 length = j;
21491 /* The precision in %q and %Q means how many input characters to
21492 ** consume, not the length of the output...
21493 ** if( precision>=0 && precision<length ) length = precision; */
21494 break;
21496 case etTOKEN: {
21497 Token *pToken = va_arg(ap, Token*);
21498 assert( bArgList==0 );
21499 if( pToken && pToken->n ){
21500 sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
21502 length = width = 0;
21503 break;
21505 case etSRCLIST: {
21506 SrcList *pSrc = va_arg(ap, SrcList*);
21507 int k = va_arg(ap, int);
21508 struct SrcList_item *pItem = &pSrc->a[k];
21509 assert( bArgList==0 );
21510 assert( k>=0 && k<pSrc->nSrc );
21511 if( pItem->zDatabase ){
21512 sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
21513 sqlite3StrAccumAppend(pAccum, ".", 1);
21515 sqlite3StrAccumAppendAll(pAccum, pItem->zName);
21516 length = width = 0;
21517 break;
21519 default: {
21520 assert( xtype==etINVALID );
21521 return;
21523 }/* End switch over the format type */
21525 ** The text of the conversion is pointed to by "bufpt" and is
21526 ** "length" characters long. The field width is "width". Do
21527 ** the output.
21529 width -= length;
21530 if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
21531 sqlite3StrAccumAppend(pAccum, bufpt, length);
21532 if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
21534 if( zExtra ){
21535 sqlite3_free(zExtra);
21536 zExtra = 0;
21538 }/* End for loop over the format string */
21539 } /* End of function */
21542 ** Enlarge the memory allocation on a StrAccum object so that it is
21543 ** able to accept at least N more bytes of text.
21545 ** Return the number of bytes of text that StrAccum is able to accept
21546 ** after the attempted enlargement. The value returned might be zero.
21548 static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
21549 char *zNew;
21550 assert( p->nChar+N >= p->nAlloc ); /* Only called if really needed */
21551 if( p->accError ){
21552 testcase(p->accError==STRACCUM_TOOBIG);
21553 testcase(p->accError==STRACCUM_NOMEM);
21554 return 0;
21556 if( !p->useMalloc ){
21557 N = p->nAlloc - p->nChar - 1;
21558 setStrAccumError(p, STRACCUM_TOOBIG);
21559 return N;
21560 }else{
21561 char *zOld = (p->zText==p->zBase ? 0 : p->zText);
21562 i64 szNew = p->nChar;
21563 szNew += N + 1;
21564 if( szNew > p->mxAlloc ){
21565 sqlite3StrAccumReset(p);
21566 setStrAccumError(p, STRACCUM_TOOBIG);
21567 return 0;
21568 }else{
21569 p->nAlloc = (int)szNew;
21571 if( p->useMalloc==1 ){
21572 zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
21573 }else{
21574 zNew = sqlite3_realloc(zOld, p->nAlloc);
21576 if( zNew ){
21577 assert( p->zText!=0 || p->nChar==0 );
21578 if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
21579 p->zText = zNew;
21580 }else{
21581 sqlite3StrAccumReset(p);
21582 setStrAccumError(p, STRACCUM_NOMEM);
21583 return 0;
21586 return N;
21590 ** Append N copies of character c to the given string buffer.
21592 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
21593 if( p->nChar+N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ) return;
21594 while( (N--)>0 ) p->zText[p->nChar++] = c;
21598 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
21599 ** So enlarge if first, then do the append.
21601 ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
21602 ** work (enlarging the buffer) using tail recursion, so that the
21603 ** sqlite3StrAccumAppend() routine can use fast calling semantics.
21605 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
21606 N = sqlite3StrAccumEnlarge(p, N);
21607 if( N>0 ){
21608 memcpy(&p->zText[p->nChar], z, N);
21609 p->nChar += N;
21614 ** Append N bytes of text from z to the StrAccum object. Increase the
21615 ** size of the memory allocation for StrAccum if necessary.
21617 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
21618 assert( z!=0 );
21619 assert( p->zText!=0 || p->nChar==0 || p->accError );
21620 assert( N>=0 );
21621 assert( p->accError==0 || p->nAlloc==0 );
21622 if( p->nChar+N >= p->nAlloc ){
21623 enlargeAndAppend(p,z,N);
21624 }else{
21625 assert( p->zText );
21626 p->nChar += N;
21627 memcpy(&p->zText[p->nChar-N], z, N);
21632 ** Append the complete text of zero-terminated string z[] to the p string.
21634 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
21635 sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
21640 ** Finish off a string by making sure it is zero-terminated.
21641 ** Return a pointer to the resulting string. Return a NULL
21642 ** pointer if any kind of error was encountered.
21644 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
21645 if( p->zText ){
21646 p->zText[p->nChar] = 0;
21647 if( p->useMalloc && p->zText==p->zBase ){
21648 if( p->useMalloc==1 ){
21649 p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
21650 }else{
21651 p->zText = sqlite3_malloc(p->nChar+1);
21653 if( p->zText ){
21654 memcpy(p->zText, p->zBase, p->nChar+1);
21655 }else{
21656 setStrAccumError(p, STRACCUM_NOMEM);
21660 return p->zText;
21664 ** Reset an StrAccum string. Reclaim all malloced memory.
21666 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
21667 if( p->zText!=p->zBase ){
21668 if( p->useMalloc==1 ){
21669 sqlite3DbFree(p->db, p->zText);
21670 }else{
21671 sqlite3_free(p->zText);
21674 p->zText = 0;
21678 ** Initialize a string accumulator
21680 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
21681 p->zText = p->zBase = zBase;
21682 p->db = 0;
21683 p->nChar = 0;
21684 p->nAlloc = n;
21685 p->mxAlloc = mx;
21686 p->useMalloc = 1;
21687 p->accError = 0;
21691 ** Print into memory obtained from sqliteMalloc(). Use the internal
21692 ** %-conversion extensions.
21694 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
21695 char *z;
21696 char zBase[SQLITE_PRINT_BUF_SIZE];
21697 StrAccum acc;
21698 assert( db!=0 );
21699 sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
21700 db->aLimit[SQLITE_LIMIT_LENGTH]);
21701 acc.db = db;
21702 sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
21703 z = sqlite3StrAccumFinish(&acc);
21704 if( acc.accError==STRACCUM_NOMEM ){
21705 db->mallocFailed = 1;
21707 return z;
21711 ** Print into memory obtained from sqliteMalloc(). Use the internal
21712 ** %-conversion extensions.
21714 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
21715 va_list ap;
21716 char *z;
21717 va_start(ap, zFormat);
21718 z = sqlite3VMPrintf(db, zFormat, ap);
21719 va_end(ap);
21720 return z;
21724 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
21725 ** the string and before returning. This routine is intended to be used
21726 ** to modify an existing string. For example:
21728 ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
21731 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
21732 va_list ap;
21733 char *z;
21734 va_start(ap, zFormat);
21735 z = sqlite3VMPrintf(db, zFormat, ap);
21736 va_end(ap);
21737 sqlite3DbFree(db, zStr);
21738 return z;
21742 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
21743 ** %-conversion extensions.
21745 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
21746 char *z;
21747 char zBase[SQLITE_PRINT_BUF_SIZE];
21748 StrAccum acc;
21749 #ifndef SQLITE_OMIT_AUTOINIT
21750 if( sqlite3_initialize() ) return 0;
21751 #endif
21752 sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
21753 acc.useMalloc = 2;
21754 sqlite3VXPrintf(&acc, 0, zFormat, ap);
21755 z = sqlite3StrAccumFinish(&acc);
21756 return z;
21760 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
21761 ** %-conversion extensions.
21763 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
21764 va_list ap;
21765 char *z;
21766 #ifndef SQLITE_OMIT_AUTOINIT
21767 if( sqlite3_initialize() ) return 0;
21768 #endif
21769 va_start(ap, zFormat);
21770 z = sqlite3_vmprintf(zFormat, ap);
21771 va_end(ap);
21772 return z;
21776 ** sqlite3_snprintf() works like snprintf() except that it ignores the
21777 ** current locale settings. This is important for SQLite because we
21778 ** are not able to use a "," as the decimal point in place of "." as
21779 ** specified by some locales.
21781 ** Oops: The first two arguments of sqlite3_snprintf() are backwards
21782 ** from the snprintf() standard. Unfortunately, it is too late to change
21783 ** this without breaking compatibility, so we just have to live with the
21784 ** mistake.
21786 ** sqlite3_vsnprintf() is the varargs version.
21788 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
21789 StrAccum acc;
21790 if( n<=0 ) return zBuf;
21791 sqlite3StrAccumInit(&acc, zBuf, n, 0);
21792 acc.useMalloc = 0;
21793 sqlite3VXPrintf(&acc, 0, zFormat, ap);
21794 return sqlite3StrAccumFinish(&acc);
21796 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
21797 char *z;
21798 va_list ap;
21799 va_start(ap,zFormat);
21800 z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
21801 va_end(ap);
21802 return z;
21806 ** This is the routine that actually formats the sqlite3_log() message.
21807 ** We house it in a separate routine from sqlite3_log() to avoid using
21808 ** stack space on small-stack systems when logging is disabled.
21810 ** sqlite3_log() must render into a static buffer. It cannot dynamically
21811 ** allocate memory because it might be called while the memory allocator
21812 ** mutex is held.
21814 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
21815 StrAccum acc; /* String accumulator */
21816 char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
21818 sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
21819 acc.useMalloc = 0;
21820 sqlite3VXPrintf(&acc, 0, zFormat, ap);
21821 sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
21822 sqlite3StrAccumFinish(&acc));
21826 ** Format and write a message to the log if logging is enabled.
21828 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
21829 va_list ap; /* Vararg list */
21830 if( sqlite3GlobalConfig.xLog ){
21831 va_start(ap, zFormat);
21832 renderLogMsg(iErrCode, zFormat, ap);
21833 va_end(ap);
21837 #if defined(SQLITE_DEBUG)
21839 ** A version of printf() that understands %lld. Used for debugging.
21840 ** The printf() built into some versions of windows does not understand %lld
21841 ** and segfaults if you give it a long long int.
21843 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
21844 va_list ap;
21845 StrAccum acc;
21846 char zBuf[500];
21847 sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
21848 acc.useMalloc = 0;
21849 va_start(ap,zFormat);
21850 sqlite3VXPrintf(&acc, 0, zFormat, ap);
21851 va_end(ap);
21852 sqlite3StrAccumFinish(&acc);
21853 fprintf(stdout,"%s", zBuf);
21854 fflush(stdout);
21856 #endif
21858 #ifdef SQLITE_DEBUG
21859 /*************************************************************************
21860 ** Routines for implementing the "TreeView" display of hierarchical
21861 ** data structures for debugging.
21863 ** The main entry points (coded elsewhere) are:
21864 ** sqlite3TreeViewExpr(0, pExpr, 0);
21865 ** sqlite3TreeViewExprList(0, pList, 0, 0);
21866 ** sqlite3TreeViewSelect(0, pSelect, 0);
21867 ** Insert calls to those routines while debugging in order to display
21868 ** a diagram of Expr, ExprList, and Select objects.
21871 /* Add a new subitem to the tree. The moreToFollow flag indicates that this
21872 ** is not the last item in the tree. */
21873 SQLITE_PRIVATE TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
21874 if( p==0 ){
21875 p = sqlite3_malloc( sizeof(*p) );
21876 if( p==0 ) return 0;
21877 memset(p, 0, sizeof(*p));
21878 }else{
21879 p->iLevel++;
21881 assert( moreToFollow==0 || moreToFollow==1 );
21882 if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
21883 return p;
21885 /* Finished with one layer of the tree */
21886 SQLITE_PRIVATE void sqlite3TreeViewPop(TreeView *p){
21887 if( p==0 ) return;
21888 p->iLevel--;
21889 if( p->iLevel<0 ) sqlite3_free(p);
21891 /* Generate a single line of output for the tree, with a prefix that contains
21892 ** all the appropriate tree lines */
21893 SQLITE_PRIVATE void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
21894 va_list ap;
21895 int i;
21896 StrAccum acc;
21897 char zBuf[500];
21898 sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
21899 acc.useMalloc = 0;
21900 if( p ){
21901 for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
21902 sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
21904 sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
21906 va_start(ap, zFormat);
21907 sqlite3VXPrintf(&acc, 0, zFormat, ap);
21908 va_end(ap);
21909 if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
21910 sqlite3StrAccumFinish(&acc);
21911 fprintf(stdout,"%s", zBuf);
21912 fflush(stdout);
21914 /* Shorthand for starting a new tree item that consists of a single label */
21915 SQLITE_PRIVATE void sqlite3TreeViewItem(TreeView *p, const char *zLabel, u8 moreToFollow){
21916 p = sqlite3TreeViewPush(p, moreToFollow);
21917 sqlite3TreeViewLine(p, "%s", zLabel);
21919 #endif /* SQLITE_DEBUG */
21922 ** variable-argument wrapper around sqlite3VXPrintf().
21924 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
21925 va_list ap;
21926 va_start(ap,zFormat);
21927 sqlite3VXPrintf(p, bFlags, zFormat, ap);
21928 va_end(ap);
21931 /************** End of printf.c **********************************************/
21932 /************** Begin file random.c ******************************************/
21934 ** 2001 September 15
21936 ** The author disclaims copyright to this source code. In place of
21937 ** a legal notice, here is a blessing:
21939 ** May you do good and not evil.
21940 ** May you find forgiveness for yourself and forgive others.
21941 ** May you share freely, never taking more than you give.
21943 *************************************************************************
21944 ** This file contains code to implement a pseudo-random number
21945 ** generator (PRNG) for SQLite.
21947 ** Random numbers are used by some of the database backends in order
21948 ** to generate random integer keys for tables or random filenames.
21952 /* All threads share a single random number generator.
21953 ** This structure is the current state of the generator.
21955 static SQLITE_WSD struct sqlite3PrngType {
21956 unsigned char isInit; /* True if initialized */
21957 unsigned char i, j; /* State variables */
21958 unsigned char s[256]; /* State variables */
21959 } sqlite3Prng;
21962 ** Return N random bytes.
21964 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
21965 unsigned char t;
21966 unsigned char *zBuf = pBuf;
21968 /* The "wsdPrng" macro will resolve to the pseudo-random number generator
21969 ** state vector. If writable static data is unsupported on the target,
21970 ** we have to locate the state vector at run-time. In the more common
21971 ** case where writable static data is supported, wsdPrng can refer directly
21972 ** to the "sqlite3Prng" state vector declared above.
21974 #ifdef SQLITE_OMIT_WSD
21975 struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
21976 # define wsdPrng p[0]
21977 #else
21978 # define wsdPrng sqlite3Prng
21979 #endif
21981 #if SQLITE_THREADSAFE
21982 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
21983 sqlite3_mutex_enter(mutex);
21984 #endif
21986 if( N<=0 ){
21987 wsdPrng.isInit = 0;
21988 sqlite3_mutex_leave(mutex);
21989 return;
21992 /* Initialize the state of the random number generator once,
21993 ** the first time this routine is called. The seed value does
21994 ** not need to contain a lot of randomness since we are not
21995 ** trying to do secure encryption or anything like that...
21997 ** Nothing in this file or anywhere else in SQLite does any kind of
21998 ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
21999 ** number generator) not as an encryption device.
22001 if( !wsdPrng.isInit ){
22002 int i;
22003 char k[256];
22004 wsdPrng.j = 0;
22005 wsdPrng.i = 0;
22006 sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
22007 for(i=0; i<256; i++){
22008 wsdPrng.s[i] = (u8)i;
22010 for(i=0; i<256; i++){
22011 wsdPrng.j += wsdPrng.s[i] + k[i];
22012 t = wsdPrng.s[wsdPrng.j];
22013 wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
22014 wsdPrng.s[i] = t;
22016 wsdPrng.isInit = 1;
22019 assert( N>0 );
22021 wsdPrng.i++;
22022 t = wsdPrng.s[wsdPrng.i];
22023 wsdPrng.j += t;
22024 wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
22025 wsdPrng.s[wsdPrng.j] = t;
22026 t += wsdPrng.s[wsdPrng.i];
22027 *(zBuf++) = wsdPrng.s[t];
22028 }while( --N );
22029 sqlite3_mutex_leave(mutex);
22032 #ifndef SQLITE_OMIT_BUILTIN_TEST
22034 ** For testing purposes, we sometimes want to preserve the state of
22035 ** PRNG and restore the PRNG to its saved state at a later time, or
22036 ** to reset the PRNG to its initial state. These routines accomplish
22037 ** those tasks.
22039 ** The sqlite3_test_control() interface calls these routines to
22040 ** control the PRNG.
22042 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
22043 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
22044 memcpy(
22045 &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
22046 &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
22047 sizeof(sqlite3Prng)
22050 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
22051 memcpy(
22052 &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
22053 &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
22054 sizeof(sqlite3Prng)
22057 #endif /* SQLITE_OMIT_BUILTIN_TEST */
22059 /************** End of random.c **********************************************/
22060 /************** Begin file threads.c *****************************************/
22062 ** 2012 July 21
22064 ** The author disclaims copyright to this source code. In place of
22065 ** a legal notice, here is a blessing:
22067 ** May you do good and not evil.
22068 ** May you find forgiveness for yourself and forgive others.
22069 ** May you share freely, never taking more than you give.
22071 ******************************************************************************
22073 ** This file presents a simple cross-platform threading interface for
22074 ** use internally by SQLite.
22076 ** A "thread" can be created using sqlite3ThreadCreate(). This thread
22077 ** runs independently of its creator until it is joined using
22078 ** sqlite3ThreadJoin(), at which point it terminates.
22080 ** Threads do not have to be real. It could be that the work of the
22081 ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
22082 ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
22083 ** single threaded systems. Nothing in SQLite requires multiple threads.
22084 ** This interface exists so that applications that want to take advantage
22085 ** of multiple cores can do so, while also allowing applications to stay
22086 ** single-threaded if desired.
22089 #if SQLITE_MAX_WORKER_THREADS>0
22091 /********************************* Unix Pthreads ****************************/
22092 #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
22094 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
22095 /* #include <pthread.h> */
22097 /* A running thread */
22098 struct SQLiteThread {
22099 pthread_t tid; /* Thread ID */
22100 int done; /* Set to true when thread finishes */
22101 void *pOut; /* Result returned by the thread */
22102 void *(*xTask)(void*); /* The thread routine */
22103 void *pIn; /* Argument to the thread */
22106 /* Create a new thread */
22107 SQLITE_PRIVATE int sqlite3ThreadCreate(
22108 SQLiteThread **ppThread, /* OUT: Write the thread object here */
22109 void *(*xTask)(void*), /* Routine to run in a separate thread */
22110 void *pIn /* Argument passed into xTask() */
22112 SQLiteThread *p;
22113 int rc;
22115 assert( ppThread!=0 );
22116 assert( xTask!=0 );
22117 /* This routine is never used in single-threaded mode */
22118 assert( sqlite3GlobalConfig.bCoreMutex!=0 );
22120 *ppThread = 0;
22121 p = sqlite3Malloc(sizeof(*p));
22122 if( p==0 ) return SQLITE_NOMEM;
22123 memset(p, 0, sizeof(*p));
22124 p->xTask = xTask;
22125 p->pIn = pIn;
22126 if( sqlite3FaultSim(200) ){
22127 rc = 1;
22128 }else{
22129 rc = pthread_create(&p->tid, 0, xTask, pIn);
22131 if( rc ){
22132 p->done = 1;
22133 p->pOut = xTask(pIn);
22135 *ppThread = p;
22136 return SQLITE_OK;
22139 /* Get the results of the thread */
22140 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
22141 int rc;
22143 assert( ppOut!=0 );
22144 if( NEVER(p==0) ) return SQLITE_NOMEM;
22145 if( p->done ){
22146 *ppOut = p->pOut;
22147 rc = SQLITE_OK;
22148 }else{
22149 rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
22151 sqlite3_free(p);
22152 return rc;
22155 #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
22156 /******************************** End Unix Pthreads *************************/
22159 /********************************* Win32 Threads ****************************/
22160 #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_THREADSAFE>0
22162 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
22163 #include <process.h>
22165 /* A running thread */
22166 struct SQLiteThread {
22167 void *tid; /* The thread handle */
22168 unsigned id; /* The thread identifier */
22169 void *(*xTask)(void*); /* The routine to run as a thread */
22170 void *pIn; /* Argument to xTask */
22171 void *pResult; /* Result of xTask */
22174 /* Thread procedure Win32 compatibility shim */
22175 static unsigned __stdcall sqlite3ThreadProc(
22176 void *pArg /* IN: Pointer to the SQLiteThread structure */
22178 SQLiteThread *p = (SQLiteThread *)pArg;
22180 assert( p!=0 );
22181 #if 0
22183 ** This assert appears to trigger spuriously on certain
22184 ** versions of Windows, possibly due to _beginthreadex()
22185 ** and/or CreateThread() not fully setting their thread
22186 ** ID parameter before starting the thread.
22188 assert( p->id==GetCurrentThreadId() );
22189 #endif
22190 assert( p->xTask!=0 );
22191 p->pResult = p->xTask(p->pIn);
22193 _endthreadex(0);
22194 return 0; /* NOT REACHED */
22197 /* Create a new thread */
22198 SQLITE_PRIVATE int sqlite3ThreadCreate(
22199 SQLiteThread **ppThread, /* OUT: Write the thread object here */
22200 void *(*xTask)(void*), /* Routine to run in a separate thread */
22201 void *pIn /* Argument passed into xTask() */
22203 SQLiteThread *p;
22205 assert( ppThread!=0 );
22206 assert( xTask!=0 );
22207 *ppThread = 0;
22208 p = sqlite3Malloc(sizeof(*p));
22209 if( p==0 ) return SQLITE_NOMEM;
22210 if( sqlite3GlobalConfig.bCoreMutex==0 ){
22211 memset(p, 0, sizeof(*p));
22212 }else{
22213 p->xTask = xTask;
22214 p->pIn = pIn;
22215 p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
22216 if( p->tid==0 ){
22217 memset(p, 0, sizeof(*p));
22220 if( p->xTask==0 ){
22221 p->id = GetCurrentThreadId();
22222 p->pResult = xTask(pIn);
22224 *ppThread = p;
22225 return SQLITE_OK;
22228 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
22230 /* Get the results of the thread */
22231 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
22232 DWORD rc;
22233 BOOL bRc;
22235 assert( ppOut!=0 );
22236 if( NEVER(p==0) ) return SQLITE_NOMEM;
22237 if( p->xTask==0 ){
22238 assert( p->id==GetCurrentThreadId() );
22239 rc = WAIT_OBJECT_0;
22240 assert( p->tid==0 );
22241 }else{
22242 assert( p->id!=0 && p->id!=GetCurrentThreadId() );
22243 rc = sqlite3Win32Wait((HANDLE)p->tid);
22244 assert( rc!=WAIT_IO_COMPLETION );
22245 bRc = CloseHandle((HANDLE)p->tid);
22246 assert( bRc );
22248 if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
22249 sqlite3_free(p);
22250 return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
22253 #endif /* SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT */
22254 /******************************** End Win32 Threads *************************/
22257 /********************************* Single-Threaded **************************/
22258 #ifndef SQLITE_THREADS_IMPLEMENTED
22260 ** This implementation does not actually create a new thread. It does the
22261 ** work of the thread in the main thread, when either the thread is created
22262 ** or when it is joined
22265 /* A running thread */
22266 struct SQLiteThread {
22267 void *(*xTask)(void*); /* The routine to run as a thread */
22268 void *pIn; /* Argument to xTask */
22269 void *pResult; /* Result of xTask */
22272 /* Create a new thread */
22273 SQLITE_PRIVATE int sqlite3ThreadCreate(
22274 SQLiteThread **ppThread, /* OUT: Write the thread object here */
22275 void *(*xTask)(void*), /* Routine to run in a separate thread */
22276 void *pIn /* Argument passed into xTask() */
22278 SQLiteThread *p;
22280 assert( ppThread!=0 );
22281 assert( xTask!=0 );
22282 *ppThread = 0;
22283 p = sqlite3Malloc(sizeof(*p));
22284 if( p==0 ) return SQLITE_NOMEM;
22285 if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
22286 p->xTask = xTask;
22287 p->pIn = pIn;
22288 }else{
22289 p->xTask = 0;
22290 p->pResult = xTask(pIn);
22292 *ppThread = p;
22293 return SQLITE_OK;
22296 /* Get the results of the thread */
22297 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
22299 assert( ppOut!=0 );
22300 if( NEVER(p==0) ) return SQLITE_NOMEM;
22301 if( p->xTask ){
22302 *ppOut = p->xTask(p->pIn);
22303 }else{
22304 *ppOut = p->pResult;
22306 sqlite3_free(p);
22308 #if defined(SQLITE_TEST)
22310 void *pTstAlloc = sqlite3Malloc(10);
22311 if (!pTstAlloc) return SQLITE_NOMEM;
22312 sqlite3_free(pTstAlloc);
22314 #endif
22316 return SQLITE_OK;
22319 #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
22320 /****************************** End Single-Threaded *************************/
22321 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
22323 /************** End of threads.c *********************************************/
22324 /************** Begin file utf.c *********************************************/
22326 ** 2004 April 13
22328 ** The author disclaims copyright to this source code. In place of
22329 ** a legal notice, here is a blessing:
22331 ** May you do good and not evil.
22332 ** May you find forgiveness for yourself and forgive others.
22333 ** May you share freely, never taking more than you give.
22335 *************************************************************************
22336 ** This file contains routines used to translate between UTF-8,
22337 ** UTF-16, UTF-16BE, and UTF-16LE.
22339 ** Notes on UTF-8:
22341 ** Byte-0 Byte-1 Byte-2 Byte-3 Value
22342 ** 0xxxxxxx 00000000 00000000 0xxxxxxx
22343 ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
22344 ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
22345 ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
22348 ** Notes on UTF-16: (with wwww+1==uuuuu)
22350 ** Word-0 Word-1 Value
22351 ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
22352 ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
22355 ** BOM or Byte Order Mark:
22356 ** 0xff 0xfe little-endian utf-16 follows
22357 ** 0xfe 0xff big-endian utf-16 follows
22360 /* #include <assert.h> */
22362 #ifndef SQLITE_AMALGAMATION
22364 ** The following constant value is used by the SQLITE_BIGENDIAN and
22365 ** SQLITE_LITTLEENDIAN macros.
22367 SQLITE_PRIVATE const int sqlite3one = 1;
22368 #endif /* SQLITE_AMALGAMATION */
22371 ** This lookup table is used to help decode the first byte of
22372 ** a multi-byte UTF8 character.
22374 static const unsigned char sqlite3Utf8Trans1[] = {
22375 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22376 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
22377 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
22378 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
22379 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22380 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
22381 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22382 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
22386 #define WRITE_UTF8(zOut, c) { \
22387 if( c<0x00080 ){ \
22388 *zOut++ = (u8)(c&0xFF); \
22390 else if( c<0x00800 ){ \
22391 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
22392 *zOut++ = 0x80 + (u8)(c & 0x3F); \
22394 else if( c<0x10000 ){ \
22395 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
22396 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
22397 *zOut++ = 0x80 + (u8)(c & 0x3F); \
22398 }else{ \
22399 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
22400 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
22401 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
22402 *zOut++ = 0x80 + (u8)(c & 0x3F); \
22406 #define WRITE_UTF16LE(zOut, c) { \
22407 if( c<=0xFFFF ){ \
22408 *zOut++ = (u8)(c&0x00FF); \
22409 *zOut++ = (u8)((c>>8)&0x00FF); \
22410 }else{ \
22411 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
22412 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
22413 *zOut++ = (u8)(c&0x00FF); \
22414 *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
22418 #define WRITE_UTF16BE(zOut, c) { \
22419 if( c<=0xFFFF ){ \
22420 *zOut++ = (u8)((c>>8)&0x00FF); \
22421 *zOut++ = (u8)(c&0x00FF); \
22422 }else{ \
22423 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
22424 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
22425 *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
22426 *zOut++ = (u8)(c&0x00FF); \
22430 #define READ_UTF16LE(zIn, TERM, c){ \
22431 c = (*zIn++); \
22432 c += ((*zIn++)<<8); \
22433 if( c>=0xD800 && c<0xE000 && TERM ){ \
22434 int c2 = (*zIn++); \
22435 c2 += ((*zIn++)<<8); \
22436 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
22440 #define READ_UTF16BE(zIn, TERM, c){ \
22441 c = ((*zIn++)<<8); \
22442 c += (*zIn++); \
22443 if( c>=0xD800 && c<0xE000 && TERM ){ \
22444 int c2 = ((*zIn++)<<8); \
22445 c2 += (*zIn++); \
22446 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
22451 ** Translate a single UTF-8 character. Return the unicode value.
22453 ** During translation, assume that the byte that zTerm points
22454 ** is a 0x00.
22456 ** Write a pointer to the next unread byte back into *pzNext.
22458 ** Notes On Invalid UTF-8:
22460 ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
22461 ** be encoded as a multi-byte character. Any multi-byte character that
22462 ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
22464 ** * This routine never allows a UTF16 surrogate value to be encoded.
22465 ** If a multi-byte character attempts to encode a value between
22466 ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
22468 ** * Bytes in the range of 0x80 through 0xbf which occur as the first
22469 ** byte of a character are interpreted as single-byte characters
22470 ** and rendered as themselves even though they are technically
22471 ** invalid characters.
22473 ** * This routine accepts over-length UTF8 encodings
22474 ** for unicode values 0x80 and greater. It does not change over-length
22475 ** encodings to 0xfffd as some systems recommend.
22477 #define READ_UTF8(zIn, zTerm, c) \
22478 c = *(zIn++); \
22479 if( c>=0xc0 ){ \
22480 c = sqlite3Utf8Trans1[c-0xc0]; \
22481 while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
22482 c = (c<<6) + (0x3f & *(zIn++)); \
22484 if( c<0x80 \
22485 || (c&0xFFFFF800)==0xD800 \
22486 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
22488 SQLITE_PRIVATE u32 sqlite3Utf8Read(
22489 const unsigned char **pz /* Pointer to string from which to read char */
22491 unsigned int c;
22493 /* Same as READ_UTF8() above but without the zTerm parameter.
22494 ** For this routine, we assume the UTF8 string is always zero-terminated.
22496 c = *((*pz)++);
22497 if( c>=0xc0 ){
22498 c = sqlite3Utf8Trans1[c-0xc0];
22499 while( (*(*pz) & 0xc0)==0x80 ){
22500 c = (c<<6) + (0x3f & *((*pz)++));
22502 if( c<0x80
22503 || (c&0xFFFFF800)==0xD800
22504 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
22506 return c;
22513 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
22514 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
22516 /* #define TRANSLATE_TRACE 1 */
22518 #ifndef SQLITE_OMIT_UTF16
22520 ** This routine transforms the internal text encoding used by pMem to
22521 ** desiredEnc. It is an error if the string is already of the desired
22522 ** encoding, or if *pMem does not contain a string value.
22524 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
22525 int len; /* Maximum length of output string in bytes */
22526 unsigned char *zOut; /* Output buffer */
22527 unsigned char *zIn; /* Input iterator */
22528 unsigned char *zTerm; /* End of input */
22529 unsigned char *z; /* Output iterator */
22530 unsigned int c;
22532 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
22533 assert( pMem->flags&MEM_Str );
22534 assert( pMem->enc!=desiredEnc );
22535 assert( pMem->enc!=0 );
22536 assert( pMem->n>=0 );
22538 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
22540 char zBuf[100];
22541 sqlite3VdbeMemPrettyPrint(pMem, zBuf);
22542 fprintf(stderr, "INPUT: %s\n", zBuf);
22544 #endif
22546 /* If the translation is between UTF-16 little and big endian, then
22547 ** all that is required is to swap the byte order. This case is handled
22548 ** differently from the others.
22550 if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
22551 u8 temp;
22552 int rc;
22553 rc = sqlite3VdbeMemMakeWriteable(pMem);
22554 if( rc!=SQLITE_OK ){
22555 assert( rc==SQLITE_NOMEM );
22556 return SQLITE_NOMEM;
22558 zIn = (u8*)pMem->z;
22559 zTerm = &zIn[pMem->n&~1];
22560 while( zIn<zTerm ){
22561 temp = *zIn;
22562 *zIn = *(zIn+1);
22563 zIn++;
22564 *zIn++ = temp;
22566 pMem->enc = desiredEnc;
22567 goto translate_out;
22570 /* Set len to the maximum number of bytes required in the output buffer. */
22571 if( desiredEnc==SQLITE_UTF8 ){
22572 /* When converting from UTF-16, the maximum growth results from
22573 ** translating a 2-byte character to a 4-byte UTF-8 character.
22574 ** A single byte is required for the output string
22575 ** nul-terminator.
22577 pMem->n &= ~1;
22578 len = pMem->n * 2 + 1;
22579 }else{
22580 /* When converting from UTF-8 to UTF-16 the maximum growth is caused
22581 ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
22582 ** character. Two bytes are required in the output buffer for the
22583 ** nul-terminator.
22585 len = pMem->n * 2 + 2;
22588 /* Set zIn to point at the start of the input buffer and zTerm to point 1
22589 ** byte past the end.
22591 ** Variable zOut is set to point at the output buffer, space obtained
22592 ** from sqlite3_malloc().
22594 zIn = (u8*)pMem->z;
22595 zTerm = &zIn[pMem->n];
22596 zOut = sqlite3DbMallocRaw(pMem->db, len);
22597 if( !zOut ){
22598 return SQLITE_NOMEM;
22600 z = zOut;
22602 if( pMem->enc==SQLITE_UTF8 ){
22603 if( desiredEnc==SQLITE_UTF16LE ){
22604 /* UTF-8 -> UTF-16 Little-endian */
22605 while( zIn<zTerm ){
22606 READ_UTF8(zIn, zTerm, c);
22607 WRITE_UTF16LE(z, c);
22609 }else{
22610 assert( desiredEnc==SQLITE_UTF16BE );
22611 /* UTF-8 -> UTF-16 Big-endian */
22612 while( zIn<zTerm ){
22613 READ_UTF8(zIn, zTerm, c);
22614 WRITE_UTF16BE(z, c);
22617 pMem->n = (int)(z - zOut);
22618 *z++ = 0;
22619 }else{
22620 assert( desiredEnc==SQLITE_UTF8 );
22621 if( pMem->enc==SQLITE_UTF16LE ){
22622 /* UTF-16 Little-endian -> UTF-8 */
22623 while( zIn<zTerm ){
22624 READ_UTF16LE(zIn, zIn<zTerm, c);
22625 WRITE_UTF8(z, c);
22627 }else{
22628 /* UTF-16 Big-endian -> UTF-8 */
22629 while( zIn<zTerm ){
22630 READ_UTF16BE(zIn, zIn<zTerm, c);
22631 WRITE_UTF8(z, c);
22634 pMem->n = (int)(z - zOut);
22636 *z = 0;
22637 assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
22639 c = pMem->flags;
22640 sqlite3VdbeMemRelease(pMem);
22641 pMem->flags = MEM_Str|MEM_Term|(c&MEM_AffMask);
22642 pMem->enc = desiredEnc;
22643 pMem->z = (char*)zOut;
22644 pMem->zMalloc = pMem->z;
22645 pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
22647 translate_out:
22648 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
22650 char zBuf[100];
22651 sqlite3VdbeMemPrettyPrint(pMem, zBuf);
22652 fprintf(stderr, "OUTPUT: %s\n", zBuf);
22654 #endif
22655 return SQLITE_OK;
22659 ** This routine checks for a byte-order mark at the beginning of the
22660 ** UTF-16 string stored in *pMem. If one is present, it is removed and
22661 ** the encoding of the Mem adjusted. This routine does not do any
22662 ** byte-swapping, it just sets Mem.enc appropriately.
22664 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
22665 ** changed by this function.
22667 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
22668 int rc = SQLITE_OK;
22669 u8 bom = 0;
22671 assert( pMem->n>=0 );
22672 if( pMem->n>1 ){
22673 u8 b1 = *(u8 *)pMem->z;
22674 u8 b2 = *(((u8 *)pMem->z) + 1);
22675 if( b1==0xFE && b2==0xFF ){
22676 bom = SQLITE_UTF16BE;
22678 if( b1==0xFF && b2==0xFE ){
22679 bom = SQLITE_UTF16LE;
22683 if( bom ){
22684 rc = sqlite3VdbeMemMakeWriteable(pMem);
22685 if( rc==SQLITE_OK ){
22686 pMem->n -= 2;
22687 memmove(pMem->z, &pMem->z[2], pMem->n);
22688 pMem->z[pMem->n] = '\0';
22689 pMem->z[pMem->n+1] = '\0';
22690 pMem->flags |= MEM_Term;
22691 pMem->enc = bom;
22694 return rc;
22696 #endif /* SQLITE_OMIT_UTF16 */
22699 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
22700 ** return the number of unicode characters in pZ up to (but not including)
22701 ** the first 0x00 byte. If nByte is not less than zero, return the
22702 ** number of unicode characters in the first nByte of pZ (or up to
22703 ** the first 0x00, whichever comes first).
22705 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
22706 int r = 0;
22707 const u8 *z = (const u8*)zIn;
22708 const u8 *zTerm;
22709 if( nByte>=0 ){
22710 zTerm = &z[nByte];
22711 }else{
22712 zTerm = (const u8*)(-1);
22714 assert( z<=zTerm );
22715 while( *z!=0 && z<zTerm ){
22716 SQLITE_SKIP_UTF8(z);
22717 r++;
22719 return r;
22722 /* This test function is not currently used by the automated test-suite.
22723 ** Hence it is only available in debug builds.
22725 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
22727 ** Translate UTF-8 to UTF-8.
22729 ** This has the effect of making sure that the string is well-formed
22730 ** UTF-8. Miscoded characters are removed.
22732 ** The translation is done in-place and aborted if the output
22733 ** overruns the input.
22735 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
22736 unsigned char *zOut = zIn;
22737 unsigned char *zStart = zIn;
22738 u32 c;
22740 while( zIn[0] && zOut<=zIn ){
22741 c = sqlite3Utf8Read((const u8**)&zIn);
22742 if( c!=0xfffd ){
22743 WRITE_UTF8(zOut, c);
22746 *zOut = 0;
22747 return (int)(zOut - zStart);
22749 #endif
22751 #ifndef SQLITE_OMIT_UTF16
22753 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
22754 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
22755 ** be freed by the calling function.
22757 ** NULL is returned if there is an allocation error.
22759 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
22760 Mem m;
22761 memset(&m, 0, sizeof(m));
22762 m.db = db;
22763 sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
22764 sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
22765 if( db->mallocFailed ){
22766 sqlite3VdbeMemRelease(&m);
22767 m.z = 0;
22769 assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
22770 assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
22771 assert( m.z || db->mallocFailed );
22772 return m.z;
22776 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
22777 ** Return the number of bytes in the first nChar unicode characters
22778 ** in pZ. nChar must be non-negative.
22780 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
22781 int c;
22782 unsigned char const *z = zIn;
22783 int n = 0;
22785 if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
22786 while( n<nChar ){
22787 READ_UTF16BE(z, 1, c);
22788 n++;
22790 }else{
22791 while( n<nChar ){
22792 READ_UTF16LE(z, 1, c);
22793 n++;
22796 return (int)(z-(unsigned char const *)zIn);
22799 #if defined(SQLITE_TEST)
22801 ** This routine is called from the TCL test function "translate_selftest".
22802 ** It checks that the primitives for serializing and deserializing
22803 ** characters in each encoding are inverses of each other.
22805 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
22806 unsigned int i, t;
22807 unsigned char zBuf[20];
22808 unsigned char *z;
22809 int n;
22810 unsigned int c;
22812 for(i=0; i<0x00110000; i++){
22813 z = zBuf;
22814 WRITE_UTF8(z, i);
22815 n = (int)(z-zBuf);
22816 assert( n>0 && n<=4 );
22817 z[0] = 0;
22818 z = zBuf;
22819 c = sqlite3Utf8Read((const u8**)&z);
22820 t = i;
22821 if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
22822 if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
22823 assert( c==t );
22824 assert( (z-zBuf)==n );
22826 for(i=0; i<0x00110000; i++){
22827 if( i>=0xD800 && i<0xE000 ) continue;
22828 z = zBuf;
22829 WRITE_UTF16LE(z, i);
22830 n = (int)(z-zBuf);
22831 assert( n>0 && n<=4 );
22832 z[0] = 0;
22833 z = zBuf;
22834 READ_UTF16LE(z, 1, c);
22835 assert( c==i );
22836 assert( (z-zBuf)==n );
22838 for(i=0; i<0x00110000; i++){
22839 if( i>=0xD800 && i<0xE000 ) continue;
22840 z = zBuf;
22841 WRITE_UTF16BE(z, i);
22842 n = (int)(z-zBuf);
22843 assert( n>0 && n<=4 );
22844 z[0] = 0;
22845 z = zBuf;
22846 READ_UTF16BE(z, 1, c);
22847 assert( c==i );
22848 assert( (z-zBuf)==n );
22851 #endif /* SQLITE_TEST */
22852 #endif /* SQLITE_OMIT_UTF16 */
22854 /************** End of utf.c *************************************************/
22855 /************** Begin file util.c ********************************************/
22857 ** 2001 September 15
22859 ** The author disclaims copyright to this source code. In place of
22860 ** a legal notice, here is a blessing:
22862 ** May you do good and not evil.
22863 ** May you find forgiveness for yourself and forgive others.
22864 ** May you share freely, never taking more than you give.
22866 *************************************************************************
22867 ** Utility functions used throughout sqlite.
22869 ** This file contains functions for allocating memory, comparing
22870 ** strings, and stuff like that.
22873 /* #include <stdarg.h> */
22874 #ifdef SQLITE_HAVE_ISNAN
22875 # include <math.h>
22876 #endif
22879 ** Routine needed to support the testcase() macro.
22881 #ifdef SQLITE_COVERAGE_TEST
22882 SQLITE_PRIVATE void sqlite3Coverage(int x){
22883 static unsigned dummy = 0;
22884 dummy += (unsigned)x;
22886 #endif
22889 ** Give a callback to the test harness that can be used to simulate faults
22890 ** in places where it is difficult or expensive to do so purely by means
22891 ** of inputs.
22893 ** The intent of the integer argument is to let the fault simulator know
22894 ** which of multiple sqlite3FaultSim() calls has been hit.
22896 ** Return whatever integer value the test callback returns, or return
22897 ** SQLITE_OK if no test callback is installed.
22899 #ifndef SQLITE_OMIT_BUILTIN_TEST
22900 SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
22901 int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
22902 return xCallback ? xCallback(iTest) : SQLITE_OK;
22904 #endif
22906 #ifndef SQLITE_OMIT_FLOATING_POINT
22908 ** Return true if the floating point value is Not a Number (NaN).
22910 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
22911 ** Otherwise, we have our own implementation that works on most systems.
22913 SQLITE_PRIVATE int sqlite3IsNaN(double x){
22914 int rc; /* The value return */
22915 #if !defined(SQLITE_HAVE_ISNAN)
22917 ** Systems that support the isnan() library function should probably
22918 ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
22919 ** found that many systems do not have a working isnan() function so
22920 ** this implementation is provided as an alternative.
22922 ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
22923 ** On the other hand, the use of -ffast-math comes with the following
22924 ** warning:
22926 ** This option [-ffast-math] should never be turned on by any
22927 ** -O option since it can result in incorrect output for programs
22928 ** which depend on an exact implementation of IEEE or ISO
22929 ** rules/specifications for math functions.
22931 ** Under MSVC, this NaN test may fail if compiled with a floating-
22932 ** point precision mode other than /fp:precise. From the MSDN
22933 ** documentation:
22935 ** The compiler [with /fp:precise] will properly handle comparisons
22936 ** involving NaN. For example, x != x evaluates to true if x is NaN
22937 ** ...
22939 #ifdef __FAST_MATH__
22940 # error SQLite will not work correctly with the -ffast-math option of GCC.
22941 #endif
22942 volatile double y = x;
22943 volatile double z = y;
22944 rc = (y!=z);
22945 #else /* if defined(SQLITE_HAVE_ISNAN) */
22946 rc = isnan(x);
22947 #endif /* SQLITE_HAVE_ISNAN */
22948 testcase( rc );
22949 return rc;
22951 #endif /* SQLITE_OMIT_FLOATING_POINT */
22954 ** Compute a string length that is limited to what can be stored in
22955 ** lower 30 bits of a 32-bit signed integer.
22957 ** The value returned will never be negative. Nor will it ever be greater
22958 ** than the actual length of the string. For very long strings (greater
22959 ** than 1GiB) the value returned might be less than the true string length.
22961 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
22962 const char *z2 = z;
22963 if( z==0 ) return 0;
22964 while( *z2 ){ z2++; }
22965 return 0x3fffffff & (int)(z2 - z);
22969 ** Set the current error code to err_code and clear any prior error message.
22971 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
22972 assert( db!=0 );
22973 db->errCode = err_code;
22974 if( db->pErr ) sqlite3ValueSetNull(db->pErr);
22978 ** Set the most recent error code and error string for the sqlite
22979 ** handle "db". The error code is set to "err_code".
22981 ** If it is not NULL, string zFormat specifies the format of the
22982 ** error string in the style of the printf functions: The following
22983 ** format characters are allowed:
22985 ** %s Insert a string
22986 ** %z A string that should be freed after use
22987 ** %d Insert an integer
22988 ** %T Insert a token
22989 ** %S Insert the first element of a SrcList
22991 ** zFormat and any string tokens that follow it are assumed to be
22992 ** encoded in UTF-8.
22994 ** To clear the most recent error for sqlite handle "db", sqlite3Error
22995 ** should be called with err_code set to SQLITE_OK and zFormat set
22996 ** to NULL.
22998 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
22999 assert( db!=0 );
23000 db->errCode = err_code;
23001 if( zFormat==0 ){
23002 sqlite3Error(db, err_code);
23003 }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
23004 char *z;
23005 va_list ap;
23006 va_start(ap, zFormat);
23007 z = sqlite3VMPrintf(db, zFormat, ap);
23008 va_end(ap);
23009 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
23014 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
23015 ** The following formatting characters are allowed:
23017 ** %s Insert a string
23018 ** %z A string that should be freed after use
23019 ** %d Insert an integer
23020 ** %T Insert a token
23021 ** %S Insert the first element of a SrcList
23023 ** This function should be used to report any error that occurs while
23024 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
23025 ** last thing the sqlite3_prepare() function does is copy the error
23026 ** stored by this function into the database handle using sqlite3Error().
23027 ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
23028 ** during statement execution (sqlite3_step() etc.).
23030 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
23031 char *zMsg;
23032 va_list ap;
23033 sqlite3 *db = pParse->db;
23034 va_start(ap, zFormat);
23035 zMsg = sqlite3VMPrintf(db, zFormat, ap);
23036 va_end(ap);
23037 if( db->suppressErr ){
23038 sqlite3DbFree(db, zMsg);
23039 }else{
23040 pParse->nErr++;
23041 sqlite3DbFree(db, pParse->zErrMsg);
23042 pParse->zErrMsg = zMsg;
23043 pParse->rc = SQLITE_ERROR;
23048 ** Convert an SQL-style quoted string into a normal string by removing
23049 ** the quote characters. The conversion is done in-place. If the
23050 ** input does not begin with a quote character, then this routine
23051 ** is a no-op.
23053 ** The input string must be zero-terminated. A new zero-terminator
23054 ** is added to the dequoted string.
23056 ** The return value is -1 if no dequoting occurs or the length of the
23057 ** dequoted string, exclusive of the zero terminator, if dequoting does
23058 ** occur.
23060 ** 2002-Feb-14: This routine is extended to remove MS-Access style
23061 ** brackets from around identifiers. For example: "[a-b-c]" becomes
23062 ** "a-b-c".
23064 SQLITE_PRIVATE int sqlite3Dequote(char *z){
23065 char quote;
23066 int i, j;
23067 if( z==0 ) return -1;
23068 quote = z[0];
23069 switch( quote ){
23070 case '\'': break;
23071 case '"': break;
23072 case '`': break; /* For MySQL compatibility */
23073 case '[': quote = ']'; break; /* For MS SqlServer compatibility */
23074 default: return -1;
23076 for(i=1, j=0;; i++){
23077 assert( z[i] );
23078 if( z[i]==quote ){
23079 if( z[i+1]==quote ){
23080 z[j++] = quote;
23081 i++;
23082 }else{
23083 break;
23085 }else{
23086 z[j++] = z[i];
23089 z[j] = 0;
23090 return j;
23093 /* Convenient short-hand */
23094 #define UpperToLower sqlite3UpperToLower
23097 ** Some systems have stricmp(). Others have strcasecmp(). Because
23098 ** there is no consistency, we will define our own.
23100 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
23101 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
23102 ** the contents of two buffers containing UTF-8 strings in a
23103 ** case-independent fashion, using the same definition of "case
23104 ** independence" that SQLite uses internally when comparing identifiers.
23106 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
23107 register unsigned char *a, *b;
23108 a = (unsigned char *)zLeft;
23109 b = (unsigned char *)zRight;
23110 while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
23111 return UpperToLower[*a] - UpperToLower[*b];
23113 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
23114 register unsigned char *a, *b;
23115 a = (unsigned char *)zLeft;
23116 b = (unsigned char *)zRight;
23117 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
23118 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
23122 ** The string z[] is an text representation of a real number.
23123 ** Convert this string to a double and write it into *pResult.
23125 ** The string z[] is length bytes in length (bytes, not characters) and
23126 ** uses the encoding enc. The string is not necessarily zero-terminated.
23128 ** Return TRUE if the result is a valid real number (or integer) and FALSE
23129 ** if the string is empty or contains extraneous text. Valid numbers
23130 ** are in one of these formats:
23132 ** [+-]digits[E[+-]digits]
23133 ** [+-]digits.[digits][E[+-]digits]
23134 ** [+-].digits[E[+-]digits]
23136 ** Leading and trailing whitespace is ignored for the purpose of determining
23137 ** validity.
23139 ** If some prefix of the input string is a valid number, this routine
23140 ** returns FALSE but it still converts the prefix and writes the result
23141 ** into *pResult.
23143 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
23144 #ifndef SQLITE_OMIT_FLOATING_POINT
23145 int incr;
23146 const char *zEnd = z + length;
23147 /* sign * significand * (10 ^ (esign * exponent)) */
23148 int sign = 1; /* sign of significand */
23149 i64 s = 0; /* significand */
23150 int d = 0; /* adjust exponent for shifting decimal point */
23151 int esign = 1; /* sign of exponent */
23152 int e = 0; /* exponent */
23153 int eValid = 1; /* True exponent is either not used or is well-formed */
23154 double result;
23155 int nDigits = 0;
23156 int nonNum = 0;
23158 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
23159 *pResult = 0.0; /* Default return value, in case of an error */
23161 if( enc==SQLITE_UTF8 ){
23162 incr = 1;
23163 }else{
23164 int i;
23165 incr = 2;
23166 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
23167 for(i=3-enc; i<length && z[i]==0; i+=2){}
23168 nonNum = i<length;
23169 zEnd = z+i+enc-3;
23170 z += (enc&1);
23173 /* skip leading spaces */
23174 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
23175 if( z>=zEnd ) return 0;
23177 /* get sign of significand */
23178 if( *z=='-' ){
23179 sign = -1;
23180 z+=incr;
23181 }else if( *z=='+' ){
23182 z+=incr;
23185 /* skip leading zeroes */
23186 while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
23188 /* copy max significant digits to significand */
23189 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
23190 s = s*10 + (*z - '0');
23191 z+=incr, nDigits++;
23194 /* skip non-significant significand digits
23195 ** (increase exponent by d to shift decimal left) */
23196 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
23197 if( z>=zEnd ) goto do_atof_calc;
23199 /* if decimal point is present */
23200 if( *z=='.' ){
23201 z+=incr;
23202 /* copy digits from after decimal to significand
23203 ** (decrease exponent by d to shift decimal right) */
23204 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
23205 s = s*10 + (*z - '0');
23206 z+=incr, nDigits++, d--;
23208 /* skip non-significant digits */
23209 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
23211 if( z>=zEnd ) goto do_atof_calc;
23213 /* if exponent is present */
23214 if( *z=='e' || *z=='E' ){
23215 z+=incr;
23216 eValid = 0;
23217 if( z>=zEnd ) goto do_atof_calc;
23218 /* get sign of exponent */
23219 if( *z=='-' ){
23220 esign = -1;
23221 z+=incr;
23222 }else if( *z=='+' ){
23223 z+=incr;
23225 /* copy digits to exponent */
23226 while( z<zEnd && sqlite3Isdigit(*z) ){
23227 e = e<10000 ? (e*10 + (*z - '0')) : 10000;
23228 z+=incr;
23229 eValid = 1;
23233 /* skip trailing spaces */
23234 if( nDigits && eValid ){
23235 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
23238 do_atof_calc:
23239 /* adjust exponent by d, and update sign */
23240 e = (e*esign) + d;
23241 if( e<0 ) {
23242 esign = -1;
23243 e *= -1;
23244 } else {
23245 esign = 1;
23248 /* if 0 significand */
23249 if( !s ) {
23250 /* In the IEEE 754 standard, zero is signed.
23251 ** Add the sign if we've seen at least one digit */
23252 result = (sign<0 && nDigits) ? -(double)0 : (double)0;
23253 } else {
23254 /* attempt to reduce exponent */
23255 if( esign>0 ){
23256 while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
23257 }else{
23258 while( !(s%10) && e>0 ) e--,s/=10;
23261 /* adjust the sign of significand */
23262 s = sign<0 ? -s : s;
23264 /* if exponent, scale significand as appropriate
23265 ** and store in result. */
23266 if( e ){
23267 LONGDOUBLE_TYPE scale = 1.0;
23268 /* attempt to handle extremely small/large numbers better */
23269 if( e>307 && e<342 ){
23270 while( e%308 ) { scale *= 1.0e+1; e -= 1; }
23271 if( esign<0 ){
23272 result = s / scale;
23273 result /= 1.0e+308;
23274 }else{
23275 result = s * scale;
23276 result *= 1.0e+308;
23278 }else if( e>=342 ){
23279 if( esign<0 ){
23280 result = 0.0*s;
23281 }else{
23282 result = 1e308*1e308*s; /* Infinity */
23284 }else{
23285 /* 1.0e+22 is the largest power of 10 than can be
23286 ** represented exactly. */
23287 while( e%22 ) { scale *= 1.0e+1; e -= 1; }
23288 while( e>0 ) { scale *= 1.0e+22; e -= 22; }
23289 if( esign<0 ){
23290 result = s / scale;
23291 }else{
23292 result = s * scale;
23295 } else {
23296 result = (double)s;
23300 /* store the result */
23301 *pResult = result;
23303 /* return true if number and no extra non-whitespace chracters after */
23304 return z>=zEnd && nDigits>0 && eValid && nonNum==0;
23305 #else
23306 return !sqlite3Atoi64(z, pResult, length, enc);
23307 #endif /* SQLITE_OMIT_FLOATING_POINT */
23311 ** Compare the 19-character string zNum against the text representation
23312 ** value 2^63: 9223372036854775808. Return negative, zero, or positive
23313 ** if zNum is less than, equal to, or greater than the string.
23314 ** Note that zNum must contain exactly 19 characters.
23316 ** Unlike memcmp() this routine is guaranteed to return the difference
23317 ** in the values of the last digit if the only difference is in the
23318 ** last digit. So, for example,
23320 ** compare2pow63("9223372036854775800", 1)
23322 ** will return -8.
23324 static int compare2pow63(const char *zNum, int incr){
23325 int c = 0;
23326 int i;
23327 /* 012345678901234567 */
23328 const char *pow63 = "922337203685477580";
23329 for(i=0; c==0 && i<18; i++){
23330 c = (zNum[i*incr]-pow63[i])*10;
23332 if( c==0 ){
23333 c = zNum[18*incr] - '8';
23334 testcase( c==(-1) );
23335 testcase( c==0 );
23336 testcase( c==(+1) );
23338 return c;
23342 ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
23343 ** routine does *not* accept hexadecimal notation.
23345 ** If the zNum value is representable as a 64-bit twos-complement
23346 ** integer, then write that value into *pNum and return 0.
23348 ** If zNum is exactly 9223372036854775808, return 2. This special
23349 ** case is broken out because while 9223372036854775808 cannot be a
23350 ** signed 64-bit integer, its negative -9223372036854775808 can be.
23352 ** If zNum is too big for a 64-bit integer and is not
23353 ** 9223372036854775808 or if zNum contains any non-numeric text,
23354 ** then return 1.
23356 ** length is the number of bytes in the string (bytes, not characters).
23357 ** The string is not necessarily zero-terminated. The encoding is
23358 ** given by enc.
23360 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
23361 int incr;
23362 u64 u = 0;
23363 int neg = 0; /* assume positive */
23364 int i;
23365 int c = 0;
23366 int nonNum = 0;
23367 const char *zStart;
23368 const char *zEnd = zNum + length;
23369 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
23370 if( enc==SQLITE_UTF8 ){
23371 incr = 1;
23372 }else{
23373 incr = 2;
23374 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
23375 for(i=3-enc; i<length && zNum[i]==0; i+=2){}
23376 nonNum = i<length;
23377 zEnd = zNum+i+enc-3;
23378 zNum += (enc&1);
23380 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
23381 if( zNum<zEnd ){
23382 if( *zNum=='-' ){
23383 neg = 1;
23384 zNum+=incr;
23385 }else if( *zNum=='+' ){
23386 zNum+=incr;
23389 zStart = zNum;
23390 while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
23391 for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
23392 u = u*10 + c - '0';
23394 if( u>LARGEST_INT64 ){
23395 *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
23396 }else if( neg ){
23397 *pNum = -(i64)u;
23398 }else{
23399 *pNum = (i64)u;
23401 testcase( i==18 );
23402 testcase( i==19 );
23403 testcase( i==20 );
23404 if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
23405 /* zNum is empty or contains non-numeric text or is longer
23406 ** than 19 digits (thus guaranteeing that it is too large) */
23407 return 1;
23408 }else if( i<19*incr ){
23409 /* Less than 19 digits, so we know that it fits in 64 bits */
23410 assert( u<=LARGEST_INT64 );
23411 return 0;
23412 }else{
23413 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
23414 c = compare2pow63(zNum, incr);
23415 if( c<0 ){
23416 /* zNum is less than 9223372036854775808 so it fits */
23417 assert( u<=LARGEST_INT64 );
23418 return 0;
23419 }else if( c>0 ){
23420 /* zNum is greater than 9223372036854775808 so it overflows */
23421 return 1;
23422 }else{
23423 /* zNum is exactly 9223372036854775808. Fits if negative. The
23424 ** special case 2 overflow if positive */
23425 assert( u-1==LARGEST_INT64 );
23426 return neg ? 0 : 2;
23432 ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
23433 ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
23434 ** whereas sqlite3Atoi64() does not.
23436 ** Returns:
23438 ** 0 Successful transformation. Fits in a 64-bit signed integer.
23439 ** 1 Integer too large for a 64-bit signed integer or is malformed
23440 ** 2 Special case of 9223372036854775808
23442 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
23443 #ifndef SQLITE_OMIT_HEX_INTEGER
23444 if( z[0]=='0'
23445 && (z[1]=='x' || z[1]=='X')
23446 && sqlite3Isxdigit(z[2])
23448 u64 u = 0;
23449 int i, k;
23450 for(i=2; z[i]=='0'; i++){}
23451 for(k=i; sqlite3Isxdigit(z[k]); k++){
23452 u = u*16 + sqlite3HexToInt(z[k]);
23454 memcpy(pOut, &u, 8);
23455 return (z[k]==0 && k-i<=16) ? 0 : 1;
23456 }else
23457 #endif /* SQLITE_OMIT_HEX_INTEGER */
23459 return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
23464 ** If zNum represents an integer that will fit in 32-bits, then set
23465 ** *pValue to that integer and return true. Otherwise return false.
23467 ** This routine accepts both decimal and hexadecimal notation for integers.
23469 ** Any non-numeric characters that following zNum are ignored.
23470 ** This is different from sqlite3Atoi64() which requires the
23471 ** input number to be zero-terminated.
23473 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
23474 sqlite_int64 v = 0;
23475 int i, c;
23476 int neg = 0;
23477 if( zNum[0]=='-' ){
23478 neg = 1;
23479 zNum++;
23480 }else if( zNum[0]=='+' ){
23481 zNum++;
23483 #ifndef SQLITE_OMIT_HEX_INTEGER
23484 else if( zNum[0]=='0'
23485 && (zNum[1]=='x' || zNum[1]=='X')
23486 && sqlite3Isxdigit(zNum[2])
23488 u32 u = 0;
23489 zNum += 2;
23490 while( zNum[0]=='0' ) zNum++;
23491 for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
23492 u = u*16 + sqlite3HexToInt(zNum[i]);
23494 if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
23495 memcpy(pValue, &u, 4);
23496 return 1;
23497 }else{
23498 return 0;
23501 #endif
23502 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
23503 v = v*10 + c;
23506 /* The longest decimal representation of a 32 bit integer is 10 digits:
23508 ** 1234567890
23509 ** 2^31 -> 2147483648
23511 testcase( i==10 );
23512 if( i>10 ){
23513 return 0;
23515 testcase( v-neg==2147483647 );
23516 if( v-neg>2147483647 ){
23517 return 0;
23519 if( neg ){
23520 v = -v;
23522 *pValue = (int)v;
23523 return 1;
23527 ** Return a 32-bit integer value extracted from a string. If the
23528 ** string is not an integer, just return 0.
23530 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
23531 int x = 0;
23532 if( z ) sqlite3GetInt32(z, &x);
23533 return x;
23537 ** The variable-length integer encoding is as follows:
23539 ** KEY:
23540 ** A = 0xxxxxxx 7 bits of data and one flag bit
23541 ** B = 1xxxxxxx 7 bits of data and one flag bit
23542 ** C = xxxxxxxx 8 bits of data
23544 ** 7 bits - A
23545 ** 14 bits - BA
23546 ** 21 bits - BBA
23547 ** 28 bits - BBBA
23548 ** 35 bits - BBBBA
23549 ** 42 bits - BBBBBA
23550 ** 49 bits - BBBBBBA
23551 ** 56 bits - BBBBBBBA
23552 ** 64 bits - BBBBBBBBC
23556 ** Write a 64-bit variable-length integer to memory starting at p[0].
23557 ** The length of data write will be between 1 and 9 bytes. The number
23558 ** of bytes written is returned.
23560 ** A variable-length integer consists of the lower 7 bits of each byte
23561 ** for all bytes that have the 8th bit set and one byte with the 8th
23562 ** bit clear. Except, if we get to the 9th byte, it stores the full
23563 ** 8 bits and is the last byte.
23565 static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
23566 int i, j, n;
23567 u8 buf[10];
23568 if( v & (((u64)0xff000000)<<32) ){
23569 p[8] = (u8)v;
23570 v >>= 8;
23571 for(i=7; i>=0; i--){
23572 p[i] = (u8)((v & 0x7f) | 0x80);
23573 v >>= 7;
23575 return 9;
23577 n = 0;
23579 buf[n++] = (u8)((v & 0x7f) | 0x80);
23580 v >>= 7;
23581 }while( v!=0 );
23582 buf[0] &= 0x7f;
23583 assert( n<=9 );
23584 for(i=0, j=n-1; j>=0; j--, i++){
23585 p[i] = buf[j];
23587 return n;
23589 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
23590 if( v<=0x7f ){
23591 p[0] = v&0x7f;
23592 return 1;
23594 if( v<=0x3fff ){
23595 p[0] = ((v>>7)&0x7f)|0x80;
23596 p[1] = v&0x7f;
23597 return 2;
23599 return putVarint64(p,v);
23603 ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
23604 ** are defined here rather than simply putting the constant expressions
23605 ** inline in order to work around bugs in the RVT compiler.
23607 ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
23609 ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
23611 #define SLOT_2_0 0x001fc07f
23612 #define SLOT_4_2_0 0xf01fc07f
23616 ** Read a 64-bit variable-length integer from memory starting at p[0].
23617 ** Return the number of bytes read. The value is stored in *v.
23619 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
23620 u32 a,b,s;
23622 a = *p;
23623 /* a: p0 (unmasked) */
23624 if (!(a&0x80))
23626 *v = a;
23627 return 1;
23630 p++;
23631 b = *p;
23632 /* b: p1 (unmasked) */
23633 if (!(b&0x80))
23635 a &= 0x7f;
23636 a = a<<7;
23637 a |= b;
23638 *v = a;
23639 return 2;
23642 /* Verify that constants are precomputed correctly */
23643 assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
23644 assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
23646 p++;
23647 a = a<<14;
23648 a |= *p;
23649 /* a: p0<<14 | p2 (unmasked) */
23650 if (!(a&0x80))
23652 a &= SLOT_2_0;
23653 b &= 0x7f;
23654 b = b<<7;
23655 a |= b;
23656 *v = a;
23657 return 3;
23660 /* CSE1 from below */
23661 a &= SLOT_2_0;
23662 p++;
23663 b = b<<14;
23664 b |= *p;
23665 /* b: p1<<14 | p3 (unmasked) */
23666 if (!(b&0x80))
23668 b &= SLOT_2_0;
23669 /* moved CSE1 up */
23670 /* a &= (0x7f<<14)|(0x7f); */
23671 a = a<<7;
23672 a |= b;
23673 *v = a;
23674 return 4;
23677 /* a: p0<<14 | p2 (masked) */
23678 /* b: p1<<14 | p3 (unmasked) */
23679 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
23680 /* moved CSE1 up */
23681 /* a &= (0x7f<<14)|(0x7f); */
23682 b &= SLOT_2_0;
23683 s = a;
23684 /* s: p0<<14 | p2 (masked) */
23686 p++;
23687 a = a<<14;
23688 a |= *p;
23689 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
23690 if (!(a&0x80))
23692 /* we can skip these cause they were (effectively) done above in calc'ing s */
23693 /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
23694 /* b &= (0x7f<<14)|(0x7f); */
23695 b = b<<7;
23696 a |= b;
23697 s = s>>18;
23698 *v = ((u64)s)<<32 | a;
23699 return 5;
23702 /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
23703 s = s<<7;
23704 s |= b;
23705 /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
23707 p++;
23708 b = b<<14;
23709 b |= *p;
23710 /* b: p1<<28 | p3<<14 | p5 (unmasked) */
23711 if (!(b&0x80))
23713 /* we can skip this cause it was (effectively) done above in calc'ing s */
23714 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
23715 a &= SLOT_2_0;
23716 a = a<<7;
23717 a |= b;
23718 s = s>>18;
23719 *v = ((u64)s)<<32 | a;
23720 return 6;
23723 p++;
23724 a = a<<14;
23725 a |= *p;
23726 /* a: p2<<28 | p4<<14 | p6 (unmasked) */
23727 if (!(a&0x80))
23729 a &= SLOT_4_2_0;
23730 b &= SLOT_2_0;
23731 b = b<<7;
23732 a |= b;
23733 s = s>>11;
23734 *v = ((u64)s)<<32 | a;
23735 return 7;
23738 /* CSE2 from below */
23739 a &= SLOT_2_0;
23740 p++;
23741 b = b<<14;
23742 b |= *p;
23743 /* b: p3<<28 | p5<<14 | p7 (unmasked) */
23744 if (!(b&0x80))
23746 b &= SLOT_4_2_0;
23747 /* moved CSE2 up */
23748 /* a &= (0x7f<<14)|(0x7f); */
23749 a = a<<7;
23750 a |= b;
23751 s = s>>4;
23752 *v = ((u64)s)<<32 | a;
23753 return 8;
23756 p++;
23757 a = a<<15;
23758 a |= *p;
23759 /* a: p4<<29 | p6<<15 | p8 (unmasked) */
23761 /* moved CSE2 up */
23762 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
23763 b &= SLOT_2_0;
23764 b = b<<8;
23765 a |= b;
23767 s = s<<4;
23768 b = p[-4];
23769 b &= 0x7f;
23770 b = b>>3;
23771 s |= b;
23773 *v = ((u64)s)<<32 | a;
23775 return 9;
23779 ** Read a 32-bit variable-length integer from memory starting at p[0].
23780 ** Return the number of bytes read. The value is stored in *v.
23782 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
23783 ** integer, then set *v to 0xffffffff.
23785 ** A MACRO version, getVarint32, is provided which inlines the
23786 ** single-byte case. All code should use the MACRO version as
23787 ** this function assumes the single-byte case has already been handled.
23789 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
23790 u32 a,b;
23792 /* The 1-byte case. Overwhelmingly the most common. Handled inline
23793 ** by the getVarin32() macro */
23794 a = *p;
23795 /* a: p0 (unmasked) */
23796 #ifndef getVarint32
23797 if (!(a&0x80))
23799 /* Values between 0 and 127 */
23800 *v = a;
23801 return 1;
23803 #endif
23805 /* The 2-byte case */
23806 p++;
23807 b = *p;
23808 /* b: p1 (unmasked) */
23809 if (!(b&0x80))
23811 /* Values between 128 and 16383 */
23812 a &= 0x7f;
23813 a = a<<7;
23814 *v = a | b;
23815 return 2;
23818 /* The 3-byte case */
23819 p++;
23820 a = a<<14;
23821 a |= *p;
23822 /* a: p0<<14 | p2 (unmasked) */
23823 if (!(a&0x80))
23825 /* Values between 16384 and 2097151 */
23826 a &= (0x7f<<14)|(0x7f);
23827 b &= 0x7f;
23828 b = b<<7;
23829 *v = a | b;
23830 return 3;
23833 /* A 32-bit varint is used to store size information in btrees.
23834 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
23835 ** A 3-byte varint is sufficient, for example, to record the size
23836 ** of a 1048569-byte BLOB or string.
23838 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
23839 ** rare larger cases can be handled by the slower 64-bit varint
23840 ** routine.
23842 #if 1
23844 u64 v64;
23845 u8 n;
23847 p -= 2;
23848 n = sqlite3GetVarint(p, &v64);
23849 assert( n>3 && n<=9 );
23850 if( (v64 & SQLITE_MAX_U32)!=v64 ){
23851 *v = 0xffffffff;
23852 }else{
23853 *v = (u32)v64;
23855 return n;
23858 #else
23859 /* For following code (kept for historical record only) shows an
23860 ** unrolling for the 3- and 4-byte varint cases. This code is
23861 ** slightly faster, but it is also larger and much harder to test.
23863 p++;
23864 b = b<<14;
23865 b |= *p;
23866 /* b: p1<<14 | p3 (unmasked) */
23867 if (!(b&0x80))
23869 /* Values between 2097152 and 268435455 */
23870 b &= (0x7f<<14)|(0x7f);
23871 a &= (0x7f<<14)|(0x7f);
23872 a = a<<7;
23873 *v = a | b;
23874 return 4;
23877 p++;
23878 a = a<<14;
23879 a |= *p;
23880 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
23881 if (!(a&0x80))
23883 /* Values between 268435456 and 34359738367 */
23884 a &= SLOT_4_2_0;
23885 b &= SLOT_4_2_0;
23886 b = b<<7;
23887 *v = a | b;
23888 return 5;
23891 /* We can only reach this point when reading a corrupt database
23892 ** file. In that case we are not in any hurry. Use the (relatively
23893 ** slow) general-purpose sqlite3GetVarint() routine to extract the
23894 ** value. */
23896 u64 v64;
23897 u8 n;
23899 p -= 4;
23900 n = sqlite3GetVarint(p, &v64);
23901 assert( n>5 && n<=9 );
23902 *v = (u32)v64;
23903 return n;
23905 #endif
23909 ** Return the number of bytes that will be needed to store the given
23910 ** 64-bit integer.
23912 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
23913 int i = 0;
23915 i++;
23916 v >>= 7;
23917 }while( v!=0 && ALWAYS(i<9) );
23918 return i;
23923 ** Read or write a four-byte big-endian integer value.
23925 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
23926 testcase( p[0]&0x80 );
23927 return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
23929 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
23930 p[0] = (u8)(v>>24);
23931 p[1] = (u8)(v>>16);
23932 p[2] = (u8)(v>>8);
23933 p[3] = (u8)v;
23939 ** Translate a single byte of Hex into an integer.
23940 ** This routine only works if h really is a valid hexadecimal
23941 ** character: 0..9a..fA..F
23943 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
23944 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
23945 #ifdef SQLITE_ASCII
23946 h += 9*(1&(h>>6));
23947 #endif
23948 #ifdef SQLITE_EBCDIC
23949 h += 9*(1&~(h>>4));
23950 #endif
23951 return (u8)(h & 0xf);
23954 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
23956 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
23957 ** value. Return a pointer to its binary value. Space to hold the
23958 ** binary value has been obtained from malloc and must be freed by
23959 ** the calling routine.
23961 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
23962 char *zBlob;
23963 int i;
23965 zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
23966 n--;
23967 if( zBlob ){
23968 for(i=0; i<n; i+=2){
23969 zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
23971 zBlob[i/2] = 0;
23973 return zBlob;
23975 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
23978 ** Log an error that is an API call on a connection pointer that should
23979 ** not have been used. The "type" of connection pointer is given as the
23980 ** argument. The zType is a word like "NULL" or "closed" or "invalid".
23982 static void logBadConnection(const char *zType){
23983 sqlite3_log(SQLITE_MISUSE,
23984 "API call with %s database connection pointer",
23985 zType
23990 ** Check to make sure we have a valid db pointer. This test is not
23991 ** foolproof but it does provide some measure of protection against
23992 ** misuse of the interface such as passing in db pointers that are
23993 ** NULL or which have been previously closed. If this routine returns
23994 ** 1 it means that the db pointer is valid and 0 if it should not be
23995 ** dereferenced for any reason. The calling function should invoke
23996 ** SQLITE_MISUSE immediately.
23998 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
23999 ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
24000 ** open properly and is not fit for general use but which can be
24001 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
24003 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
24004 u32 magic;
24005 if( db==0 ){
24006 logBadConnection("NULL");
24007 return 0;
24009 magic = db->magic;
24010 if( magic!=SQLITE_MAGIC_OPEN ){
24011 if( sqlite3SafetyCheckSickOrOk(db) ){
24012 testcase( sqlite3GlobalConfig.xLog!=0 );
24013 logBadConnection("unopened");
24015 return 0;
24016 }else{
24017 return 1;
24020 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
24021 u32 magic;
24022 magic = db->magic;
24023 if( magic!=SQLITE_MAGIC_SICK &&
24024 magic!=SQLITE_MAGIC_OPEN &&
24025 magic!=SQLITE_MAGIC_BUSY ){
24026 testcase( sqlite3GlobalConfig.xLog!=0 );
24027 logBadConnection("invalid");
24028 return 0;
24029 }else{
24030 return 1;
24035 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
24036 ** the other 64-bit signed integer at *pA and store the result in *pA.
24037 ** Return 0 on success. Or if the operation would have resulted in an
24038 ** overflow, leave *pA unchanged and return 1.
24040 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
24041 i64 iA = *pA;
24042 testcase( iA==0 ); testcase( iA==1 );
24043 testcase( iB==-1 ); testcase( iB==0 );
24044 if( iB>=0 ){
24045 testcase( iA>0 && LARGEST_INT64 - iA == iB );
24046 testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
24047 if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
24048 }else{
24049 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
24050 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
24051 if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
24053 *pA += iB;
24054 return 0;
24056 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
24057 testcase( iB==SMALLEST_INT64+1 );
24058 if( iB==SMALLEST_INT64 ){
24059 testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
24060 if( (*pA)>=0 ) return 1;
24061 *pA -= iB;
24062 return 0;
24063 }else{
24064 return sqlite3AddInt64(pA, -iB);
24067 #define TWOPOWER32 (((i64)1)<<32)
24068 #define TWOPOWER31 (((i64)1)<<31)
24069 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
24070 i64 iA = *pA;
24071 i64 iA1, iA0, iB1, iB0, r;
24073 iA1 = iA/TWOPOWER32;
24074 iA0 = iA % TWOPOWER32;
24075 iB1 = iB/TWOPOWER32;
24076 iB0 = iB % TWOPOWER32;
24077 if( iA1==0 ){
24078 if( iB1==0 ){
24079 *pA *= iB;
24080 return 0;
24082 r = iA0*iB1;
24083 }else if( iB1==0 ){
24084 r = iA1*iB0;
24085 }else{
24086 /* If both iA1 and iB1 are non-zero, overflow will result */
24087 return 1;
24089 testcase( r==(-TWOPOWER31)-1 );
24090 testcase( r==(-TWOPOWER31) );
24091 testcase( r==TWOPOWER31 );
24092 testcase( r==TWOPOWER31-1 );
24093 if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
24094 r *= TWOPOWER32;
24095 if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
24096 *pA = r;
24097 return 0;
24101 ** Compute the absolute value of a 32-bit signed integer, of possible. Or
24102 ** if the integer has a value of -2147483648, return +2147483647
24104 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
24105 if( x>=0 ) return x;
24106 if( x==(int)0x80000000 ) return 0x7fffffff;
24107 return -x;
24110 #ifdef SQLITE_ENABLE_8_3_NAMES
24112 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
24113 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
24114 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
24115 ** three characters, then shorten the suffix on z[] to be the last three
24116 ** characters of the original suffix.
24118 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
24119 ** do the suffix shortening regardless of URI parameter.
24121 ** Examples:
24123 ** test.db-journal => test.nal
24124 ** test.db-wal => test.wal
24125 ** test.db-shm => test.shm
24126 ** test.db-mj7f3319fa => test.9fa
24128 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
24129 #if SQLITE_ENABLE_8_3_NAMES<2
24130 if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
24131 #endif
24133 int i, sz;
24134 sz = sqlite3Strlen30(z);
24135 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
24136 if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
24139 #endif
24142 ** Find (an approximate) sum of two LogEst values. This computation is
24143 ** not a simple "+" operator because LogEst is stored as a logarithmic
24144 ** value.
24147 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
24148 static const unsigned char x[] = {
24149 10, 10, /* 0,1 */
24150 9, 9, /* 2,3 */
24151 8, 8, /* 4,5 */
24152 7, 7, 7, /* 6,7,8 */
24153 6, 6, 6, /* 9,10,11 */
24154 5, 5, 5, /* 12-14 */
24155 4, 4, 4, 4, /* 15-18 */
24156 3, 3, 3, 3, 3, 3, /* 19-24 */
24157 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
24159 if( a>=b ){
24160 if( a>b+49 ) return a;
24161 if( a>b+31 ) return a+1;
24162 return a+x[a-b];
24163 }else{
24164 if( b>a+49 ) return b;
24165 if( b>a+31 ) return b+1;
24166 return b+x[b-a];
24171 ** Convert an integer into a LogEst. In other words, compute an
24172 ** approximation for 10*log2(x).
24174 SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
24175 static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
24176 LogEst y = 40;
24177 if( x<8 ){
24178 if( x<2 ) return 0;
24179 while( x<8 ){ y -= 10; x <<= 1; }
24180 }else{
24181 while( x>255 ){ y += 40; x >>= 4; }
24182 while( x>15 ){ y += 10; x >>= 1; }
24184 return a[x&7] + y - 10;
24187 #ifndef SQLITE_OMIT_VIRTUALTABLE
24189 ** Convert a double into a LogEst
24190 ** In other words, compute an approximation for 10*log2(x).
24192 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
24193 u64 a;
24194 LogEst e;
24195 assert( sizeof(x)==8 && sizeof(a)==8 );
24196 if( x<=1 ) return 0;
24197 if( x<=2000000000 ) return sqlite3LogEst((u64)x);
24198 memcpy(&a, &x, 8);
24199 e = (a>>52) - 1022;
24200 return e*10;
24202 #endif /* SQLITE_OMIT_VIRTUALTABLE */
24205 ** Convert a LogEst into an integer.
24207 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
24208 u64 n;
24209 if( x<10 ) return 1;
24210 n = x%10;
24211 x /= 10;
24212 if( n>=5 ) n -= 2;
24213 else if( n>=1 ) n -= 1;
24214 if( x>=3 ){
24215 return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
24217 return (n+8)>>(3-x);
24220 /************** End of util.c ************************************************/
24221 /************** Begin file hash.c ********************************************/
24223 ** 2001 September 22
24225 ** The author disclaims copyright to this source code. In place of
24226 ** a legal notice, here is a blessing:
24228 ** May you do good and not evil.
24229 ** May you find forgiveness for yourself and forgive others.
24230 ** May you share freely, never taking more than you give.
24232 *************************************************************************
24233 ** This is the implementation of generic hash-tables
24234 ** used in SQLite.
24236 /* #include <assert.h> */
24238 /* Turn bulk memory into a hash table object by initializing the
24239 ** fields of the Hash structure.
24241 ** "pNew" is a pointer to the hash table that is to be initialized.
24243 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
24244 assert( pNew!=0 );
24245 pNew->first = 0;
24246 pNew->count = 0;
24247 pNew->htsize = 0;
24248 pNew->ht = 0;
24251 /* Remove all entries from a hash table. Reclaim all memory.
24252 ** Call this routine to delete a hash table or to reset a hash table
24253 ** to the empty state.
24255 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
24256 HashElem *elem; /* For looping over all elements of the table */
24258 assert( pH!=0 );
24259 elem = pH->first;
24260 pH->first = 0;
24261 sqlite3_free(pH->ht);
24262 pH->ht = 0;
24263 pH->htsize = 0;
24264 while( elem ){
24265 HashElem *next_elem = elem->next;
24266 sqlite3_free(elem);
24267 elem = next_elem;
24269 pH->count = 0;
24273 ** The hashing function.
24275 static unsigned int strHash(const char *z){
24276 unsigned int h = 0;
24277 unsigned char c;
24278 while( (c = (unsigned char)*z++)!=0 ){
24279 h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
24281 return h;
24285 /* Link pNew element into the hash table pH. If pEntry!=0 then also
24286 ** insert pNew into the pEntry hash bucket.
24288 static void insertElement(
24289 Hash *pH, /* The complete hash table */
24290 struct _ht *pEntry, /* The entry into which pNew is inserted */
24291 HashElem *pNew /* The element to be inserted */
24293 HashElem *pHead; /* First element already in pEntry */
24294 if( pEntry ){
24295 pHead = pEntry->count ? pEntry->chain : 0;
24296 pEntry->count++;
24297 pEntry->chain = pNew;
24298 }else{
24299 pHead = 0;
24301 if( pHead ){
24302 pNew->next = pHead;
24303 pNew->prev = pHead->prev;
24304 if( pHead->prev ){ pHead->prev->next = pNew; }
24305 else { pH->first = pNew; }
24306 pHead->prev = pNew;
24307 }else{
24308 pNew->next = pH->first;
24309 if( pH->first ){ pH->first->prev = pNew; }
24310 pNew->prev = 0;
24311 pH->first = pNew;
24316 /* Resize the hash table so that it cantains "new_size" buckets.
24318 ** The hash table might fail to resize if sqlite3_malloc() fails or
24319 ** if the new size is the same as the prior size.
24320 ** Return TRUE if the resize occurs and false if not.
24322 static int rehash(Hash *pH, unsigned int new_size){
24323 struct _ht *new_ht; /* The new hash table */
24324 HashElem *elem, *next_elem; /* For looping over existing elements */
24326 #if SQLITE_MALLOC_SOFT_LIMIT>0
24327 if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
24328 new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
24330 if( new_size==pH->htsize ) return 0;
24331 #endif
24333 /* The inability to allocates space for a larger hash table is
24334 ** a performance hit but it is not a fatal error. So mark the
24335 ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
24336 ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
24337 ** only zeroes the requested number of bytes whereas this module will
24338 ** use the actual amount of space allocated for the hash table (which
24339 ** may be larger than the requested amount).
24341 sqlite3BeginBenignMalloc();
24342 new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
24343 sqlite3EndBenignMalloc();
24345 if( new_ht==0 ) return 0;
24346 sqlite3_free(pH->ht);
24347 pH->ht = new_ht;
24348 pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
24349 memset(new_ht, 0, new_size*sizeof(struct _ht));
24350 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
24351 unsigned int h = strHash(elem->pKey) % new_size;
24352 next_elem = elem->next;
24353 insertElement(pH, &new_ht[h], elem);
24355 return 1;
24358 /* This function (for internal use only) locates an element in an
24359 ** hash table that matches the given key. The hash for this key is
24360 ** also computed and returned in the *pH parameter.
24362 static HashElem *findElementWithHash(
24363 const Hash *pH, /* The pH to be searched */
24364 const char *pKey, /* The key we are searching for */
24365 unsigned int *pHash /* Write the hash value here */
24367 HashElem *elem; /* Used to loop thru the element list */
24368 int count; /* Number of elements left to test */
24369 unsigned int h; /* The computed hash */
24371 if( pH->ht ){
24372 struct _ht *pEntry;
24373 h = strHash(pKey) % pH->htsize;
24374 pEntry = &pH->ht[h];
24375 elem = pEntry->chain;
24376 count = pEntry->count;
24377 }else{
24378 h = 0;
24379 elem = pH->first;
24380 count = pH->count;
24382 *pHash = h;
24383 while( count-- ){
24384 assert( elem!=0 );
24385 if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
24386 return elem;
24388 elem = elem->next;
24390 return 0;
24393 /* Remove a single entry from the hash table given a pointer to that
24394 ** element and a hash on the element's key.
24396 static void removeElementGivenHash(
24397 Hash *pH, /* The pH containing "elem" */
24398 HashElem* elem, /* The element to be removed from the pH */
24399 unsigned int h /* Hash value for the element */
24401 struct _ht *pEntry;
24402 if( elem->prev ){
24403 elem->prev->next = elem->next;
24404 }else{
24405 pH->first = elem->next;
24407 if( elem->next ){
24408 elem->next->prev = elem->prev;
24410 if( pH->ht ){
24411 pEntry = &pH->ht[h];
24412 if( pEntry->chain==elem ){
24413 pEntry->chain = elem->next;
24415 pEntry->count--;
24416 assert( pEntry->count>=0 );
24418 sqlite3_free( elem );
24419 pH->count--;
24420 if( pH->count==0 ){
24421 assert( pH->first==0 );
24422 assert( pH->count==0 );
24423 sqlite3HashClear(pH);
24427 /* Attempt to locate an element of the hash table pH with a key
24428 ** that matches pKey. Return the data for this element if it is
24429 ** found, or NULL if there is no match.
24431 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
24432 HashElem *elem; /* The element that matches key */
24433 unsigned int h; /* A hash on key */
24435 assert( pH!=0 );
24436 assert( pKey!=0 );
24437 elem = findElementWithHash(pH, pKey, &h);
24438 return elem ? elem->data : 0;
24441 /* Insert an element into the hash table pH. The key is pKey
24442 ** and the data is "data".
24444 ** If no element exists with a matching key, then a new
24445 ** element is created and NULL is returned.
24447 ** If another element already exists with the same key, then the
24448 ** new data replaces the old data and the old data is returned.
24449 ** The key is not copied in this instance. If a malloc fails, then
24450 ** the new data is returned and the hash table is unchanged.
24452 ** If the "data" parameter to this function is NULL, then the
24453 ** element corresponding to "key" is removed from the hash table.
24455 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
24456 unsigned int h; /* the hash of the key modulo hash table size */
24457 HashElem *elem; /* Used to loop thru the element list */
24458 HashElem *new_elem; /* New element added to the pH */
24460 assert( pH!=0 );
24461 assert( pKey!=0 );
24462 elem = findElementWithHash(pH,pKey,&h);
24463 if( elem ){
24464 void *old_data = elem->data;
24465 if( data==0 ){
24466 removeElementGivenHash(pH,elem,h);
24467 }else{
24468 elem->data = data;
24469 elem->pKey = pKey;
24471 return old_data;
24473 if( data==0 ) return 0;
24474 new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
24475 if( new_elem==0 ) return data;
24476 new_elem->pKey = pKey;
24477 new_elem->data = data;
24478 pH->count++;
24479 if( pH->count>=10 && pH->count > 2*pH->htsize ){
24480 if( rehash(pH, pH->count*2) ){
24481 assert( pH->htsize>0 );
24482 h = strHash(pKey) % pH->htsize;
24485 insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
24486 return 0;
24489 /************** End of hash.c ************************************************/
24490 /************** Begin file opcodes.c *****************************************/
24491 /* Automatically generated. Do not edit */
24492 /* See the mkopcodec.awk script for details. */
24493 #if !defined(SQLITE_OMIT_EXPLAIN) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
24494 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
24495 # define OpHelp(X) "\0" X
24496 #else
24497 # define OpHelp(X)
24498 #endif
24499 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
24500 static const char *const azName[] = { "?",
24501 /* 1 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
24502 /* 2 */ "Savepoint" OpHelp(""),
24503 /* 3 */ "AutoCommit" OpHelp(""),
24504 /* 4 */ "Transaction" OpHelp(""),
24505 /* 5 */ "SorterNext" OpHelp(""),
24506 /* 6 */ "PrevIfOpen" OpHelp(""),
24507 /* 7 */ "NextIfOpen" OpHelp(""),
24508 /* 8 */ "Prev" OpHelp(""),
24509 /* 9 */ "Next" OpHelp(""),
24510 /* 10 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
24511 /* 11 */ "Checkpoint" OpHelp(""),
24512 /* 12 */ "JournalMode" OpHelp(""),
24513 /* 13 */ "Vacuum" OpHelp(""),
24514 /* 14 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
24515 /* 15 */ "VUpdate" OpHelp("data=r[P3@P2]"),
24516 /* 16 */ "Goto" OpHelp(""),
24517 /* 17 */ "Gosub" OpHelp(""),
24518 /* 18 */ "Return" OpHelp(""),
24519 /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
24520 /* 20 */ "InitCoroutine" OpHelp(""),
24521 /* 21 */ "EndCoroutine" OpHelp(""),
24522 /* 22 */ "Yield" OpHelp(""),
24523 /* 23 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
24524 /* 24 */ "Halt" OpHelp(""),
24525 /* 25 */ "Integer" OpHelp("r[P2]=P1"),
24526 /* 26 */ "Int64" OpHelp("r[P2]=P4"),
24527 /* 27 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
24528 /* 28 */ "Null" OpHelp("r[P2..P3]=NULL"),
24529 /* 29 */ "SoftNull" OpHelp("r[P1]=NULL"),
24530 /* 30 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
24531 /* 31 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
24532 /* 32 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
24533 /* 33 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
24534 /* 34 */ "SCopy" OpHelp("r[P2]=r[P1]"),
24535 /* 35 */ "ResultRow" OpHelp("output=r[P1@P2]"),
24536 /* 36 */ "CollSeq" OpHelp(""),
24537 /* 37 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
24538 /* 38 */ "MustBeInt" OpHelp(""),
24539 /* 39 */ "RealAffinity" OpHelp(""),
24540 /* 40 */ "Cast" OpHelp("affinity(r[P1])"),
24541 /* 41 */ "Permutation" OpHelp(""),
24542 /* 42 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
24543 /* 43 */ "Jump" OpHelp(""),
24544 /* 44 */ "Once" OpHelp(""),
24545 /* 45 */ "If" OpHelp(""),
24546 /* 46 */ "IfNot" OpHelp(""),
24547 /* 47 */ "Column" OpHelp("r[P3]=PX"),
24548 /* 48 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
24549 /* 49 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
24550 /* 50 */ "Count" OpHelp("r[P2]=count()"),
24551 /* 51 */ "ReadCookie" OpHelp(""),
24552 /* 52 */ "SetCookie" OpHelp(""),
24553 /* 53 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
24554 /* 54 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
24555 /* 55 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
24556 /* 56 */ "OpenAutoindex" OpHelp("nColumn=P2"),
24557 /* 57 */ "OpenEphemeral" OpHelp("nColumn=P2"),
24558 /* 58 */ "SorterOpen" OpHelp(""),
24559 /* 59 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
24560 /* 60 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
24561 /* 61 */ "Close" OpHelp(""),
24562 /* 62 */ "SeekLT" OpHelp("key=r[P3@P4]"),
24563 /* 63 */ "SeekLE" OpHelp("key=r[P3@P4]"),
24564 /* 64 */ "SeekGE" OpHelp("key=r[P3@P4]"),
24565 /* 65 */ "SeekGT" OpHelp("key=r[P3@P4]"),
24566 /* 66 */ "Seek" OpHelp("intkey=r[P2]"),
24567 /* 67 */ "NoConflict" OpHelp("key=r[P3@P4]"),
24568 /* 68 */ "NotFound" OpHelp("key=r[P3@P4]"),
24569 /* 69 */ "Found" OpHelp("key=r[P3@P4]"),
24570 /* 70 */ "NotExists" OpHelp("intkey=r[P3]"),
24571 /* 71 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
24572 /* 72 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
24573 /* 73 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
24574 /* 74 */ "NewRowid" OpHelp("r[P2]=rowid"),
24575 /* 75 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
24576 /* 76 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
24577 /* 77 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
24578 /* 78 */ "Ne" OpHelp("if r[P1]!=r[P3] goto P2"),
24579 /* 79 */ "Eq" OpHelp("if r[P1]==r[P3] goto P2"),
24580 /* 80 */ "Gt" OpHelp("if r[P1]>r[P3] goto P2"),
24581 /* 81 */ "Le" OpHelp("if r[P1]<=r[P3] goto P2"),
24582 /* 82 */ "Lt" OpHelp("if r[P1]<r[P3] goto P2"),
24583 /* 83 */ "Ge" OpHelp("if r[P1]>=r[P3] goto P2"),
24584 /* 84 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
24585 /* 85 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
24586 /* 86 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
24587 /* 87 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
24588 /* 88 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
24589 /* 89 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
24590 /* 90 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
24591 /* 91 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
24592 /* 92 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
24593 /* 93 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
24594 /* 94 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
24595 /* 95 */ "Delete" OpHelp(""),
24596 /* 96 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
24597 /* 97 */ "String8" OpHelp("r[P2]='P4'"),
24598 /* 98 */ "ResetCount" OpHelp(""),
24599 /* 99 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
24600 /* 100 */ "SorterData" OpHelp("r[P2]=data"),
24601 /* 101 */ "RowKey" OpHelp("r[P2]=key"),
24602 /* 102 */ "RowData" OpHelp("r[P2]=data"),
24603 /* 103 */ "Rowid" OpHelp("r[P2]=rowid"),
24604 /* 104 */ "NullRow" OpHelp(""),
24605 /* 105 */ "Last" OpHelp(""),
24606 /* 106 */ "SorterSort" OpHelp(""),
24607 /* 107 */ "Sort" OpHelp(""),
24608 /* 108 */ "Rewind" OpHelp(""),
24609 /* 109 */ "SorterInsert" OpHelp(""),
24610 /* 110 */ "IdxInsert" OpHelp("key=r[P2]"),
24611 /* 111 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
24612 /* 112 */ "IdxRowid" OpHelp("r[P2]=rowid"),
24613 /* 113 */ "IdxLE" OpHelp("key=r[P3@P4]"),
24614 /* 114 */ "IdxGT" OpHelp("key=r[P3@P4]"),
24615 /* 115 */ "IdxLT" OpHelp("key=r[P3@P4]"),
24616 /* 116 */ "IdxGE" OpHelp("key=r[P3@P4]"),
24617 /* 117 */ "Destroy" OpHelp(""),
24618 /* 118 */ "Clear" OpHelp(""),
24619 /* 119 */ "ResetSorter" OpHelp(""),
24620 /* 120 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
24621 /* 121 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
24622 /* 122 */ "ParseSchema" OpHelp(""),
24623 /* 123 */ "LoadAnalysis" OpHelp(""),
24624 /* 124 */ "DropTable" OpHelp(""),
24625 /* 125 */ "DropIndex" OpHelp(""),
24626 /* 126 */ "DropTrigger" OpHelp(""),
24627 /* 127 */ "IntegrityCk" OpHelp(""),
24628 /* 128 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
24629 /* 129 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
24630 /* 130 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
24631 /* 131 */ "Program" OpHelp(""),
24632 /* 132 */ "Param" OpHelp(""),
24633 /* 133 */ "Real" OpHelp("r[P2]=P4"),
24634 /* 134 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
24635 /* 135 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
24636 /* 136 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
24637 /* 137 */ "IfPos" OpHelp("if r[P1]>0 goto P2"),
24638 /* 138 */ "IfNeg" OpHelp("r[P1]+=P3, if r[P1]<0 goto P2"),
24639 /* 139 */ "IfZero" OpHelp("r[P1]+=P3, if r[P1]==0 goto P2"),
24640 /* 140 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
24641 /* 141 */ "IncrVacuum" OpHelp(""),
24642 /* 142 */ "Expire" OpHelp(""),
24643 /* 143 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
24644 /* 144 */ "VBegin" OpHelp(""),
24645 /* 145 */ "VCreate" OpHelp(""),
24646 /* 146 */ "VDestroy" OpHelp(""),
24647 /* 147 */ "VOpen" OpHelp(""),
24648 /* 148 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
24649 /* 149 */ "VNext" OpHelp(""),
24650 /* 150 */ "VRename" OpHelp(""),
24651 /* 151 */ "Pagecount" OpHelp(""),
24652 /* 152 */ "MaxPgcnt" OpHelp(""),
24653 /* 153 */ "Init" OpHelp("Start at P2"),
24654 /* 154 */ "Noop" OpHelp(""),
24655 /* 155 */ "Explain" OpHelp(""),
24657 return azName[i];
24659 #endif
24661 /************** End of opcodes.c *********************************************/
24662 /************** Begin file os_unix.c *****************************************/
24664 ** 2004 May 22
24666 ** The author disclaims copyright to this source code. In place of
24667 ** a legal notice, here is a blessing:
24669 ** May you do good and not evil.
24670 ** May you find forgiveness for yourself and forgive others.
24671 ** May you share freely, never taking more than you give.
24673 ******************************************************************************
24675 ** This file contains the VFS implementation for unix-like operating systems
24676 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
24678 ** There are actually several different VFS implementations in this file.
24679 ** The differences are in the way that file locking is done. The default
24680 ** implementation uses Posix Advisory Locks. Alternative implementations
24681 ** use flock(), dot-files, various proprietary locking schemas, or simply
24682 ** skip locking all together.
24684 ** This source file is organized into divisions where the logic for various
24685 ** subfunctions is contained within the appropriate division. PLEASE
24686 ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
24687 ** in the correct division and should be clearly labeled.
24689 ** The layout of divisions is as follows:
24691 ** * General-purpose declarations and utility functions.
24692 ** * Unique file ID logic used by VxWorks.
24693 ** * Various locking primitive implementations (all except proxy locking):
24694 ** + for Posix Advisory Locks
24695 ** + for no-op locks
24696 ** + for dot-file locks
24697 ** + for flock() locking
24698 ** + for named semaphore locks (VxWorks only)
24699 ** + for AFP filesystem locks (MacOSX only)
24700 ** * sqlite3_file methods not associated with locking.
24701 ** * Definitions of sqlite3_io_methods objects for all locking
24702 ** methods plus "finder" functions for each locking method.
24703 ** * sqlite3_vfs method implementations.
24704 ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
24705 ** * Definitions of sqlite3_vfs objects for all locking methods
24706 ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
24708 #if SQLITE_OS_UNIX /* This file is used on unix only */
24711 ** There are various methods for file locking used for concurrency
24712 ** control:
24714 ** 1. POSIX locking (the default),
24715 ** 2. No locking,
24716 ** 3. Dot-file locking,
24717 ** 4. flock() locking,
24718 ** 5. AFP locking (OSX only),
24719 ** 6. Named POSIX semaphores (VXWorks only),
24720 ** 7. proxy locking. (OSX only)
24722 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
24723 ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
24724 ** selection of the appropriate locking style based on the filesystem
24725 ** where the database is located.
24727 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
24728 # if defined(__APPLE__)
24729 # define SQLITE_ENABLE_LOCKING_STYLE 1
24730 # else
24731 # define SQLITE_ENABLE_LOCKING_STYLE 0
24732 # endif
24733 #endif
24736 ** Define the OS_VXWORKS pre-processor macro to 1 if building on
24737 ** vxworks, or 0 otherwise.
24739 #ifndef OS_VXWORKS
24740 # if defined(__RTP__) || defined(_WRS_KERNEL)
24741 # define OS_VXWORKS 1
24742 # else
24743 # define OS_VXWORKS 0
24744 # endif
24745 #endif
24748 ** standard include files.
24750 #include <sys/types.h>
24751 #include <sys/stat.h>
24752 #include <fcntl.h>
24753 #include <unistd.h>
24754 /* #include <time.h> */
24755 #include <sys/time.h>
24756 #include <errno.h>
24757 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
24758 # include <sys/mman.h>
24759 #endif
24761 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
24762 # include <sys/ioctl.h>
24763 # if OS_VXWORKS
24764 # include <semaphore.h>
24765 # include <limits.h>
24766 # else
24767 # include <sys/file.h>
24768 # include <sys/param.h>
24769 # endif
24770 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
24772 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
24773 # include <sys/mount.h>
24774 #endif
24776 #ifdef HAVE_UTIME
24777 # include <utime.h>
24778 #endif
24781 ** Allowed values of unixFile.fsFlags
24783 #define SQLITE_FSFLAGS_IS_MSDOS 0x1
24786 ** If we are to be thread-safe, include the pthreads header and define
24787 ** the SQLITE_UNIX_THREADS macro.
24789 #if SQLITE_THREADSAFE
24790 /* # include <pthread.h> */
24791 # define SQLITE_UNIX_THREADS 1
24792 #endif
24795 ** Default permissions when creating a new file
24797 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
24798 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
24799 #endif
24802 ** Default permissions when creating auto proxy dir
24804 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
24805 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
24806 #endif
24809 ** Maximum supported path-length.
24811 #define MAX_PATHNAME 512
24814 ** Only set the lastErrno if the error code is a real error and not
24815 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
24817 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
24819 /* Forward references */
24820 typedef struct unixShm unixShm; /* Connection shared memory */
24821 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
24822 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
24823 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
24826 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
24827 ** cannot be closed immediately. In these cases, instances of the following
24828 ** structure are used to store the file descriptor while waiting for an
24829 ** opportunity to either close or reuse it.
24831 struct UnixUnusedFd {
24832 int fd; /* File descriptor to close */
24833 int flags; /* Flags this file descriptor was opened with */
24834 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
24838 ** The unixFile structure is subclass of sqlite3_file specific to the unix
24839 ** VFS implementations.
24841 typedef struct unixFile unixFile;
24842 struct unixFile {
24843 sqlite3_io_methods const *pMethod; /* Always the first entry */
24844 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
24845 unixInodeInfo *pInode; /* Info about locks on this inode */
24846 int h; /* The file descriptor */
24847 unsigned char eFileLock; /* The type of lock held on this fd */
24848 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
24849 int lastErrno; /* The unix errno from last I/O error */
24850 void *lockingContext; /* Locking style specific state */
24851 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
24852 const char *zPath; /* Name of the file */
24853 unixShm *pShm; /* Shared memory segment information */
24854 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
24855 #if SQLITE_MAX_MMAP_SIZE>0
24856 int nFetchOut; /* Number of outstanding xFetch refs */
24857 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
24858 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
24859 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
24860 void *pMapRegion; /* Memory mapped region */
24861 #endif
24862 #ifdef __QNXNTO__
24863 int sectorSize; /* Device sector size */
24864 int deviceCharacteristics; /* Precomputed device characteristics */
24865 #endif
24866 #if SQLITE_ENABLE_LOCKING_STYLE
24867 int openFlags; /* The flags specified at open() */
24868 #endif
24869 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
24870 unsigned fsFlags; /* cached details from statfs() */
24871 #endif
24872 #if OS_VXWORKS
24873 struct vxworksFileId *pId; /* Unique file ID */
24874 #endif
24875 #ifdef SQLITE_DEBUG
24876 /* The next group of variables are used to track whether or not the
24877 ** transaction counter in bytes 24-27 of database files are updated
24878 ** whenever any part of the database changes. An assertion fault will
24879 ** occur if a file is updated without also updating the transaction
24880 ** counter. This test is made to avoid new problems similar to the
24881 ** one described by ticket #3584.
24883 unsigned char transCntrChng; /* True if the transaction counter changed */
24884 unsigned char dbUpdate; /* True if any part of database file changed */
24885 unsigned char inNormalWrite; /* True if in a normal write operation */
24887 #endif
24889 #ifdef SQLITE_TEST
24890 /* In test mode, increase the size of this structure a bit so that
24891 ** it is larger than the struct CrashFile defined in test6.c.
24893 char aPadding[32];
24894 #endif
24897 /* This variable holds the process id (pid) from when the xRandomness()
24898 ** method was called. If xOpen() is called from a different process id,
24899 ** indicating that a fork() has occurred, the PRNG will be reset.
24901 static int randomnessPid = 0;
24904 ** Allowed values for the unixFile.ctrlFlags bitmask:
24906 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
24907 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
24908 #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
24909 #ifndef SQLITE_DISABLE_DIRSYNC
24910 # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
24911 #else
24912 # define UNIXFILE_DIRSYNC 0x00
24913 #endif
24914 #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
24915 #define UNIXFILE_DELETE 0x20 /* Delete on close */
24916 #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
24917 #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
24918 #define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
24921 ** Include code that is common to all os_*.c files
24923 /************** Include os_common.h in the middle of os_unix.c ***************/
24924 /************** Begin file os_common.h ***************************************/
24926 ** 2004 May 22
24928 ** The author disclaims copyright to this source code. In place of
24929 ** a legal notice, here is a blessing:
24931 ** May you do good and not evil.
24932 ** May you find forgiveness for yourself and forgive others.
24933 ** May you share freely, never taking more than you give.
24935 ******************************************************************************
24937 ** This file contains macros and a little bit of code that is common to
24938 ** all of the platform-specific files (os_*.c) and is #included into those
24939 ** files.
24941 ** This file should be #included by the os_*.c files only. It is not a
24942 ** general purpose header file.
24944 #ifndef _OS_COMMON_H_
24945 #define _OS_COMMON_H_
24948 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24949 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
24950 ** switch. The following code should catch this problem at compile-time.
24952 #ifdef MEMORY_DEBUG
24953 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
24954 #endif
24956 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
24957 # ifndef SQLITE_DEBUG_OS_TRACE
24958 # define SQLITE_DEBUG_OS_TRACE 0
24959 # endif
24960 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
24961 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
24962 #else
24963 # define OSTRACE(X)
24964 #endif
24967 ** Macros for performance tracing. Normally turned off. Only works
24968 ** on i486 hardware.
24970 #ifdef SQLITE_PERFORMANCE_TRACE
24973 ** hwtime.h contains inline assembler code for implementing
24974 ** high-performance timing routines.
24976 /************** Include hwtime.h in the middle of os_common.h ****************/
24977 /************** Begin file hwtime.h ******************************************/
24979 ** 2008 May 27
24981 ** The author disclaims copyright to this source code. In place of
24982 ** a legal notice, here is a blessing:
24984 ** May you do good and not evil.
24985 ** May you find forgiveness for yourself and forgive others.
24986 ** May you share freely, never taking more than you give.
24988 ******************************************************************************
24990 ** This file contains inline asm code for retrieving "high-performance"
24991 ** counters for x86 class CPUs.
24993 #ifndef _HWTIME_H_
24994 #define _HWTIME_H_
24997 ** The following routine only works on pentium-class (or newer) processors.
24998 ** It uses the RDTSC opcode to read the cycle count value out of the
24999 ** processor and returns that value. This can be used for high-res
25000 ** profiling.
25002 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
25003 (defined(i386) || defined(__i386__) || defined(_M_IX86))
25005 #if defined(__GNUC__)
25007 __inline__ sqlite_uint64 sqlite3Hwtime(void){
25008 unsigned int lo, hi;
25009 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
25010 return (sqlite_uint64)hi << 32 | lo;
25013 #elif defined(_MSC_VER)
25015 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
25016 __asm {
25017 rdtsc
25018 ret ; return value at EDX:EAX
25022 #endif
25024 #elif (defined(__GNUC__) && defined(__x86_64__))
25026 __inline__ sqlite_uint64 sqlite3Hwtime(void){
25027 unsigned long val;
25028 __asm__ __volatile__ ("rdtsc" : "=A" (val));
25029 return val;
25032 #elif (defined(__GNUC__) && defined(__ppc__))
25034 __inline__ sqlite_uint64 sqlite3Hwtime(void){
25035 unsigned long long retval;
25036 unsigned long junk;
25037 __asm__ __volatile__ ("\n\
25038 1: mftbu %1\n\
25039 mftb %L0\n\
25040 mftbu %0\n\
25041 cmpw %0,%1\n\
25042 bne 1b"
25043 : "=r" (retval), "=r" (junk));
25044 return retval;
25047 #else
25049 #error Need implementation of sqlite3Hwtime() for your platform.
25052 ** To compile without implementing sqlite3Hwtime() for your platform,
25053 ** you can remove the above #error and use the following
25054 ** stub function. You will lose timing support for many
25055 ** of the debugging and testing utilities, but it should at
25056 ** least compile and run.
25058 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
25060 #endif
25062 #endif /* !defined(_HWTIME_H_) */
25064 /************** End of hwtime.h **********************************************/
25065 /************** Continuing where we left off in os_common.h ******************/
25067 static sqlite_uint64 g_start;
25068 static sqlite_uint64 g_elapsed;
25069 #define TIMER_START g_start=sqlite3Hwtime()
25070 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
25071 #define TIMER_ELAPSED g_elapsed
25072 #else
25073 #define TIMER_START
25074 #define TIMER_END
25075 #define TIMER_ELAPSED ((sqlite_uint64)0)
25076 #endif
25079 ** If we compile with the SQLITE_TEST macro set, then the following block
25080 ** of code will give us the ability to simulate a disk I/O error. This
25081 ** is used for testing the I/O recovery logic.
25083 #ifdef SQLITE_TEST
25084 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
25085 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
25086 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
25087 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
25088 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
25089 SQLITE_API int sqlite3_diskfull_pending = 0;
25090 SQLITE_API int sqlite3_diskfull = 0;
25091 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
25092 #define SimulateIOError(CODE) \
25093 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
25094 || sqlite3_io_error_pending-- == 1 ) \
25095 { local_ioerr(); CODE; }
25096 static void local_ioerr(){
25097 IOTRACE(("IOERR\n"));
25098 sqlite3_io_error_hit++;
25099 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
25101 #define SimulateDiskfullError(CODE) \
25102 if( sqlite3_diskfull_pending ){ \
25103 if( sqlite3_diskfull_pending == 1 ){ \
25104 local_ioerr(); \
25105 sqlite3_diskfull = 1; \
25106 sqlite3_io_error_hit = 1; \
25107 CODE; \
25108 }else{ \
25109 sqlite3_diskfull_pending--; \
25112 #else
25113 #define SimulateIOErrorBenign(X)
25114 #define SimulateIOError(A)
25115 #define SimulateDiskfullError(A)
25116 #endif
25119 ** When testing, keep a count of the number of open files.
25121 #ifdef SQLITE_TEST
25122 SQLITE_API int sqlite3_open_file_count = 0;
25123 #define OpenCounter(X) sqlite3_open_file_count+=(X)
25124 #else
25125 #define OpenCounter(X)
25126 #endif
25128 #endif /* !defined(_OS_COMMON_H_) */
25130 /************** End of os_common.h *******************************************/
25131 /************** Continuing where we left off in os_unix.c ********************/
25134 ** Define various macros that are missing from some systems.
25136 #ifndef O_LARGEFILE
25137 # define O_LARGEFILE 0
25138 #endif
25139 #ifdef SQLITE_DISABLE_LFS
25140 # undef O_LARGEFILE
25141 # define O_LARGEFILE 0
25142 #endif
25143 #ifndef O_NOFOLLOW
25144 # define O_NOFOLLOW 0
25145 #endif
25146 #ifndef O_BINARY
25147 # define O_BINARY 0
25148 #endif
25151 ** The threadid macro resolves to the thread-id or to 0. Used for
25152 ** testing and debugging only.
25154 #if SQLITE_THREADSAFE
25155 #define threadid pthread_self()
25156 #else
25157 #define threadid 0
25158 #endif
25161 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
25163 #if !defined(HAVE_MREMAP)
25164 # if defined(__linux__) && defined(_GNU_SOURCE)
25165 # define HAVE_MREMAP 1
25166 # else
25167 # define HAVE_MREMAP 0
25168 # endif
25169 #endif
25172 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
25173 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
25175 #ifdef __ANDROID__
25176 # define lseek lseek64
25177 #endif
25180 ** Different Unix systems declare open() in different ways. Same use
25181 ** open(const char*,int,mode_t). Others use open(const char*,int,...).
25182 ** The difference is important when using a pointer to the function.
25184 ** The safest way to deal with the problem is to always use this wrapper
25185 ** which always has the same well-defined interface.
25187 static int posixOpen(const char *zFile, int flags, int mode){
25188 return open(zFile, flags, mode);
25192 ** On some systems, calls to fchown() will trigger a message in a security
25193 ** log if they come from non-root processes. So avoid calling fchown() if
25194 ** we are not running as root.
25196 static int posixFchown(int fd, uid_t uid, gid_t gid){
25197 #if OS_VXWORKS
25198 return 0;
25199 #else
25200 return geteuid() ? 0 : fchown(fd,uid,gid);
25201 #endif
25204 /* Forward reference */
25205 static int openDirectory(const char*, int*);
25206 static int unixGetpagesize(void);
25209 ** Many system calls are accessed through pointer-to-functions so that
25210 ** they may be overridden at runtime to facilitate fault injection during
25211 ** testing and sandboxing. The following array holds the names and pointers
25212 ** to all overrideable system calls.
25214 static struct unix_syscall {
25215 const char *zName; /* Name of the system call */
25216 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
25217 sqlite3_syscall_ptr pDefault; /* Default value */
25218 } aSyscall[] = {
25219 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
25220 #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
25222 { "close", (sqlite3_syscall_ptr)close, 0 },
25223 #define osClose ((int(*)(int))aSyscall[1].pCurrent)
25225 { "access", (sqlite3_syscall_ptr)access, 0 },
25226 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
25228 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
25229 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
25231 { "stat", (sqlite3_syscall_ptr)stat, 0 },
25232 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
25235 ** The DJGPP compiler environment looks mostly like Unix, but it
25236 ** lacks the fcntl() system call. So redefine fcntl() to be something
25237 ** that always succeeds. This means that locking does not occur under
25238 ** DJGPP. But it is DOS - what did you expect?
25240 #ifdef __DJGPP__
25241 { "fstat", 0, 0 },
25242 #define osFstat(a,b,c) 0
25243 #else
25244 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
25245 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
25246 #endif
25248 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
25249 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
25251 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
25252 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
25254 { "read", (sqlite3_syscall_ptr)read, 0 },
25255 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
25257 #if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
25258 { "pread", (sqlite3_syscall_ptr)pread, 0 },
25259 #else
25260 { "pread", (sqlite3_syscall_ptr)0, 0 },
25261 #endif
25262 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
25264 #if defined(USE_PREAD64)
25265 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
25266 #else
25267 { "pread64", (sqlite3_syscall_ptr)0, 0 },
25268 #endif
25269 #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
25271 { "write", (sqlite3_syscall_ptr)write, 0 },
25272 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
25274 #if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
25275 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
25276 #else
25277 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
25278 #endif
25279 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
25280 aSyscall[12].pCurrent)
25282 #if defined(USE_PREAD64)
25283 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
25284 #else
25285 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
25286 #endif
25287 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
25288 aSyscall[13].pCurrent)
25290 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
25291 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
25293 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
25294 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
25295 #else
25296 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
25297 #endif
25298 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
25300 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
25301 #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
25303 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
25304 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
25306 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
25307 #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
25309 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
25310 #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
25312 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
25313 #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
25315 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
25316 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
25317 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
25319 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
25320 #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
25322 #if HAVE_MREMAP
25323 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
25324 #else
25325 { "mremap", (sqlite3_syscall_ptr)0, 0 },
25326 #endif
25327 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
25328 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
25329 #define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
25331 #endif
25333 }; /* End of the overrideable system calls */
25336 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
25337 ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
25338 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
25339 ** system call named zName.
25341 static int unixSetSystemCall(
25342 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
25343 const char *zName, /* Name of system call to override */
25344 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
25346 unsigned int i;
25347 int rc = SQLITE_NOTFOUND;
25349 UNUSED_PARAMETER(pNotUsed);
25350 if( zName==0 ){
25351 /* If no zName is given, restore all system calls to their default
25352 ** settings and return NULL
25354 rc = SQLITE_OK;
25355 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25356 if( aSyscall[i].pDefault ){
25357 aSyscall[i].pCurrent = aSyscall[i].pDefault;
25360 }else{
25361 /* If zName is specified, operate on only the one system call
25362 ** specified.
25364 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25365 if( strcmp(zName, aSyscall[i].zName)==0 ){
25366 if( aSyscall[i].pDefault==0 ){
25367 aSyscall[i].pDefault = aSyscall[i].pCurrent;
25369 rc = SQLITE_OK;
25370 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
25371 aSyscall[i].pCurrent = pNewFunc;
25372 break;
25376 return rc;
25380 ** Return the value of a system call. Return NULL if zName is not a
25381 ** recognized system call name. NULL is also returned if the system call
25382 ** is currently undefined.
25384 static sqlite3_syscall_ptr unixGetSystemCall(
25385 sqlite3_vfs *pNotUsed,
25386 const char *zName
25388 unsigned int i;
25390 UNUSED_PARAMETER(pNotUsed);
25391 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25392 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
25394 return 0;
25398 ** Return the name of the first system call after zName. If zName==NULL
25399 ** then return the name of the first system call. Return NULL if zName
25400 ** is the last system call or if zName is not the name of a valid
25401 ** system call.
25403 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
25404 int i = -1;
25406 UNUSED_PARAMETER(p);
25407 if( zName ){
25408 for(i=0; i<ArraySize(aSyscall)-1; i++){
25409 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
25412 for(i++; i<ArraySize(aSyscall); i++){
25413 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
25415 return 0;
25419 ** Do not accept any file descriptor less than this value, in order to avoid
25420 ** opening database file using file descriptors that are commonly used for
25421 ** standard input, output, and error.
25423 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
25424 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
25425 #endif
25428 ** Invoke open(). Do so multiple times, until it either succeeds or
25429 ** fails for some reason other than EINTR.
25431 ** If the file creation mode "m" is 0 then set it to the default for
25432 ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
25433 ** 0644) as modified by the system umask. If m is not 0, then
25434 ** make the file creation mode be exactly m ignoring the umask.
25436 ** The m parameter will be non-zero only when creating -wal, -journal,
25437 ** and -shm files. We want those files to have *exactly* the same
25438 ** permissions as their original database, unadulterated by the umask.
25439 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
25440 ** transaction crashes and leaves behind hot journals, then any
25441 ** process that is able to write to the database will also be able to
25442 ** recover the hot journals.
25444 static int robust_open(const char *z, int f, mode_t m){
25445 int fd;
25446 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
25447 while(1){
25448 #if defined(O_CLOEXEC)
25449 fd = osOpen(z,f|O_CLOEXEC,m2);
25450 #else
25451 fd = osOpen(z,f,m2);
25452 #endif
25453 if( fd<0 ){
25454 if( errno==EINTR ) continue;
25455 break;
25457 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
25458 osClose(fd);
25459 sqlite3_log(SQLITE_WARNING,
25460 "attempt to open \"%s\" as file descriptor %d", z, fd);
25461 fd = -1;
25462 if( osOpen("/dev/null", f, m)<0 ) break;
25464 if( fd>=0 ){
25465 if( m!=0 ){
25466 struct stat statbuf;
25467 if( osFstat(fd, &statbuf)==0
25468 && statbuf.st_size==0
25469 && (statbuf.st_mode&0777)!=m
25471 osFchmod(fd, m);
25474 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
25475 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25476 #endif
25478 return fd;
25482 ** Helper functions to obtain and relinquish the global mutex. The
25483 ** global mutex is used to protect the unixInodeInfo and
25484 ** vxworksFileId objects used by this file, all of which may be
25485 ** shared by multiple threads.
25487 ** Function unixMutexHeld() is used to assert() that the global mutex
25488 ** is held when required. This function is only used as part of assert()
25489 ** statements. e.g.
25491 ** unixEnterMutex()
25492 ** assert( unixMutexHeld() );
25493 ** unixEnterLeave()
25495 static void unixEnterMutex(void){
25496 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25498 static void unixLeaveMutex(void){
25499 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25501 #ifdef SQLITE_DEBUG
25502 static int unixMutexHeld(void) {
25503 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25505 #endif
25508 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
25510 ** Helper function for printing out trace information from debugging
25511 ** binaries. This returns the string representation of the supplied
25512 ** integer lock-type.
25514 static const char *azFileLock(int eFileLock){
25515 switch( eFileLock ){
25516 case NO_LOCK: return "NONE";
25517 case SHARED_LOCK: return "SHARED";
25518 case RESERVED_LOCK: return "RESERVED";
25519 case PENDING_LOCK: return "PENDING";
25520 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
25522 return "ERROR";
25524 #endif
25526 #ifdef SQLITE_LOCK_TRACE
25528 ** Print out information about all locking operations.
25530 ** This routine is used for troubleshooting locks on multithreaded
25531 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
25532 ** command-line option on the compiler. This code is normally
25533 ** turned off.
25535 static int lockTrace(int fd, int op, struct flock *p){
25536 char *zOpName, *zType;
25537 int s;
25538 int savedErrno;
25539 if( op==F_GETLK ){
25540 zOpName = "GETLK";
25541 }else if( op==F_SETLK ){
25542 zOpName = "SETLK";
25543 }else{
25544 s = osFcntl(fd, op, p);
25545 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
25546 return s;
25548 if( p->l_type==F_RDLCK ){
25549 zType = "RDLCK";
25550 }else if( p->l_type==F_WRLCK ){
25551 zType = "WRLCK";
25552 }else if( p->l_type==F_UNLCK ){
25553 zType = "UNLCK";
25554 }else{
25555 assert( 0 );
25557 assert( p->l_whence==SEEK_SET );
25558 s = osFcntl(fd, op, p);
25559 savedErrno = errno;
25560 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
25561 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
25562 (int)p->l_pid, s);
25563 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
25564 struct flock l2;
25565 l2 = *p;
25566 osFcntl(fd, F_GETLK, &l2);
25567 if( l2.l_type==F_RDLCK ){
25568 zType = "RDLCK";
25569 }else if( l2.l_type==F_WRLCK ){
25570 zType = "WRLCK";
25571 }else if( l2.l_type==F_UNLCK ){
25572 zType = "UNLCK";
25573 }else{
25574 assert( 0 );
25576 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
25577 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
25579 errno = savedErrno;
25580 return s;
25582 #undef osFcntl
25583 #define osFcntl lockTrace
25584 #endif /* SQLITE_LOCK_TRACE */
25587 ** Retry ftruncate() calls that fail due to EINTR
25589 ** All calls to ftruncate() within this file should be made through this wrapper.
25590 ** On the Android platform, bypassing the logic below could lead to a corrupt
25591 ** database.
25593 static int robust_ftruncate(int h, sqlite3_int64 sz){
25594 int rc;
25595 #ifdef __ANDROID__
25596 /* On Android, ftruncate() always uses 32-bit offsets, even if
25597 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
25598 ** truncate a file to any size larger than 2GiB. Silently ignore any
25599 ** such attempts. */
25600 if( sz>(sqlite3_int64)0x7FFFFFFF ){
25601 rc = SQLITE_OK;
25602 }else
25603 #endif
25604 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
25605 return rc;
25609 ** This routine translates a standard POSIX errno code into something
25610 ** useful to the clients of the sqlite3 functions. Specifically, it is
25611 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
25612 ** and a variety of "please close the file descriptor NOW" errors into
25613 ** SQLITE_IOERR
25615 ** Errors during initialization of locks, or file system support for locks,
25616 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
25618 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
25619 switch (posixError) {
25620 #if 0
25621 /* At one point this code was not commented out. In theory, this branch
25622 ** should never be hit, as this function should only be called after
25623 ** a locking-related function (i.e. fcntl()) has returned non-zero with
25624 ** the value of errno as the first argument. Since a system call has failed,
25625 ** errno should be non-zero.
25627 ** Despite this, if errno really is zero, we still don't want to return
25628 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
25629 ** propagated back to the caller. Commenting this branch out means errno==0
25630 ** will be handled by the "default:" case below.
25632 case 0:
25633 return SQLITE_OK;
25634 #endif
25636 case EAGAIN:
25637 case ETIMEDOUT:
25638 case EBUSY:
25639 case EINTR:
25640 case ENOLCK:
25641 /* random NFS retry error, unless during file system support
25642 * introspection, in which it actually means what it says */
25643 return SQLITE_BUSY;
25645 case EACCES:
25646 /* EACCES is like EAGAIN during locking operations, but not any other time*/
25647 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
25648 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
25649 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
25650 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
25651 return SQLITE_BUSY;
25653 /* else fall through */
25654 case EPERM:
25655 return SQLITE_PERM;
25657 #if EOPNOTSUPP!=ENOTSUP
25658 case EOPNOTSUPP:
25659 /* something went terribly awry, unless during file system support
25660 * introspection, in which it actually means what it says */
25661 #endif
25662 #ifdef ENOTSUP
25663 case ENOTSUP:
25664 /* invalid fd, unless during file system support introspection, in which
25665 * it actually means what it says */
25666 #endif
25667 case EIO:
25668 case EBADF:
25669 case EINVAL:
25670 case ENOTCONN:
25671 case ENODEV:
25672 case ENXIO:
25673 case ENOENT:
25674 #ifdef ESTALE /* ESTALE is not defined on Interix systems */
25675 case ESTALE:
25676 #endif
25677 case ENOSYS:
25678 /* these should force the client to close the file and reconnect */
25680 default:
25681 return sqliteIOErr;
25686 /******************************************************************************
25687 ****************** Begin Unique File ID Utility Used By VxWorks ***************
25689 ** On most versions of unix, we can get a unique ID for a file by concatenating
25690 ** the device number and the inode number. But this does not work on VxWorks.
25691 ** On VxWorks, a unique file id must be based on the canonical filename.
25693 ** A pointer to an instance of the following structure can be used as a
25694 ** unique file ID in VxWorks. Each instance of this structure contains
25695 ** a copy of the canonical filename. There is also a reference count.
25696 ** The structure is reclaimed when the number of pointers to it drops to
25697 ** zero.
25699 ** There are never very many files open at one time and lookups are not
25700 ** a performance-critical path, so it is sufficient to put these
25701 ** structures on a linked list.
25703 struct vxworksFileId {
25704 struct vxworksFileId *pNext; /* Next in a list of them all */
25705 int nRef; /* Number of references to this one */
25706 int nName; /* Length of the zCanonicalName[] string */
25707 char *zCanonicalName; /* Canonical filename */
25710 #if OS_VXWORKS
25712 ** All unique filenames are held on a linked list headed by this
25713 ** variable:
25715 static struct vxworksFileId *vxworksFileList = 0;
25718 ** Simplify a filename into its canonical form
25719 ** by making the following changes:
25721 ** * removing any trailing and duplicate /
25722 ** * convert /./ into just /
25723 ** * convert /A/../ where A is any simple name into just /
25725 ** Changes are made in-place. Return the new name length.
25727 ** The original filename is in z[0..n-1]. Return the number of
25728 ** characters in the simplified name.
25730 static int vxworksSimplifyName(char *z, int n){
25731 int i, j;
25732 while( n>1 && z[n-1]=='/' ){ n--; }
25733 for(i=j=0; i<n; i++){
25734 if( z[i]=='/' ){
25735 if( z[i+1]=='/' ) continue;
25736 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
25737 i += 1;
25738 continue;
25740 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
25741 while( j>0 && z[j-1]!='/' ){ j--; }
25742 if( j>0 ){ j--; }
25743 i += 2;
25744 continue;
25747 z[j++] = z[i];
25749 z[j] = 0;
25750 return j;
25754 ** Find a unique file ID for the given absolute pathname. Return
25755 ** a pointer to the vxworksFileId object. This pointer is the unique
25756 ** file ID.
25758 ** The nRef field of the vxworksFileId object is incremented before
25759 ** the object is returned. A new vxworksFileId object is created
25760 ** and added to the global list if necessary.
25762 ** If a memory allocation error occurs, return NULL.
25764 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
25765 struct vxworksFileId *pNew; /* search key and new file ID */
25766 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
25767 int n; /* Length of zAbsoluteName string */
25769 assert( zAbsoluteName[0]=='/' );
25770 n = (int)strlen(zAbsoluteName);
25771 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
25772 if( pNew==0 ) return 0;
25773 pNew->zCanonicalName = (char*)&pNew[1];
25774 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
25775 n = vxworksSimplifyName(pNew->zCanonicalName, n);
25777 /* Search for an existing entry that matching the canonical name.
25778 ** If found, increment the reference count and return a pointer to
25779 ** the existing file ID.
25781 unixEnterMutex();
25782 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
25783 if( pCandidate->nName==n
25784 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
25786 sqlite3_free(pNew);
25787 pCandidate->nRef++;
25788 unixLeaveMutex();
25789 return pCandidate;
25793 /* No match was found. We will make a new file ID */
25794 pNew->nRef = 1;
25795 pNew->nName = n;
25796 pNew->pNext = vxworksFileList;
25797 vxworksFileList = pNew;
25798 unixLeaveMutex();
25799 return pNew;
25803 ** Decrement the reference count on a vxworksFileId object. Free
25804 ** the object when the reference count reaches zero.
25806 static void vxworksReleaseFileId(struct vxworksFileId *pId){
25807 unixEnterMutex();
25808 assert( pId->nRef>0 );
25809 pId->nRef--;
25810 if( pId->nRef==0 ){
25811 struct vxworksFileId **pp;
25812 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
25813 assert( *pp==pId );
25814 *pp = pId->pNext;
25815 sqlite3_free(pId);
25817 unixLeaveMutex();
25819 #endif /* OS_VXWORKS */
25820 /*************** End of Unique File ID Utility Used By VxWorks ****************
25821 ******************************************************************************/
25824 /******************************************************************************
25825 *************************** Posix Advisory Locking ****************************
25827 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
25828 ** section 6.5.2.2 lines 483 through 490 specify that when a process
25829 ** sets or clears a lock, that operation overrides any prior locks set
25830 ** by the same process. It does not explicitly say so, but this implies
25831 ** that it overrides locks set by the same process using a different
25832 ** file descriptor. Consider this test case:
25834 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
25835 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
25837 ** Suppose ./file1 and ./file2 are really the same file (because
25838 ** one is a hard or symbolic link to the other) then if you set
25839 ** an exclusive lock on fd1, then try to get an exclusive lock
25840 ** on fd2, it works. I would have expected the second lock to
25841 ** fail since there was already a lock on the file due to fd1.
25842 ** But not so. Since both locks came from the same process, the
25843 ** second overrides the first, even though they were on different
25844 ** file descriptors opened on different file names.
25846 ** This means that we cannot use POSIX locks to synchronize file access
25847 ** among competing threads of the same process. POSIX locks will work fine
25848 ** to synchronize access for threads in separate processes, but not
25849 ** threads within the same process.
25851 ** To work around the problem, SQLite has to manage file locks internally
25852 ** on its own. Whenever a new database is opened, we have to find the
25853 ** specific inode of the database file (the inode is determined by the
25854 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
25855 ** and check for locks already existing on that inode. When locks are
25856 ** created or removed, we have to look at our own internal record of the
25857 ** locks to see if another thread has previously set a lock on that same
25858 ** inode.
25860 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
25861 ** For VxWorks, we have to use the alternative unique ID system based on
25862 ** canonical filename and implemented in the previous division.)
25864 ** The sqlite3_file structure for POSIX is no longer just an integer file
25865 ** descriptor. It is now a structure that holds the integer file
25866 ** descriptor and a pointer to a structure that describes the internal
25867 ** locks on the corresponding inode. There is one locking structure
25868 ** per inode, so if the same inode is opened twice, both unixFile structures
25869 ** point to the same locking structure. The locking structure keeps
25870 ** a reference count (so we will know when to delete it) and a "cnt"
25871 ** field that tells us its internal lock status. cnt==0 means the
25872 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
25873 ** cnt>0 means there are cnt shared locks on the file.
25875 ** Any attempt to lock or unlock a file first checks the locking
25876 ** structure. The fcntl() system call is only invoked to set a
25877 ** POSIX lock if the internal lock structure transitions between
25878 ** a locked and an unlocked state.
25880 ** But wait: there are yet more problems with POSIX advisory locks.
25882 ** If you close a file descriptor that points to a file that has locks,
25883 ** all locks on that file that are owned by the current process are
25884 ** released. To work around this problem, each unixInodeInfo object
25885 ** maintains a count of the number of pending locks on tha inode.
25886 ** When an attempt is made to close an unixFile, if there are
25887 ** other unixFile open on the same inode that are holding locks, the call
25888 ** to close() the file descriptor is deferred until all of the locks clear.
25889 ** The unixInodeInfo structure keeps a list of file descriptors that need to
25890 ** be closed and that list is walked (and cleared) when the last lock
25891 ** clears.
25893 ** Yet another problem: LinuxThreads do not play well with posix locks.
25895 ** Many older versions of linux use the LinuxThreads library which is
25896 ** not posix compliant. Under LinuxThreads, a lock created by thread
25897 ** A cannot be modified or overridden by a different thread B.
25898 ** Only thread A can modify the lock. Locking behavior is correct
25899 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
25900 ** on linux - with NPTL a lock created by thread A can override locks
25901 ** in thread B. But there is no way to know at compile-time which
25902 ** threading library is being used. So there is no way to know at
25903 ** compile-time whether or not thread A can override locks on thread B.
25904 ** One has to do a run-time check to discover the behavior of the
25905 ** current process.
25907 ** SQLite used to support LinuxThreads. But support for LinuxThreads
25908 ** was dropped beginning with version 3.7.0. SQLite will still work with
25909 ** LinuxThreads provided that (1) there is no more than one connection
25910 ** per database file in the same process and (2) database connections
25911 ** do not move across threads.
25915 ** An instance of the following structure serves as the key used
25916 ** to locate a particular unixInodeInfo object.
25918 struct unixFileId {
25919 dev_t dev; /* Device number */
25920 #if OS_VXWORKS
25921 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
25922 #else
25923 ino_t ino; /* Inode number */
25924 #endif
25928 ** An instance of the following structure is allocated for each open
25929 ** inode. Or, on LinuxThreads, there is one of these structures for
25930 ** each inode opened by each thread.
25932 ** A single inode can have multiple file descriptors, so each unixFile
25933 ** structure contains a pointer to an instance of this object and this
25934 ** object keeps a count of the number of unixFile pointing to it.
25936 struct unixInodeInfo {
25937 struct unixFileId fileId; /* The lookup key */
25938 int nShared; /* Number of SHARED locks held */
25939 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
25940 unsigned char bProcessLock; /* An exclusive process lock is held */
25941 int nRef; /* Number of pointers to this structure */
25942 unixShmNode *pShmNode; /* Shared memory associated with this inode */
25943 int nLock; /* Number of outstanding file locks */
25944 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
25945 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
25946 unixInodeInfo *pPrev; /* .... doubly linked */
25947 #if SQLITE_ENABLE_LOCKING_STYLE
25948 unsigned long long sharedByte; /* for AFP simulated shared lock */
25949 #endif
25950 #if OS_VXWORKS
25951 sem_t *pSem; /* Named POSIX semaphore */
25952 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
25953 #endif
25957 ** A lists of all unixInodeInfo objects.
25959 static unixInodeInfo *inodeList = 0;
25963 ** This function - unixLogError_x(), is only ever called via the macro
25964 ** unixLogError().
25966 ** It is invoked after an error occurs in an OS function and errno has been
25967 ** set. It logs a message using sqlite3_log() containing the current value of
25968 ** errno and, if possible, the human-readable equivalent from strerror() or
25969 ** strerror_r().
25971 ** The first argument passed to the macro should be the error code that
25972 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
25973 ** The two subsequent arguments should be the name of the OS function that
25974 ** failed (e.g. "unlink", "open") and the associated file-system path,
25975 ** if any.
25977 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
25978 static int unixLogErrorAtLine(
25979 int errcode, /* SQLite error code */
25980 const char *zFunc, /* Name of OS function that failed */
25981 const char *zPath, /* File path associated with error */
25982 int iLine /* Source line number where error occurred */
25984 char *zErr; /* Message from strerror() or equivalent */
25985 int iErrno = errno; /* Saved syscall error number */
25987 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
25988 ** the strerror() function to obtain the human-readable error message
25989 ** equivalent to errno. Otherwise, use strerror_r().
25991 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
25992 char aErr[80];
25993 memset(aErr, 0, sizeof(aErr));
25994 zErr = aErr;
25996 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
25997 ** assume that the system provides the GNU version of strerror_r() that
25998 ** returns a pointer to a buffer containing the error message. That pointer
25999 ** may point to aErr[], or it may point to some static storage somewhere.
26000 ** Otherwise, assume that the system provides the POSIX version of
26001 ** strerror_r(), which always writes an error message into aErr[].
26003 ** If the code incorrectly assumes that it is the POSIX version that is
26004 ** available, the error message will often be an empty string. Not a
26005 ** huge problem. Incorrectly concluding that the GNU version is available
26006 ** could lead to a segfault though.
26008 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
26009 zErr =
26010 # endif
26011 strerror_r(iErrno, aErr, sizeof(aErr)-1);
26013 #elif SQLITE_THREADSAFE
26014 /* This is a threadsafe build, but strerror_r() is not available. */
26015 zErr = "";
26016 #else
26017 /* Non-threadsafe build, use strerror(). */
26018 zErr = strerror(iErrno);
26019 #endif
26021 if( zPath==0 ) zPath = "";
26022 sqlite3_log(errcode,
26023 "os_unix.c:%d: (%d) %s(%s) - %s",
26024 iLine, iErrno, zFunc, zPath, zErr
26027 return errcode;
26031 ** Close a file descriptor.
26033 ** We assume that close() almost always works, since it is only in a
26034 ** very sick application or on a very sick platform that it might fail.
26035 ** If it does fail, simply leak the file descriptor, but do log the
26036 ** error.
26038 ** Note that it is not safe to retry close() after EINTR since the
26039 ** file descriptor might have already been reused by another thread.
26040 ** So we don't even try to recover from an EINTR. Just log the error
26041 ** and move on.
26043 static void robust_close(unixFile *pFile, int h, int lineno){
26044 if( osClose(h) ){
26045 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
26046 pFile ? pFile->zPath : 0, lineno);
26051 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
26053 static void closePendingFds(unixFile *pFile){
26054 unixInodeInfo *pInode = pFile->pInode;
26055 UnixUnusedFd *p;
26056 UnixUnusedFd *pNext;
26057 for(p=pInode->pUnused; p; p=pNext){
26058 pNext = p->pNext;
26059 robust_close(pFile, p->fd, __LINE__);
26060 sqlite3_free(p);
26062 pInode->pUnused = 0;
26066 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
26068 ** The mutex entered using the unixEnterMutex() function must be held
26069 ** when this function is called.
26071 static void releaseInodeInfo(unixFile *pFile){
26072 unixInodeInfo *pInode = pFile->pInode;
26073 assert( unixMutexHeld() );
26074 if( ALWAYS(pInode) ){
26075 pInode->nRef--;
26076 if( pInode->nRef==0 ){
26077 assert( pInode->pShmNode==0 );
26078 closePendingFds(pFile);
26079 if( pInode->pPrev ){
26080 assert( pInode->pPrev->pNext==pInode );
26081 pInode->pPrev->pNext = pInode->pNext;
26082 }else{
26083 assert( inodeList==pInode );
26084 inodeList = pInode->pNext;
26086 if( pInode->pNext ){
26087 assert( pInode->pNext->pPrev==pInode );
26088 pInode->pNext->pPrev = pInode->pPrev;
26090 sqlite3_free(pInode);
26096 ** Given a file descriptor, locate the unixInodeInfo object that
26097 ** describes that file descriptor. Create a new one if necessary. The
26098 ** return value might be uninitialized if an error occurs.
26100 ** The mutex entered using the unixEnterMutex() function must be held
26101 ** when this function is called.
26103 ** Return an appropriate error code.
26105 static int findInodeInfo(
26106 unixFile *pFile, /* Unix file with file desc used in the key */
26107 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
26109 int rc; /* System call return code */
26110 int fd; /* The file descriptor for pFile */
26111 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
26112 struct stat statbuf; /* Low-level file information */
26113 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
26115 assert( unixMutexHeld() );
26117 /* Get low-level information about the file that we can used to
26118 ** create a unique name for the file.
26120 fd = pFile->h;
26121 rc = osFstat(fd, &statbuf);
26122 if( rc!=0 ){
26123 pFile->lastErrno = errno;
26124 #ifdef EOVERFLOW
26125 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
26126 #endif
26127 return SQLITE_IOERR;
26130 #ifdef __APPLE__
26131 /* On OS X on an msdos filesystem, the inode number is reported
26132 ** incorrectly for zero-size files. See ticket #3260. To work
26133 ** around this problem (we consider it a bug in OS X, not SQLite)
26134 ** we always increase the file size to 1 by writing a single byte
26135 ** prior to accessing the inode number. The one byte written is
26136 ** an ASCII 'S' character which also happens to be the first byte
26137 ** in the header of every SQLite database. In this way, if there
26138 ** is a race condition such that another thread has already populated
26139 ** the first page of the database, no damage is done.
26141 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
26142 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
26143 if( rc!=1 ){
26144 pFile->lastErrno = errno;
26145 return SQLITE_IOERR;
26147 rc = osFstat(fd, &statbuf);
26148 if( rc!=0 ){
26149 pFile->lastErrno = errno;
26150 return SQLITE_IOERR;
26153 #endif
26155 memset(&fileId, 0, sizeof(fileId));
26156 fileId.dev = statbuf.st_dev;
26157 #if OS_VXWORKS
26158 fileId.pId = pFile->pId;
26159 #else
26160 fileId.ino = statbuf.st_ino;
26161 #endif
26162 pInode = inodeList;
26163 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
26164 pInode = pInode->pNext;
26166 if( pInode==0 ){
26167 pInode = sqlite3_malloc( sizeof(*pInode) );
26168 if( pInode==0 ){
26169 return SQLITE_NOMEM;
26171 memset(pInode, 0, sizeof(*pInode));
26172 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
26173 pInode->nRef = 1;
26174 pInode->pNext = inodeList;
26175 pInode->pPrev = 0;
26176 if( inodeList ) inodeList->pPrev = pInode;
26177 inodeList = pInode;
26178 }else{
26179 pInode->nRef++;
26181 *ppInode = pInode;
26182 return SQLITE_OK;
26186 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
26188 static int fileHasMoved(unixFile *pFile){
26189 #if OS_VXWORKS
26190 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
26191 #else
26192 struct stat buf;
26194 /* TODO(shess): This check doesn't work when the Chromium's WebDB code is
26195 ** running in the sandbox.
26197 return 0;
26199 return pFile->pInode!=0 &&
26200 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
26201 #endif
26206 ** Check a unixFile that is a database. Verify the following:
26208 ** (1) There is exactly one hard link on the file
26209 ** (2) The file is not a symbolic link
26210 ** (3) The file has not been renamed or unlinked
26212 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
26214 static void verifyDbFile(unixFile *pFile){
26215 struct stat buf;
26216 int rc;
26217 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
26218 /* One or more of the following warnings have already been issued. Do not
26219 ** repeat them so as not to clutter the error log */
26220 return;
26222 rc = osFstat(pFile->h, &buf);
26223 if( rc!=0 ){
26224 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
26225 pFile->ctrlFlags |= UNIXFILE_WARNED;
26226 return;
26228 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
26229 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
26230 pFile->ctrlFlags |= UNIXFILE_WARNED;
26231 return;
26233 if( buf.st_nlink>1 ){
26234 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
26235 pFile->ctrlFlags |= UNIXFILE_WARNED;
26236 return;
26238 if( fileHasMoved(pFile) ){
26239 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
26240 pFile->ctrlFlags |= UNIXFILE_WARNED;
26241 return;
26247 ** This routine checks if there is a RESERVED lock held on the specified
26248 ** file by this or any other process. If such a lock is held, set *pResOut
26249 ** to a non-zero value otherwise *pResOut is set to zero. The return value
26250 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26252 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
26253 int rc = SQLITE_OK;
26254 int reserved = 0;
26255 unixFile *pFile = (unixFile*)id;
26257 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26259 assert( pFile );
26260 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
26262 /* Check if a thread in this process holds such a lock */
26263 if( pFile->pInode->eFileLock>SHARED_LOCK ){
26264 reserved = 1;
26267 /* Otherwise see if some other process holds it.
26269 #ifndef __DJGPP__
26270 if( !reserved && !pFile->pInode->bProcessLock ){
26271 struct flock lock;
26272 lock.l_whence = SEEK_SET;
26273 lock.l_start = RESERVED_BYTE;
26274 lock.l_len = 1;
26275 lock.l_type = F_WRLCK;
26276 if( osFcntl(pFile->h, F_GETLK, &lock) ){
26277 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
26278 pFile->lastErrno = errno;
26279 } else if( lock.l_type!=F_UNLCK ){
26280 reserved = 1;
26283 #endif
26285 unixLeaveMutex();
26286 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
26288 *pResOut = reserved;
26289 return rc;
26293 ** Attempt to set a system-lock on the file pFile. The lock is
26294 ** described by pLock.
26296 ** If the pFile was opened read/write from unix-excl, then the only lock
26297 ** ever obtained is an exclusive lock, and it is obtained exactly once
26298 ** the first time any lock is attempted. All subsequent system locking
26299 ** operations become no-ops. Locking operations still happen internally,
26300 ** in order to coordinate access between separate database connections
26301 ** within this process, but all of that is handled in memory and the
26302 ** operating system does not participate.
26304 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
26305 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
26306 ** and is read-only.
26308 ** Zero is returned if the call completes successfully, or -1 if a call
26309 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
26311 static int unixFileLock(unixFile *pFile, struct flock *pLock){
26312 int rc;
26313 unixInodeInfo *pInode = pFile->pInode;
26314 assert( unixMutexHeld() );
26315 assert( pInode!=0 );
26316 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
26317 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
26319 if( pInode->bProcessLock==0 ){
26320 struct flock lock;
26321 assert( pInode->nLock==0 );
26322 lock.l_whence = SEEK_SET;
26323 lock.l_start = SHARED_FIRST;
26324 lock.l_len = SHARED_SIZE;
26325 lock.l_type = F_WRLCK;
26326 rc = osFcntl(pFile->h, F_SETLK, &lock);
26327 if( rc<0 ) return rc;
26328 pInode->bProcessLock = 1;
26329 pInode->nLock++;
26330 }else{
26331 rc = 0;
26333 }else{
26334 rc = osFcntl(pFile->h, F_SETLK, pLock);
26336 return rc;
26340 ** Lock the file with the lock specified by parameter eFileLock - one
26341 ** of the following:
26343 ** (1) SHARED_LOCK
26344 ** (2) RESERVED_LOCK
26345 ** (3) PENDING_LOCK
26346 ** (4) EXCLUSIVE_LOCK
26348 ** Sometimes when requesting one lock state, additional lock states
26349 ** are inserted in between. The locking might fail on one of the later
26350 ** transitions leaving the lock state different from what it started but
26351 ** still short of its goal. The following chart shows the allowed
26352 ** transitions and the inserted intermediate states:
26354 ** UNLOCKED -> SHARED
26355 ** SHARED -> RESERVED
26356 ** SHARED -> (PENDING) -> EXCLUSIVE
26357 ** RESERVED -> (PENDING) -> EXCLUSIVE
26358 ** PENDING -> EXCLUSIVE
26360 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
26361 ** routine to lower a locking level.
26363 static int unixLock(sqlite3_file *id, int eFileLock){
26364 /* The following describes the implementation of the various locks and
26365 ** lock transitions in terms of the POSIX advisory shared and exclusive
26366 ** lock primitives (called read-locks and write-locks below, to avoid
26367 ** confusion with SQLite lock names). The algorithms are complicated
26368 ** slightly in order to be compatible with windows systems simultaneously
26369 ** accessing the same database file, in case that is ever required.
26371 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
26372 ** byte', each single bytes at well known offsets, and the 'shared byte
26373 ** range', a range of 510 bytes at a well known offset.
26375 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
26376 ** byte'. If this is successful, a random byte from the 'shared byte
26377 ** range' is read-locked and the lock on the 'pending byte' released.
26379 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
26380 ** A RESERVED lock is implemented by grabbing a write-lock on the
26381 ** 'reserved byte'.
26383 ** A process may only obtain a PENDING lock after it has obtained a
26384 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
26385 ** on the 'pending byte'. This ensures that no new SHARED locks can be
26386 ** obtained, but existing SHARED locks are allowed to persist. A process
26387 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
26388 ** This property is used by the algorithm for rolling back a journal file
26389 ** after a crash.
26391 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
26392 ** implemented by obtaining a write-lock on the entire 'shared byte
26393 ** range'. Since all other locks require a read-lock on one of the bytes
26394 ** within this range, this ensures that no other locks are held on the
26395 ** database.
26397 ** The reason a single byte cannot be used instead of the 'shared byte
26398 ** range' is that some versions of windows do not support read-locks. By
26399 ** locking a random byte from a range, concurrent SHARED locks may exist
26400 ** even if the locking primitive used is always a write-lock.
26402 int rc = SQLITE_OK;
26403 unixFile *pFile = (unixFile*)id;
26404 unixInodeInfo *pInode;
26405 struct flock lock;
26406 int tErrno = 0;
26408 assert( pFile );
26409 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
26410 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
26411 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
26413 /* If there is already a lock of this type or more restrictive on the
26414 ** unixFile, do nothing. Don't use the end_lock: exit path, as
26415 ** unixEnterMutex() hasn't been called yet.
26417 if( pFile->eFileLock>=eFileLock ){
26418 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
26419 azFileLock(eFileLock)));
26420 return SQLITE_OK;
26423 /* Make sure the locking sequence is correct.
26424 ** (1) We never move from unlocked to anything higher than shared lock.
26425 ** (2) SQLite never explicitly requests a pendig lock.
26426 ** (3) A shared lock is always held when a reserve lock is requested.
26428 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
26429 assert( eFileLock!=PENDING_LOCK );
26430 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
26432 /* This mutex is needed because pFile->pInode is shared across threads
26434 unixEnterMutex();
26435 pInode = pFile->pInode;
26437 /* If some thread using this PID has a lock via a different unixFile*
26438 ** handle that precludes the requested lock, return BUSY.
26440 if( (pFile->eFileLock!=pInode->eFileLock &&
26441 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
26443 rc = SQLITE_BUSY;
26444 goto end_lock;
26447 /* If a SHARED lock is requested, and some thread using this PID already
26448 ** has a SHARED or RESERVED lock, then increment reference counts and
26449 ** return SQLITE_OK.
26451 if( eFileLock==SHARED_LOCK &&
26452 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
26453 assert( eFileLock==SHARED_LOCK );
26454 assert( pFile->eFileLock==0 );
26455 assert( pInode->nShared>0 );
26456 pFile->eFileLock = SHARED_LOCK;
26457 pInode->nShared++;
26458 pInode->nLock++;
26459 goto end_lock;
26463 /* A PENDING lock is needed before acquiring a SHARED lock and before
26464 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
26465 ** be released.
26467 lock.l_len = 1L;
26468 lock.l_whence = SEEK_SET;
26469 if( eFileLock==SHARED_LOCK
26470 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
26472 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
26473 lock.l_start = PENDING_BYTE;
26474 if( unixFileLock(pFile, &lock) ){
26475 tErrno = errno;
26476 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26477 if( rc!=SQLITE_BUSY ){
26478 pFile->lastErrno = tErrno;
26480 goto end_lock;
26485 /* If control gets to this point, then actually go ahead and make
26486 ** operating system calls for the specified lock.
26488 if( eFileLock==SHARED_LOCK ){
26489 assert( pInode->nShared==0 );
26490 assert( pInode->eFileLock==0 );
26491 assert( rc==SQLITE_OK );
26493 /* Now get the read-lock */
26494 lock.l_start = SHARED_FIRST;
26495 lock.l_len = SHARED_SIZE;
26496 if( unixFileLock(pFile, &lock) ){
26497 tErrno = errno;
26498 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26501 /* Drop the temporary PENDING lock */
26502 lock.l_start = PENDING_BYTE;
26503 lock.l_len = 1L;
26504 lock.l_type = F_UNLCK;
26505 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
26506 /* This could happen with a network mount */
26507 tErrno = errno;
26508 rc = SQLITE_IOERR_UNLOCK;
26511 if( rc ){
26512 if( rc!=SQLITE_BUSY ){
26513 pFile->lastErrno = tErrno;
26515 goto end_lock;
26516 }else{
26517 pFile->eFileLock = SHARED_LOCK;
26518 pInode->nLock++;
26519 pInode->nShared = 1;
26521 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
26522 /* We are trying for an exclusive lock but another thread in this
26523 ** same process is still holding a shared lock. */
26524 rc = SQLITE_BUSY;
26525 }else{
26526 /* The request was for a RESERVED or EXCLUSIVE lock. It is
26527 ** assumed that there is a SHARED or greater lock on the file
26528 ** already.
26530 assert( 0!=pFile->eFileLock );
26531 lock.l_type = F_WRLCK;
26533 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
26534 if( eFileLock==RESERVED_LOCK ){
26535 lock.l_start = RESERVED_BYTE;
26536 lock.l_len = 1L;
26537 }else{
26538 lock.l_start = SHARED_FIRST;
26539 lock.l_len = SHARED_SIZE;
26542 if( unixFileLock(pFile, &lock) ){
26543 tErrno = errno;
26544 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26545 if( rc!=SQLITE_BUSY ){
26546 pFile->lastErrno = tErrno;
26552 #ifdef SQLITE_DEBUG
26553 /* Set up the transaction-counter change checking flags when
26554 ** transitioning from a SHARED to a RESERVED lock. The change
26555 ** from SHARED to RESERVED marks the beginning of a normal
26556 ** write operation (not a hot journal rollback).
26558 if( rc==SQLITE_OK
26559 && pFile->eFileLock<=SHARED_LOCK
26560 && eFileLock==RESERVED_LOCK
26562 pFile->transCntrChng = 0;
26563 pFile->dbUpdate = 0;
26564 pFile->inNormalWrite = 1;
26566 #endif
26569 if( rc==SQLITE_OK ){
26570 pFile->eFileLock = eFileLock;
26571 pInode->eFileLock = eFileLock;
26572 }else if( eFileLock==EXCLUSIVE_LOCK ){
26573 pFile->eFileLock = PENDING_LOCK;
26574 pInode->eFileLock = PENDING_LOCK;
26577 end_lock:
26578 unixLeaveMutex();
26579 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
26580 rc==SQLITE_OK ? "ok" : "failed"));
26581 return rc;
26585 ** Add the file descriptor used by file handle pFile to the corresponding
26586 ** pUnused list.
26588 static void setPendingFd(unixFile *pFile){
26589 unixInodeInfo *pInode = pFile->pInode;
26590 UnixUnusedFd *p = pFile->pUnused;
26591 p->pNext = pInode->pUnused;
26592 pInode->pUnused = p;
26593 pFile->h = -1;
26594 pFile->pUnused = 0;
26598 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26599 ** must be either NO_LOCK or SHARED_LOCK.
26601 ** If the locking level of the file descriptor is already at or below
26602 ** the requested locking level, this routine is a no-op.
26604 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
26605 ** the byte range is divided into 2 parts and the first part is unlocked then
26606 ** set to a read lock, then the other part is simply unlocked. This works
26607 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
26608 ** remove the write lock on a region when a read lock is set.
26610 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
26611 unixFile *pFile = (unixFile*)id;
26612 unixInodeInfo *pInode;
26613 struct flock lock;
26614 int rc = SQLITE_OK;
26616 assert( pFile );
26617 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
26618 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26619 getpid()));
26621 assert( eFileLock<=SHARED_LOCK );
26622 if( pFile->eFileLock<=eFileLock ){
26623 return SQLITE_OK;
26625 unixEnterMutex();
26626 pInode = pFile->pInode;
26627 assert( pInode->nShared!=0 );
26628 if( pFile->eFileLock>SHARED_LOCK ){
26629 assert( pInode->eFileLock==pFile->eFileLock );
26631 #ifdef SQLITE_DEBUG
26632 /* When reducing a lock such that other processes can start
26633 ** reading the database file again, make sure that the
26634 ** transaction counter was updated if any part of the database
26635 ** file changed. If the transaction counter is not updated,
26636 ** other connections to the same file might not realize that
26637 ** the file has changed and hence might not know to flush their
26638 ** cache. The use of a stale cache can lead to database corruption.
26640 pFile->inNormalWrite = 0;
26641 #endif
26643 /* downgrading to a shared lock on NFS involves clearing the write lock
26644 ** before establishing the readlock - to avoid a race condition we downgrade
26645 ** the lock in 2 blocks, so that part of the range will be covered by a
26646 ** write lock until the rest is covered by a read lock:
26647 ** 1: [WWWWW]
26648 ** 2: [....W]
26649 ** 3: [RRRRW]
26650 ** 4: [RRRR.]
26652 if( eFileLock==SHARED_LOCK ){
26654 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
26655 (void)handleNFSUnlock;
26656 assert( handleNFSUnlock==0 );
26657 #endif
26658 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26659 if( handleNFSUnlock ){
26660 int tErrno; /* Error code from system call errors */
26661 off_t divSize = SHARED_SIZE - 1;
26663 lock.l_type = F_UNLCK;
26664 lock.l_whence = SEEK_SET;
26665 lock.l_start = SHARED_FIRST;
26666 lock.l_len = divSize;
26667 if( unixFileLock(pFile, &lock)==(-1) ){
26668 tErrno = errno;
26669 rc = SQLITE_IOERR_UNLOCK;
26670 if( IS_LOCK_ERROR(rc) ){
26671 pFile->lastErrno = tErrno;
26673 goto end_unlock;
26675 lock.l_type = F_RDLCK;
26676 lock.l_whence = SEEK_SET;
26677 lock.l_start = SHARED_FIRST;
26678 lock.l_len = divSize;
26679 if( unixFileLock(pFile, &lock)==(-1) ){
26680 tErrno = errno;
26681 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
26682 if( IS_LOCK_ERROR(rc) ){
26683 pFile->lastErrno = tErrno;
26685 goto end_unlock;
26687 lock.l_type = F_UNLCK;
26688 lock.l_whence = SEEK_SET;
26689 lock.l_start = SHARED_FIRST+divSize;
26690 lock.l_len = SHARED_SIZE-divSize;
26691 if( unixFileLock(pFile, &lock)==(-1) ){
26692 tErrno = errno;
26693 rc = SQLITE_IOERR_UNLOCK;
26694 if( IS_LOCK_ERROR(rc) ){
26695 pFile->lastErrno = tErrno;
26697 goto end_unlock;
26699 }else
26700 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26702 lock.l_type = F_RDLCK;
26703 lock.l_whence = SEEK_SET;
26704 lock.l_start = SHARED_FIRST;
26705 lock.l_len = SHARED_SIZE;
26706 if( unixFileLock(pFile, &lock) ){
26707 /* In theory, the call to unixFileLock() cannot fail because another
26708 ** process is holding an incompatible lock. If it does, this
26709 ** indicates that the other process is not following the locking
26710 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
26711 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
26712 ** an assert to fail). */
26713 rc = SQLITE_IOERR_RDLOCK;
26714 pFile->lastErrno = errno;
26715 goto end_unlock;
26719 lock.l_type = F_UNLCK;
26720 lock.l_whence = SEEK_SET;
26721 lock.l_start = PENDING_BYTE;
26722 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
26723 if( unixFileLock(pFile, &lock)==0 ){
26724 pInode->eFileLock = SHARED_LOCK;
26725 }else{
26726 rc = SQLITE_IOERR_UNLOCK;
26727 pFile->lastErrno = errno;
26728 goto end_unlock;
26731 if( eFileLock==NO_LOCK ){
26732 /* Decrement the shared lock counter. Release the lock using an
26733 ** OS call only when all threads in this same process have released
26734 ** the lock.
26736 pInode->nShared--;
26737 if( pInode->nShared==0 ){
26738 lock.l_type = F_UNLCK;
26739 lock.l_whence = SEEK_SET;
26740 lock.l_start = lock.l_len = 0L;
26741 if( unixFileLock(pFile, &lock)==0 ){
26742 pInode->eFileLock = NO_LOCK;
26743 }else{
26744 rc = SQLITE_IOERR_UNLOCK;
26745 pFile->lastErrno = errno;
26746 pInode->eFileLock = NO_LOCK;
26747 pFile->eFileLock = NO_LOCK;
26751 /* Decrement the count of locks against this same file. When the
26752 ** count reaches zero, close any other file descriptors whose close
26753 ** was deferred because of outstanding locks.
26755 pInode->nLock--;
26756 assert( pInode->nLock>=0 );
26757 if( pInode->nLock==0 ){
26758 closePendingFds(pFile);
26762 end_unlock:
26763 unixLeaveMutex();
26764 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26765 return rc;
26769 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26770 ** must be either NO_LOCK or SHARED_LOCK.
26772 ** If the locking level of the file descriptor is already at or below
26773 ** the requested locking level, this routine is a no-op.
26775 static int unixUnlock(sqlite3_file *id, int eFileLock){
26776 #if SQLITE_MAX_MMAP_SIZE>0
26777 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
26778 #endif
26779 return posixUnlock(id, eFileLock, 0);
26782 #if SQLITE_MAX_MMAP_SIZE>0
26783 static int unixMapfile(unixFile *pFd, i64 nByte);
26784 static void unixUnmapfile(unixFile *pFd);
26785 #endif
26788 ** This function performs the parts of the "close file" operation
26789 ** common to all locking schemes. It closes the directory and file
26790 ** handles, if they are valid, and sets all fields of the unixFile
26791 ** structure to 0.
26793 ** It is *not* necessary to hold the mutex when this routine is called,
26794 ** even on VxWorks. A mutex will be acquired on VxWorks by the
26795 ** vxworksReleaseFileId() routine.
26797 static int closeUnixFile(sqlite3_file *id){
26798 unixFile *pFile = (unixFile*)id;
26799 #if SQLITE_MAX_MMAP_SIZE>0
26800 unixUnmapfile(pFile);
26801 #endif
26802 if( pFile->h>=0 ){
26803 robust_close(pFile, pFile->h, __LINE__);
26804 pFile->h = -1;
26806 #if OS_VXWORKS
26807 if( pFile->pId ){
26808 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
26809 osUnlink(pFile->pId->zCanonicalName);
26811 vxworksReleaseFileId(pFile->pId);
26812 pFile->pId = 0;
26814 #endif
26815 #ifdef SQLITE_UNLINK_AFTER_CLOSE
26816 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
26817 osUnlink(pFile->zPath);
26818 sqlite3_free(*(char**)&pFile->zPath);
26819 pFile->zPath = 0;
26821 #endif
26822 OSTRACE(("CLOSE %-3d\n", pFile->h));
26823 OpenCounter(-1);
26824 sqlite3_free(pFile->pUnused);
26825 memset(pFile, 0, sizeof(unixFile));
26826 return SQLITE_OK;
26830 ** Close a file.
26832 static int unixClose(sqlite3_file *id){
26833 int rc = SQLITE_OK;
26834 unixFile *pFile = (unixFile *)id;
26835 verifyDbFile(pFile);
26836 unixUnlock(id, NO_LOCK);
26837 unixEnterMutex();
26839 /* unixFile.pInode is always valid here. Otherwise, a different close
26840 ** routine (e.g. nolockClose()) would be called instead.
26842 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
26843 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
26844 /* If there are outstanding locks, do not actually close the file just
26845 ** yet because that would clear those locks. Instead, add the file
26846 ** descriptor to pInode->pUnused list. It will be automatically closed
26847 ** when the last lock is cleared.
26849 setPendingFd(pFile);
26851 releaseInodeInfo(pFile);
26852 rc = closeUnixFile(id);
26853 unixLeaveMutex();
26854 return rc;
26857 /************** End of the posix advisory lock implementation *****************
26858 ******************************************************************************/
26860 /******************************************************************************
26861 ****************************** No-op Locking **********************************
26863 ** Of the various locking implementations available, this is by far the
26864 ** simplest: locking is ignored. No attempt is made to lock the database
26865 ** file for reading or writing.
26867 ** This locking mode is appropriate for use on read-only databases
26868 ** (ex: databases that are burned into CD-ROM, for example.) It can
26869 ** also be used if the application employs some external mechanism to
26870 ** prevent simultaneous access of the same database by two or more
26871 ** database connections. But there is a serious risk of database
26872 ** corruption if this locking mode is used in situations where multiple
26873 ** database connections are accessing the same database file at the same
26874 ** time and one or more of those connections are writing.
26877 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
26878 UNUSED_PARAMETER(NotUsed);
26879 *pResOut = 0;
26880 return SQLITE_OK;
26882 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
26883 UNUSED_PARAMETER2(NotUsed, NotUsed2);
26884 return SQLITE_OK;
26886 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
26887 UNUSED_PARAMETER2(NotUsed, NotUsed2);
26888 return SQLITE_OK;
26892 ** Close the file.
26894 static int nolockClose(sqlite3_file *id) {
26895 return closeUnixFile(id);
26898 /******************* End of the no-op lock implementation *********************
26899 ******************************************************************************/
26901 /******************************************************************************
26902 ************************* Begin dot-file Locking ******************************
26904 ** The dotfile locking implementation uses the existence of separate lock
26905 ** files (really a directory) to control access to the database. This works
26906 ** on just about every filesystem imaginable. But there are serious downsides:
26908 ** (1) There is zero concurrency. A single reader blocks all other
26909 ** connections from reading or writing the database.
26911 ** (2) An application crash or power loss can leave stale lock files
26912 ** sitting around that need to be cleared manually.
26914 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
26915 ** other locking strategy is available.
26917 ** Dotfile locking works by creating a subdirectory in the same directory as
26918 ** the database and with the same name but with a ".lock" extension added.
26919 ** The existence of a lock directory implies an EXCLUSIVE lock. All other
26920 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
26924 ** The file suffix added to the data base filename in order to create the
26925 ** lock directory.
26927 #define DOTLOCK_SUFFIX ".lock"
26930 ** This routine checks if there is a RESERVED lock held on the specified
26931 ** file by this or any other process. If such a lock is held, set *pResOut
26932 ** to a non-zero value otherwise *pResOut is set to zero. The return value
26933 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26935 ** In dotfile locking, either a lock exists or it does not. So in this
26936 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
26937 ** is held on the file and false if the file is unlocked.
26939 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
26940 int rc = SQLITE_OK;
26941 int reserved = 0;
26942 unixFile *pFile = (unixFile*)id;
26944 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26946 assert( pFile );
26948 /* Check if a thread in this process holds such a lock */
26949 if( pFile->eFileLock>SHARED_LOCK ){
26950 /* Either this connection or some other connection in the same process
26951 ** holds a lock on the file. No need to check further. */
26952 reserved = 1;
26953 }else{
26954 /* The lock is held if and only if the lockfile exists */
26955 const char *zLockFile = (const char*)pFile->lockingContext;
26956 reserved = osAccess(zLockFile, 0)==0;
26958 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
26959 *pResOut = reserved;
26960 return rc;
26964 ** Lock the file with the lock specified by parameter eFileLock - one
26965 ** of the following:
26967 ** (1) SHARED_LOCK
26968 ** (2) RESERVED_LOCK
26969 ** (3) PENDING_LOCK
26970 ** (4) EXCLUSIVE_LOCK
26972 ** Sometimes when requesting one lock state, additional lock states
26973 ** are inserted in between. The locking might fail on one of the later
26974 ** transitions leaving the lock state different from what it started but
26975 ** still short of its goal. The following chart shows the allowed
26976 ** transitions and the inserted intermediate states:
26978 ** UNLOCKED -> SHARED
26979 ** SHARED -> RESERVED
26980 ** SHARED -> (PENDING) -> EXCLUSIVE
26981 ** RESERVED -> (PENDING) -> EXCLUSIVE
26982 ** PENDING -> EXCLUSIVE
26984 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
26985 ** routine to lower a locking level.
26987 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
26988 ** But we track the other locking levels internally.
26990 static int dotlockLock(sqlite3_file *id, int eFileLock) {
26991 unixFile *pFile = (unixFile*)id;
26992 char *zLockFile = (char *)pFile->lockingContext;
26993 int rc = SQLITE_OK;
26996 /* If we have any lock, then the lock file already exists. All we have
26997 ** to do is adjust our internal record of the lock level.
26999 if( pFile->eFileLock > NO_LOCK ){
27000 pFile->eFileLock = eFileLock;
27001 /* Always update the timestamp on the old file */
27002 #ifdef HAVE_UTIME
27003 utime(zLockFile, NULL);
27004 #else
27005 utimes(zLockFile, NULL);
27006 #endif
27007 return SQLITE_OK;
27010 /* grab an exclusive lock */
27011 rc = osMkdir(zLockFile, 0777);
27012 if( rc<0 ){
27013 /* failed to open/create the lock directory */
27014 int tErrno = errno;
27015 if( EEXIST == tErrno ){
27016 rc = SQLITE_BUSY;
27017 } else {
27018 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27019 if( IS_LOCK_ERROR(rc) ){
27020 pFile->lastErrno = tErrno;
27023 return rc;
27026 /* got it, set the type and return ok */
27027 pFile->eFileLock = eFileLock;
27028 return rc;
27032 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
27033 ** must be either NO_LOCK or SHARED_LOCK.
27035 ** If the locking level of the file descriptor is already at or below
27036 ** the requested locking level, this routine is a no-op.
27038 ** When the locking level reaches NO_LOCK, delete the lock file.
27040 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
27041 unixFile *pFile = (unixFile*)id;
27042 char *zLockFile = (char *)pFile->lockingContext;
27043 int rc;
27045 assert( pFile );
27046 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
27047 pFile->eFileLock, getpid()));
27048 assert( eFileLock<=SHARED_LOCK );
27050 /* no-op if possible */
27051 if( pFile->eFileLock==eFileLock ){
27052 return SQLITE_OK;
27055 /* To downgrade to shared, simply update our internal notion of the
27056 ** lock state. No need to mess with the file on disk.
27058 if( eFileLock==SHARED_LOCK ){
27059 pFile->eFileLock = SHARED_LOCK;
27060 return SQLITE_OK;
27063 /* To fully unlock the database, delete the lock file */
27064 assert( eFileLock==NO_LOCK );
27065 rc = osRmdir(zLockFile);
27066 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
27067 if( rc<0 ){
27068 int tErrno = errno;
27069 rc = 0;
27070 if( ENOENT != tErrno ){
27071 rc = SQLITE_IOERR_UNLOCK;
27073 if( IS_LOCK_ERROR(rc) ){
27074 pFile->lastErrno = tErrno;
27076 return rc;
27078 pFile->eFileLock = NO_LOCK;
27079 return SQLITE_OK;
27083 ** Close a file. Make sure the lock has been released before closing.
27085 static int dotlockClose(sqlite3_file *id) {
27086 int rc = SQLITE_OK;
27087 if( id ){
27088 unixFile *pFile = (unixFile*)id;
27089 dotlockUnlock(id, NO_LOCK);
27090 sqlite3_free(pFile->lockingContext);
27091 rc = closeUnixFile(id);
27093 return rc;
27095 /****************** End of the dot-file lock implementation *******************
27096 ******************************************************************************/
27098 /******************************************************************************
27099 ************************** Begin flock Locking ********************************
27101 ** Use the flock() system call to do file locking.
27103 ** flock() locking is like dot-file locking in that the various
27104 ** fine-grain locking levels supported by SQLite are collapsed into
27105 ** a single exclusive lock. In other words, SHARED, RESERVED, and
27106 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
27107 ** still works when you do this, but concurrency is reduced since
27108 ** only a single process can be reading the database at a time.
27110 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
27111 ** compiling for VXWORKS.
27113 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
27116 ** Retry flock() calls that fail with EINTR
27118 #ifdef EINTR
27119 static int robust_flock(int fd, int op){
27120 int rc;
27121 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
27122 return rc;
27124 #else
27125 # define robust_flock(a,b) flock(a,b)
27126 #endif
27130 ** This routine checks if there is a RESERVED lock held on the specified
27131 ** file by this or any other process. If such a lock is held, set *pResOut
27132 ** to a non-zero value otherwise *pResOut is set to zero. The return value
27133 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27135 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
27136 int rc = SQLITE_OK;
27137 int reserved = 0;
27138 unixFile *pFile = (unixFile*)id;
27140 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27142 assert( pFile );
27144 /* Check if a thread in this process holds such a lock */
27145 if( pFile->eFileLock>SHARED_LOCK ){
27146 reserved = 1;
27149 /* Otherwise see if some other process holds it. */
27150 if( !reserved ){
27151 /* attempt to get the lock */
27152 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
27153 if( !lrc ){
27154 /* got the lock, unlock it */
27155 lrc = robust_flock(pFile->h, LOCK_UN);
27156 if ( lrc ) {
27157 int tErrno = errno;
27158 /* unlock failed with an error */
27159 lrc = SQLITE_IOERR_UNLOCK;
27160 if( IS_LOCK_ERROR(lrc) ){
27161 pFile->lastErrno = tErrno;
27162 rc = lrc;
27165 } else {
27166 int tErrno = errno;
27167 reserved = 1;
27168 /* someone else might have it reserved */
27169 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27170 if( IS_LOCK_ERROR(lrc) ){
27171 pFile->lastErrno = tErrno;
27172 rc = lrc;
27176 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
27178 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27179 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
27180 rc = SQLITE_OK;
27181 reserved=1;
27183 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27184 *pResOut = reserved;
27185 return rc;
27189 ** Lock the file with the lock specified by parameter eFileLock - one
27190 ** of the following:
27192 ** (1) SHARED_LOCK
27193 ** (2) RESERVED_LOCK
27194 ** (3) PENDING_LOCK
27195 ** (4) EXCLUSIVE_LOCK
27197 ** Sometimes when requesting one lock state, additional lock states
27198 ** are inserted in between. The locking might fail on one of the later
27199 ** transitions leaving the lock state different from what it started but
27200 ** still short of its goal. The following chart shows the allowed
27201 ** transitions and the inserted intermediate states:
27203 ** UNLOCKED -> SHARED
27204 ** SHARED -> RESERVED
27205 ** SHARED -> (PENDING) -> EXCLUSIVE
27206 ** RESERVED -> (PENDING) -> EXCLUSIVE
27207 ** PENDING -> EXCLUSIVE
27209 ** flock() only really support EXCLUSIVE locks. We track intermediate
27210 ** lock states in the sqlite3_file structure, but all locks SHARED or
27211 ** above are really EXCLUSIVE locks and exclude all other processes from
27212 ** access the file.
27214 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
27215 ** routine to lower a locking level.
27217 static int flockLock(sqlite3_file *id, int eFileLock) {
27218 int rc = SQLITE_OK;
27219 unixFile *pFile = (unixFile*)id;
27221 assert( pFile );
27223 /* if we already have a lock, it is exclusive.
27224 ** Just adjust level and punt on outta here. */
27225 if (pFile->eFileLock > NO_LOCK) {
27226 pFile->eFileLock = eFileLock;
27227 return SQLITE_OK;
27230 /* grab an exclusive lock */
27232 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
27233 int tErrno = errno;
27234 /* didn't get, must be busy */
27235 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27236 if( IS_LOCK_ERROR(rc) ){
27237 pFile->lastErrno = tErrno;
27239 } else {
27240 /* got it, set the type and return ok */
27241 pFile->eFileLock = eFileLock;
27243 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
27244 rc==SQLITE_OK ? "ok" : "failed"));
27245 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27246 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
27247 rc = SQLITE_BUSY;
27249 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27250 return rc;
27255 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
27256 ** must be either NO_LOCK or SHARED_LOCK.
27258 ** If the locking level of the file descriptor is already at or below
27259 ** the requested locking level, this routine is a no-op.
27261 static int flockUnlock(sqlite3_file *id, int eFileLock) {
27262 unixFile *pFile = (unixFile*)id;
27264 assert( pFile );
27265 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
27266 pFile->eFileLock, getpid()));
27267 assert( eFileLock<=SHARED_LOCK );
27269 /* no-op if possible */
27270 if( pFile->eFileLock==eFileLock ){
27271 return SQLITE_OK;
27274 /* shared can just be set because we always have an exclusive */
27275 if (eFileLock==SHARED_LOCK) {
27276 pFile->eFileLock = eFileLock;
27277 return SQLITE_OK;
27280 /* no, really, unlock. */
27281 if( robust_flock(pFile->h, LOCK_UN) ){
27282 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27283 return SQLITE_OK;
27284 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27285 return SQLITE_IOERR_UNLOCK;
27286 }else{
27287 pFile->eFileLock = NO_LOCK;
27288 return SQLITE_OK;
27293 ** Close a file.
27295 static int flockClose(sqlite3_file *id) {
27296 int rc = SQLITE_OK;
27297 if( id ){
27298 flockUnlock(id, NO_LOCK);
27299 rc = closeUnixFile(id);
27301 return rc;
27304 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
27306 /******************* End of the flock lock implementation *********************
27307 ******************************************************************************/
27309 /******************************************************************************
27310 ************************ Begin Named Semaphore Locking ************************
27312 ** Named semaphore locking is only supported on VxWorks.
27314 ** Semaphore locking is like dot-lock and flock in that it really only
27315 ** supports EXCLUSIVE locking. Only a single process can read or write
27316 ** the database file at a time. This reduces potential concurrency, but
27317 ** makes the lock implementation much easier.
27319 #if OS_VXWORKS
27322 ** This routine checks if there is a RESERVED lock held on the specified
27323 ** file by this or any other process. If such a lock is held, set *pResOut
27324 ** to a non-zero value otherwise *pResOut is set to zero. The return value
27325 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27327 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
27328 int rc = SQLITE_OK;
27329 int reserved = 0;
27330 unixFile *pFile = (unixFile*)id;
27332 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27334 assert( pFile );
27336 /* Check if a thread in this process holds such a lock */
27337 if( pFile->eFileLock>SHARED_LOCK ){
27338 reserved = 1;
27341 /* Otherwise see if some other process holds it. */
27342 if( !reserved ){
27343 sem_t *pSem = pFile->pInode->pSem;
27345 if( sem_trywait(pSem)==-1 ){
27346 int tErrno = errno;
27347 if( EAGAIN != tErrno ){
27348 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
27349 pFile->lastErrno = tErrno;
27350 } else {
27351 /* someone else has the lock when we are in NO_LOCK */
27352 reserved = (pFile->eFileLock < SHARED_LOCK);
27354 }else{
27355 /* we could have it if we want it */
27356 sem_post(pSem);
27359 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
27361 *pResOut = reserved;
27362 return rc;
27366 ** Lock the file with the lock specified by parameter eFileLock - one
27367 ** of the following:
27369 ** (1) SHARED_LOCK
27370 ** (2) RESERVED_LOCK
27371 ** (3) PENDING_LOCK
27372 ** (4) EXCLUSIVE_LOCK
27374 ** Sometimes when requesting one lock state, additional lock states
27375 ** are inserted in between. The locking might fail on one of the later
27376 ** transitions leaving the lock state different from what it started but
27377 ** still short of its goal. The following chart shows the allowed
27378 ** transitions and the inserted intermediate states:
27380 ** UNLOCKED -> SHARED
27381 ** SHARED -> RESERVED
27382 ** SHARED -> (PENDING) -> EXCLUSIVE
27383 ** RESERVED -> (PENDING) -> EXCLUSIVE
27384 ** PENDING -> EXCLUSIVE
27386 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
27387 ** lock states in the sqlite3_file structure, but all locks SHARED or
27388 ** above are really EXCLUSIVE locks and exclude all other processes from
27389 ** access the file.
27391 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
27392 ** routine to lower a locking level.
27394 static int semLock(sqlite3_file *id, int eFileLock) {
27395 unixFile *pFile = (unixFile*)id;
27396 sem_t *pSem = pFile->pInode->pSem;
27397 int rc = SQLITE_OK;
27399 /* if we already have a lock, it is exclusive.
27400 ** Just adjust level and punt on outta here. */
27401 if (pFile->eFileLock > NO_LOCK) {
27402 pFile->eFileLock = eFileLock;
27403 rc = SQLITE_OK;
27404 goto sem_end_lock;
27407 /* lock semaphore now but bail out when already locked. */
27408 if( sem_trywait(pSem)==-1 ){
27409 rc = SQLITE_BUSY;
27410 goto sem_end_lock;
27413 /* got it, set the type and return ok */
27414 pFile->eFileLock = eFileLock;
27416 sem_end_lock:
27417 return rc;
27421 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
27422 ** must be either NO_LOCK or SHARED_LOCK.
27424 ** If the locking level of the file descriptor is already at or below
27425 ** the requested locking level, this routine is a no-op.
27427 static int semUnlock(sqlite3_file *id, int eFileLock) {
27428 unixFile *pFile = (unixFile*)id;
27429 sem_t *pSem = pFile->pInode->pSem;
27431 assert( pFile );
27432 assert( pSem );
27433 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
27434 pFile->eFileLock, getpid()));
27435 assert( eFileLock<=SHARED_LOCK );
27437 /* no-op if possible */
27438 if( pFile->eFileLock==eFileLock ){
27439 return SQLITE_OK;
27442 /* shared can just be set because we always have an exclusive */
27443 if (eFileLock==SHARED_LOCK) {
27444 pFile->eFileLock = eFileLock;
27445 return SQLITE_OK;
27448 /* no, really unlock. */
27449 if ( sem_post(pSem)==-1 ) {
27450 int rc, tErrno = errno;
27451 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
27452 if( IS_LOCK_ERROR(rc) ){
27453 pFile->lastErrno = tErrno;
27455 return rc;
27457 pFile->eFileLock = NO_LOCK;
27458 return SQLITE_OK;
27462 ** Close a file.
27464 static int semClose(sqlite3_file *id) {
27465 if( id ){
27466 unixFile *pFile = (unixFile*)id;
27467 semUnlock(id, NO_LOCK);
27468 assert( pFile );
27469 unixEnterMutex();
27470 releaseInodeInfo(pFile);
27471 unixLeaveMutex();
27472 closeUnixFile(id);
27474 return SQLITE_OK;
27477 #endif /* OS_VXWORKS */
27479 ** Named semaphore locking is only available on VxWorks.
27481 *************** End of the named semaphore lock implementation ****************
27482 ******************************************************************************/
27485 /******************************************************************************
27486 *************************** Begin AFP Locking *********************************
27488 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
27489 ** on Apple Macintosh computers - both OS9 and OSX.
27491 ** Third-party implementations of AFP are available. But this code here
27492 ** only works on OSX.
27495 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27497 ** The afpLockingContext structure contains all afp lock specific state
27499 typedef struct afpLockingContext afpLockingContext;
27500 struct afpLockingContext {
27501 int reserved;
27502 const char *dbPath; /* Name of the open file */
27505 struct ByteRangeLockPB2
27507 unsigned long long offset; /* offset to first byte to lock */
27508 unsigned long long length; /* nbr of bytes to lock */
27509 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
27510 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
27511 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
27512 int fd; /* file desc to assoc this lock with */
27515 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
27518 ** This is a utility for setting or clearing a bit-range lock on an
27519 ** AFP filesystem.
27521 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
27523 static int afpSetLock(
27524 const char *path, /* Name of the file to be locked or unlocked */
27525 unixFile *pFile, /* Open file descriptor on path */
27526 unsigned long long offset, /* First byte to be locked */
27527 unsigned long long length, /* Number of bytes to lock */
27528 int setLockFlag /* True to set lock. False to clear lock */
27530 struct ByteRangeLockPB2 pb;
27531 int err;
27533 pb.unLockFlag = setLockFlag ? 0 : 1;
27534 pb.startEndFlag = 0;
27535 pb.offset = offset;
27536 pb.length = length;
27537 pb.fd = pFile->h;
27539 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
27540 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
27541 offset, length));
27542 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
27543 if ( err==-1 ) {
27544 int rc;
27545 int tErrno = errno;
27546 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
27547 path, tErrno, strerror(tErrno)));
27548 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
27549 rc = SQLITE_BUSY;
27550 #else
27551 rc = sqliteErrorFromPosixError(tErrno,
27552 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
27553 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
27554 if( IS_LOCK_ERROR(rc) ){
27555 pFile->lastErrno = tErrno;
27557 return rc;
27558 } else {
27559 return SQLITE_OK;
27564 ** This routine checks if there is a RESERVED lock held on the specified
27565 ** file by this or any other process. If such a lock is held, set *pResOut
27566 ** to a non-zero value otherwise *pResOut is set to zero. The return value
27567 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27569 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
27570 int rc = SQLITE_OK;
27571 int reserved = 0;
27572 unixFile *pFile = (unixFile*)id;
27573 afpLockingContext *context;
27575 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27577 assert( pFile );
27578 context = (afpLockingContext *) pFile->lockingContext;
27579 if( context->reserved ){
27580 *pResOut = 1;
27581 return SQLITE_OK;
27583 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
27585 /* Check if a thread in this process holds such a lock */
27586 if( pFile->pInode->eFileLock>SHARED_LOCK ){
27587 reserved = 1;
27590 /* Otherwise see if some other process holds it.
27592 if( !reserved ){
27593 /* lock the RESERVED byte */
27594 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
27595 if( SQLITE_OK==lrc ){
27596 /* if we succeeded in taking the reserved lock, unlock it to restore
27597 ** the original state */
27598 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
27599 } else {
27600 /* if we failed to get the lock then someone else must have it */
27601 reserved = 1;
27603 if( IS_LOCK_ERROR(lrc) ){
27604 rc=lrc;
27608 unixLeaveMutex();
27609 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
27611 *pResOut = reserved;
27612 return rc;
27616 ** Lock the file with the lock specified by parameter eFileLock - one
27617 ** of the following:
27619 ** (1) SHARED_LOCK
27620 ** (2) RESERVED_LOCK
27621 ** (3) PENDING_LOCK
27622 ** (4) EXCLUSIVE_LOCK
27624 ** Sometimes when requesting one lock state, additional lock states
27625 ** are inserted in between. The locking might fail on one of the later
27626 ** transitions leaving the lock state different from what it started but
27627 ** still short of its goal. The following chart shows the allowed
27628 ** transitions and the inserted intermediate states:
27630 ** UNLOCKED -> SHARED
27631 ** SHARED -> RESERVED
27632 ** SHARED -> (PENDING) -> EXCLUSIVE
27633 ** RESERVED -> (PENDING) -> EXCLUSIVE
27634 ** PENDING -> EXCLUSIVE
27636 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
27637 ** routine to lower a locking level.
27639 static int afpLock(sqlite3_file *id, int eFileLock){
27640 int rc = SQLITE_OK;
27641 unixFile *pFile = (unixFile*)id;
27642 unixInodeInfo *pInode = pFile->pInode;
27643 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27645 assert( pFile );
27646 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
27647 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
27648 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
27650 /* If there is already a lock of this type or more restrictive on the
27651 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
27652 ** unixEnterMutex() hasn't been called yet.
27654 if( pFile->eFileLock>=eFileLock ){
27655 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
27656 azFileLock(eFileLock)));
27657 return SQLITE_OK;
27660 /* Make sure the locking sequence is correct
27661 ** (1) We never move from unlocked to anything higher than shared lock.
27662 ** (2) SQLite never explicitly requests a pendig lock.
27663 ** (3) A shared lock is always held when a reserve lock is requested.
27665 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
27666 assert( eFileLock!=PENDING_LOCK );
27667 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
27669 /* This mutex is needed because pFile->pInode is shared across threads
27671 unixEnterMutex();
27672 pInode = pFile->pInode;
27674 /* If some thread using this PID has a lock via a different unixFile*
27675 ** handle that precludes the requested lock, return BUSY.
27677 if( (pFile->eFileLock!=pInode->eFileLock &&
27678 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
27680 rc = SQLITE_BUSY;
27681 goto afp_end_lock;
27684 /* If a SHARED lock is requested, and some thread using this PID already
27685 ** has a SHARED or RESERVED lock, then increment reference counts and
27686 ** return SQLITE_OK.
27688 if( eFileLock==SHARED_LOCK &&
27689 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
27690 assert( eFileLock==SHARED_LOCK );
27691 assert( pFile->eFileLock==0 );
27692 assert( pInode->nShared>0 );
27693 pFile->eFileLock = SHARED_LOCK;
27694 pInode->nShared++;
27695 pInode->nLock++;
27696 goto afp_end_lock;
27699 /* A PENDING lock is needed before acquiring a SHARED lock and before
27700 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
27701 ** be released.
27703 if( eFileLock==SHARED_LOCK
27704 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
27706 int failed;
27707 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
27708 if (failed) {
27709 rc = failed;
27710 goto afp_end_lock;
27714 /* If control gets to this point, then actually go ahead and make
27715 ** operating system calls for the specified lock.
27717 if( eFileLock==SHARED_LOCK ){
27718 int lrc1, lrc2, lrc1Errno = 0;
27719 long lk, mask;
27721 assert( pInode->nShared==0 );
27722 assert( pInode->eFileLock==0 );
27724 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
27725 /* Now get the read-lock SHARED_LOCK */
27726 /* note that the quality of the randomness doesn't matter that much */
27727 lk = random();
27728 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
27729 lrc1 = afpSetLock(context->dbPath, pFile,
27730 SHARED_FIRST+pInode->sharedByte, 1, 1);
27731 if( IS_LOCK_ERROR(lrc1) ){
27732 lrc1Errno = pFile->lastErrno;
27734 /* Drop the temporary PENDING lock */
27735 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
27737 if( IS_LOCK_ERROR(lrc1) ) {
27738 pFile->lastErrno = lrc1Errno;
27739 rc = lrc1;
27740 goto afp_end_lock;
27741 } else if( IS_LOCK_ERROR(lrc2) ){
27742 rc = lrc2;
27743 goto afp_end_lock;
27744 } else if( lrc1 != SQLITE_OK ) {
27745 rc = lrc1;
27746 } else {
27747 pFile->eFileLock = SHARED_LOCK;
27748 pInode->nLock++;
27749 pInode->nShared = 1;
27751 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
27752 /* We are trying for an exclusive lock but another thread in this
27753 ** same process is still holding a shared lock. */
27754 rc = SQLITE_BUSY;
27755 }else{
27756 /* The request was for a RESERVED or EXCLUSIVE lock. It is
27757 ** assumed that there is a SHARED or greater lock on the file
27758 ** already.
27760 int failed = 0;
27761 assert( 0!=pFile->eFileLock );
27762 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
27763 /* Acquire a RESERVED lock */
27764 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
27765 if( !failed ){
27766 context->reserved = 1;
27769 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
27770 /* Acquire an EXCLUSIVE lock */
27772 /* Remove the shared lock before trying the range. we'll need to
27773 ** reestablish the shared lock if we can't get the afpUnlock
27775 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
27776 pInode->sharedByte, 1, 0)) ){
27777 int failed2 = SQLITE_OK;
27778 /* now attemmpt to get the exclusive lock range */
27779 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
27780 SHARED_SIZE, 1);
27781 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
27782 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
27783 /* Can't reestablish the shared lock. Sqlite can't deal, this is
27784 ** a critical I/O error
27786 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
27787 SQLITE_IOERR_LOCK;
27788 goto afp_end_lock;
27790 }else{
27791 rc = failed;
27794 if( failed ){
27795 rc = failed;
27799 if( rc==SQLITE_OK ){
27800 pFile->eFileLock = eFileLock;
27801 pInode->eFileLock = eFileLock;
27802 }else if( eFileLock==EXCLUSIVE_LOCK ){
27803 pFile->eFileLock = PENDING_LOCK;
27804 pInode->eFileLock = PENDING_LOCK;
27807 afp_end_lock:
27808 unixLeaveMutex();
27809 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
27810 rc==SQLITE_OK ? "ok" : "failed"));
27811 return rc;
27815 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
27816 ** must be either NO_LOCK or SHARED_LOCK.
27818 ** If the locking level of the file descriptor is already at or below
27819 ** the requested locking level, this routine is a no-op.
27821 static int afpUnlock(sqlite3_file *id, int eFileLock) {
27822 int rc = SQLITE_OK;
27823 unixFile *pFile = (unixFile*)id;
27824 unixInodeInfo *pInode;
27825 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27826 int skipShared = 0;
27827 #ifdef SQLITE_TEST
27828 int h = pFile->h;
27829 #endif
27831 assert( pFile );
27832 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
27833 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
27834 getpid()));
27836 assert( eFileLock<=SHARED_LOCK );
27837 if( pFile->eFileLock<=eFileLock ){
27838 return SQLITE_OK;
27840 unixEnterMutex();
27841 pInode = pFile->pInode;
27842 assert( pInode->nShared!=0 );
27843 if( pFile->eFileLock>SHARED_LOCK ){
27844 assert( pInode->eFileLock==pFile->eFileLock );
27845 SimulateIOErrorBenign(1);
27846 SimulateIOError( h=(-1) )
27847 SimulateIOErrorBenign(0);
27849 #ifdef SQLITE_DEBUG
27850 /* When reducing a lock such that other processes can start
27851 ** reading the database file again, make sure that the
27852 ** transaction counter was updated if any part of the database
27853 ** file changed. If the transaction counter is not updated,
27854 ** other connections to the same file might not realize that
27855 ** the file has changed and hence might not know to flush their
27856 ** cache. The use of a stale cache can lead to database corruption.
27858 assert( pFile->inNormalWrite==0
27859 || pFile->dbUpdate==0
27860 || pFile->transCntrChng==1 );
27861 pFile->inNormalWrite = 0;
27862 #endif
27864 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
27865 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
27866 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
27867 /* only re-establish the shared lock if necessary */
27868 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
27869 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
27870 } else {
27871 skipShared = 1;
27874 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
27875 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
27877 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
27878 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
27879 if( !rc ){
27880 context->reserved = 0;
27883 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
27884 pInode->eFileLock = SHARED_LOCK;
27887 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
27889 /* Decrement the shared lock counter. Release the lock using an
27890 ** OS call only when all threads in this same process have released
27891 ** the lock.
27893 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
27894 pInode->nShared--;
27895 if( pInode->nShared==0 ){
27896 SimulateIOErrorBenign(1);
27897 SimulateIOError( h=(-1) )
27898 SimulateIOErrorBenign(0);
27899 if( !skipShared ){
27900 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
27902 if( !rc ){
27903 pInode->eFileLock = NO_LOCK;
27904 pFile->eFileLock = NO_LOCK;
27907 if( rc==SQLITE_OK ){
27908 pInode->nLock--;
27909 assert( pInode->nLock>=0 );
27910 if( pInode->nLock==0 ){
27911 closePendingFds(pFile);
27916 unixLeaveMutex();
27917 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
27918 return rc;
27922 ** Close a file & cleanup AFP specific locking context
27924 static int afpClose(sqlite3_file *id) {
27925 int rc = SQLITE_OK;
27926 if( id ){
27927 unixFile *pFile = (unixFile*)id;
27928 afpUnlock(id, NO_LOCK);
27929 unixEnterMutex();
27930 if( pFile->pInode && pFile->pInode->nLock ){
27931 /* If there are outstanding locks, do not actually close the file just
27932 ** yet because that would clear those locks. Instead, add the file
27933 ** descriptor to pInode->aPending. It will be automatically closed when
27934 ** the last lock is cleared.
27936 setPendingFd(pFile);
27938 releaseInodeInfo(pFile);
27939 sqlite3_free(pFile->lockingContext);
27940 rc = closeUnixFile(id);
27941 unixLeaveMutex();
27943 return rc;
27946 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27948 ** The code above is the AFP lock implementation. The code is specific
27949 ** to MacOSX and does not work on other unix platforms. No alternative
27950 ** is available. If you don't compile for a mac, then the "unix-afp"
27951 ** VFS is not available.
27953 ********************* End of the AFP lock implementation **********************
27954 ******************************************************************************/
27956 /******************************************************************************
27957 *************************** Begin NFS Locking ********************************/
27959 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27961 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
27962 ** must be either NO_LOCK or SHARED_LOCK.
27964 ** If the locking level of the file descriptor is already at or below
27965 ** the requested locking level, this routine is a no-op.
27967 static int nfsUnlock(sqlite3_file *id, int eFileLock){
27968 return posixUnlock(id, eFileLock, 1);
27971 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27973 ** The code above is the NFS lock implementation. The code is specific
27974 ** to MacOSX and does not work on other unix platforms. No alternative
27975 ** is available.
27977 ********************* End of the NFS lock implementation **********************
27978 ******************************************************************************/
27980 /******************************************************************************
27981 **************** Non-locking sqlite3_file methods *****************************
27983 ** The next division contains implementations for all methods of the
27984 ** sqlite3_file object other than the locking methods. The locking
27985 ** methods were defined in divisions above (one locking method per
27986 ** division). Those methods that are common to all locking modes
27987 ** are gather together into this division.
27991 ** Seek to the offset passed as the second argument, then read cnt
27992 ** bytes into pBuf. Return the number of bytes actually read.
27994 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
27995 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
27996 ** one system to another. Since SQLite does not define USE_PREAD
27997 ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
27998 ** See tickets #2741 and #2681.
28000 ** To avoid stomping the errno value on a failed read the lastErrno value
28001 ** is set before returning.
28003 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
28004 int got;
28005 int prior = 0;
28006 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
28007 i64 newOffset;
28008 #endif
28009 TIMER_START;
28010 assert( cnt==(cnt&0x1ffff) );
28011 assert( id->h>2 );
28012 cnt &= 0x1ffff;
28014 #if defined(USE_PREAD)
28015 got = osPread(id->h, pBuf, cnt, offset);
28016 SimulateIOError( got = -1 );
28017 #elif defined(USE_PREAD64)
28018 got = osPread64(id->h, pBuf, cnt, offset);
28019 SimulateIOError( got = -1 );
28020 #else
28021 newOffset = lseek(id->h, offset, SEEK_SET);
28022 SimulateIOError( newOffset-- );
28023 if( newOffset!=offset ){
28024 if( newOffset == -1 ){
28025 ((unixFile*)id)->lastErrno = errno;
28026 }else{
28027 ((unixFile*)id)->lastErrno = 0;
28029 return -1;
28031 got = osRead(id->h, pBuf, cnt);
28032 #endif
28033 if( got==cnt ) break;
28034 if( got<0 ){
28035 if( errno==EINTR ){ got = 1; continue; }
28036 prior = 0;
28037 ((unixFile*)id)->lastErrno = errno;
28038 break;
28039 }else if( got>0 ){
28040 cnt -= got;
28041 offset += got;
28042 prior += got;
28043 pBuf = (void*)(got + (char*)pBuf);
28045 }while( got>0 );
28046 TIMER_END;
28047 OSTRACE(("READ %-3d %5d %7lld %llu\n",
28048 id->h, got+prior, offset-prior, TIMER_ELAPSED));
28049 return got+prior;
28053 ** Read data from a file into a buffer. Return SQLITE_OK if all
28054 ** bytes were read successfully and SQLITE_IOERR if anything goes
28055 ** wrong.
28057 static int unixRead(
28058 sqlite3_file *id,
28059 void *pBuf,
28060 int amt,
28061 sqlite3_int64 offset
28063 unixFile *pFile = (unixFile *)id;
28064 int got;
28065 assert( id );
28066 assert( offset>=0 );
28067 assert( amt>0 );
28069 /* If this is a database file (not a journal, master-journal or temp
28070 ** file), the bytes in the locking range should never be read or written. */
28071 #if 0
28072 assert( pFile->pUnused==0
28073 || offset>=PENDING_BYTE+512
28074 || offset+amt<=PENDING_BYTE
28076 #endif
28078 #if SQLITE_MAX_MMAP_SIZE>0
28079 /* Deal with as much of this read request as possible by transfering
28080 ** data from the memory mapping using memcpy(). */
28081 if( offset<pFile->mmapSize ){
28082 if( offset+amt <= pFile->mmapSize ){
28083 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
28084 return SQLITE_OK;
28085 }else{
28086 int nCopy = pFile->mmapSize - offset;
28087 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
28088 pBuf = &((u8 *)pBuf)[nCopy];
28089 amt -= nCopy;
28090 offset += nCopy;
28093 #endif
28095 got = seekAndRead(pFile, offset, pBuf, amt);
28096 if( got==amt ){
28097 return SQLITE_OK;
28098 }else if( got<0 ){
28099 /* lastErrno set by seekAndRead */
28100 return SQLITE_IOERR_READ;
28101 }else{
28102 pFile->lastErrno = 0; /* not a system error */
28103 /* Unread parts of the buffer must be zero-filled */
28104 memset(&((char*)pBuf)[got], 0, amt-got);
28105 return SQLITE_IOERR_SHORT_READ;
28110 ** Attempt to seek the file-descriptor passed as the first argument to
28111 ** absolute offset iOff, then attempt to write nBuf bytes of data from
28112 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
28113 ** return the actual number of bytes written (which may be less than
28114 ** nBuf).
28116 static int seekAndWriteFd(
28117 int fd, /* File descriptor to write to */
28118 i64 iOff, /* File offset to begin writing at */
28119 const void *pBuf, /* Copy data from this buffer to the file */
28120 int nBuf, /* Size of buffer pBuf in bytes */
28121 int *piErrno /* OUT: Error number if error occurs */
28123 int rc = 0; /* Value returned by system call */
28125 assert( nBuf==(nBuf&0x1ffff) );
28126 assert( fd>2 );
28127 nBuf &= 0x1ffff;
28128 TIMER_START;
28130 #if defined(USE_PREAD)
28131 do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
28132 #elif defined(USE_PREAD64)
28133 do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
28134 #else
28136 i64 iSeek = lseek(fd, iOff, SEEK_SET);
28137 SimulateIOError( iSeek-- );
28139 if( iSeek!=iOff ){
28140 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
28141 return -1;
28143 rc = osWrite(fd, pBuf, nBuf);
28144 }while( rc<0 && errno==EINTR );
28145 #endif
28147 TIMER_END;
28148 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
28150 if( rc<0 && piErrno ) *piErrno = errno;
28151 return rc;
28156 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
28157 ** Return the number of bytes actually read. Update the offset.
28159 ** To avoid stomping the errno value on a failed write the lastErrno value
28160 ** is set before returning.
28162 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
28163 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
28168 ** Write data from a buffer into a file. Return SQLITE_OK on success
28169 ** or some other error code on failure.
28171 static int unixWrite(
28172 sqlite3_file *id,
28173 const void *pBuf,
28174 int amt,
28175 sqlite3_int64 offset
28177 unixFile *pFile = (unixFile*)id;
28178 int wrote = 0;
28179 assert( id );
28180 assert( amt>0 );
28182 /* If this is a database file (not a journal, master-journal or temp
28183 ** file), the bytes in the locking range should never be read or written. */
28184 #if 0
28185 assert( pFile->pUnused==0
28186 || offset>=PENDING_BYTE+512
28187 || offset+amt<=PENDING_BYTE
28189 #endif
28191 #ifdef SQLITE_DEBUG
28192 /* If we are doing a normal write to a database file (as opposed to
28193 ** doing a hot-journal rollback or a write to some file other than a
28194 ** normal database file) then record the fact that the database
28195 ** has changed. If the transaction counter is modified, record that
28196 ** fact too.
28198 if( pFile->inNormalWrite ){
28199 pFile->dbUpdate = 1; /* The database has been modified */
28200 if( offset<=24 && offset+amt>=27 ){
28201 int rc;
28202 char oldCntr[4];
28203 SimulateIOErrorBenign(1);
28204 rc = seekAndRead(pFile, 24, oldCntr, 4);
28205 SimulateIOErrorBenign(0);
28206 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
28207 pFile->transCntrChng = 1; /* The transaction counter has changed */
28211 #endif
28213 #if !SQLITE_MMAP_READ_ONLY
28214 #if SQLITE_MAX_MMAP_SIZE>0
28215 /* Deal with as much of this write request as possible by transfering
28216 ** data from the memory mapping using memcpy(). */
28217 if( offset<pFile->mmapSize ){
28218 if( offset+amt <= pFile->mmapSize ){
28219 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
28220 return SQLITE_OK;
28221 }else{
28222 int nCopy = pFile->mmapSize - offset;
28223 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
28224 pBuf = &((u8 *)pBuf)[nCopy];
28225 amt -= nCopy;
28226 offset += nCopy;
28229 #endif
28230 #endif
28232 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
28233 amt -= wrote;
28234 offset += wrote;
28235 pBuf = &((char*)pBuf)[wrote];
28237 SimulateIOError(( wrote=(-1), amt=1 ));
28238 SimulateDiskfullError(( wrote=0, amt=1 ));
28240 if( amt>0 ){
28241 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
28242 /* lastErrno set by seekAndWrite */
28243 return SQLITE_IOERR_WRITE;
28244 }else{
28245 pFile->lastErrno = 0; /* not a system error */
28246 return SQLITE_FULL;
28250 return SQLITE_OK;
28253 #ifdef SQLITE_TEST
28255 ** Count the number of fullsyncs and normal syncs. This is used to test
28256 ** that syncs and fullsyncs are occurring at the right times.
28258 SQLITE_API int sqlite3_sync_count = 0;
28259 SQLITE_API int sqlite3_fullsync_count = 0;
28260 #endif
28263 ** We do not trust systems to provide a working fdatasync(). Some do.
28264 ** Others do no. To be safe, we will stick with the (slightly slower)
28265 ** fsync(). If you know that your system does support fdatasync() correctly,
28266 ** then simply compile with -Dfdatasync=fdatasync
28268 #if !defined(fdatasync)
28269 # define fdatasync fsync
28270 #endif
28273 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
28274 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
28275 ** only available on Mac OS X. But that could change.
28277 #ifdef F_FULLFSYNC
28278 # define HAVE_FULLFSYNC 1
28279 #else
28280 # define HAVE_FULLFSYNC 0
28281 #endif
28285 ** The fsync() system call does not work as advertised on many
28286 ** unix systems. The following procedure is an attempt to make
28287 ** it work better.
28289 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
28290 ** for testing when we want to run through the test suite quickly.
28291 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
28292 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
28293 ** or power failure will likely corrupt the database file.
28295 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
28296 ** The idea behind dataOnly is that it should only write the file content
28297 ** to disk, not the inode. We only set dataOnly if the file size is
28298 ** unchanged since the file size is part of the inode. However,
28299 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
28300 ** file size has changed. The only real difference between fdatasync()
28301 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
28302 ** inode if the mtime or owner or other inode attributes have changed.
28303 ** We only care about the file size, not the other file attributes, so
28304 ** as far as SQLite is concerned, an fdatasync() is always adequate.
28305 ** So, we always use fdatasync() if it is available, regardless of
28306 ** the value of the dataOnly flag.
28308 static int full_fsync(int fd, int fullSync, int dataOnly){
28309 int rc;
28311 /* The following "ifdef/elif/else/" block has the same structure as
28312 ** the one below. It is replicated here solely to avoid cluttering
28313 ** up the real code with the UNUSED_PARAMETER() macros.
28315 #ifdef SQLITE_NO_SYNC
28316 UNUSED_PARAMETER(fd);
28317 UNUSED_PARAMETER(fullSync);
28318 UNUSED_PARAMETER(dataOnly);
28319 #elif HAVE_FULLFSYNC
28320 UNUSED_PARAMETER(dataOnly);
28321 #else
28322 UNUSED_PARAMETER(fullSync);
28323 UNUSED_PARAMETER(dataOnly);
28324 #endif
28326 /* Record the number of times that we do a normal fsync() and
28327 ** FULLSYNC. This is used during testing to verify that this procedure
28328 ** gets called with the correct arguments.
28330 #ifdef SQLITE_TEST
28331 if( fullSync ) sqlite3_fullsync_count++;
28332 sqlite3_sync_count++;
28333 #endif
28335 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
28336 ** no-op
28338 #ifdef SQLITE_NO_SYNC
28339 rc = SQLITE_OK;
28340 #elif HAVE_FULLFSYNC
28341 if( fullSync ){
28342 rc = osFcntl(fd, F_FULLFSYNC, 0);
28343 }else{
28344 rc = 1;
28346 /* If the FULLFSYNC failed, fall back to attempting an fsync().
28347 ** It shouldn't be possible for fullfsync to fail on the local
28348 ** file system (on OSX), so failure indicates that FULLFSYNC
28349 ** isn't supported for this file system. So, attempt an fsync
28350 ** and (for now) ignore the overhead of a superfluous fcntl call.
28351 ** It'd be better to detect fullfsync support once and avoid
28352 ** the fcntl call every time sync is called.
28354 if( rc ) rc = fsync(fd);
28356 #elif defined(__APPLE__)
28357 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
28358 ** so currently we default to the macro that redefines fdatasync to fsync
28360 rc = fsync(fd);
28361 #else
28362 rc = fdatasync(fd);
28363 #if OS_VXWORKS
28364 if( rc==-1 && errno==ENOTSUP ){
28365 rc = fsync(fd);
28367 #endif /* OS_VXWORKS */
28368 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
28370 if( OS_VXWORKS && rc!= -1 ){
28371 rc = 0;
28373 return rc;
28377 ** Open a file descriptor to the directory containing file zFilename.
28378 ** If successful, *pFd is set to the opened file descriptor and
28379 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
28380 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
28381 ** value.
28383 ** The directory file descriptor is used for only one thing - to
28384 ** fsync() a directory to make sure file creation and deletion events
28385 ** are flushed to disk. Such fsyncs are not needed on newer
28386 ** journaling filesystems, but are required on older filesystems.
28388 ** This routine can be overridden using the xSetSysCall interface.
28389 ** The ability to override this routine was added in support of the
28390 ** chromium sandbox. Opening a directory is a security risk (we are
28391 ** told) so making it overrideable allows the chromium sandbox to
28392 ** replace this routine with a harmless no-op. To make this routine
28393 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
28394 ** *pFd set to a negative number.
28396 ** If SQLITE_OK is returned, the caller is responsible for closing
28397 ** the file descriptor *pFd using close().
28399 static int openDirectory(const char *zFilename, int *pFd){
28400 int ii;
28401 int fd = -1;
28402 char zDirname[MAX_PATHNAME+1];
28404 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
28405 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
28406 if( ii>0 ){
28407 zDirname[ii] = '\0';
28408 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
28409 if( fd>=0 ){
28410 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
28413 *pFd = fd;
28414 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
28418 ** Make sure all writes to a particular file are committed to disk.
28420 ** If dataOnly==0 then both the file itself and its metadata (file
28421 ** size, access time, etc) are synced. If dataOnly!=0 then only the
28422 ** file data is synced.
28424 ** Under Unix, also make sure that the directory entry for the file
28425 ** has been created by fsync-ing the directory that contains the file.
28426 ** If we do not do this and we encounter a power failure, the directory
28427 ** entry for the journal might not exist after we reboot. The next
28428 ** SQLite to access the file will not know that the journal exists (because
28429 ** the directory entry for the journal was never created) and the transaction
28430 ** will not roll back - possibly leading to database corruption.
28432 static int unixSync(sqlite3_file *id, int flags){
28433 int rc;
28434 unixFile *pFile = (unixFile*)id;
28436 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
28437 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
28439 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
28440 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
28441 || (flags&0x0F)==SQLITE_SYNC_FULL
28444 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
28445 ** line is to test that doing so does not cause any problems.
28447 SimulateDiskfullError( return SQLITE_FULL );
28449 assert( pFile );
28450 OSTRACE(("SYNC %-3d\n", pFile->h));
28451 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
28452 SimulateIOError( rc=1 );
28453 if( rc ){
28454 pFile->lastErrno = errno;
28455 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
28458 /* Also fsync the directory containing the file if the DIRSYNC flag
28459 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
28460 ** are unable to fsync a directory, so ignore errors on the fsync.
28462 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
28463 int dirfd;
28464 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
28465 HAVE_FULLFSYNC, isFullsync));
28466 rc = osOpenDirectory(pFile->zPath, &dirfd);
28467 if( rc==SQLITE_OK && dirfd>=0 ){
28468 full_fsync(dirfd, 0, 0);
28469 robust_close(pFile, dirfd, __LINE__);
28470 }else if( rc==SQLITE_CANTOPEN ){
28471 rc = SQLITE_OK;
28473 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
28475 return rc;
28479 ** Truncate an open file to a specified size
28481 static int unixTruncate(sqlite3_file *id, i64 nByte){
28482 unixFile *pFile = (unixFile *)id;
28483 int rc;
28484 assert( pFile );
28485 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
28487 /* If the user has configured a chunk-size for this file, truncate the
28488 ** file so that it consists of an integer number of chunks (i.e. the
28489 ** actual file size after the operation may be larger than the requested
28490 ** size).
28492 if( pFile->szChunk>0 ){
28493 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
28496 rc = robust_ftruncate(pFile->h, nByte);
28497 if( rc ){
28498 pFile->lastErrno = errno;
28499 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28500 }else{
28501 #ifdef SQLITE_DEBUG
28502 /* If we are doing a normal write to a database file (as opposed to
28503 ** doing a hot-journal rollback or a write to some file other than a
28504 ** normal database file) and we truncate the file to zero length,
28505 ** that effectively updates the change counter. This might happen
28506 ** when restoring a database using the backup API from a zero-length
28507 ** source.
28509 if( pFile->inNormalWrite && nByte==0 ){
28510 pFile->transCntrChng = 1;
28512 #endif
28514 #if SQLITE_MAX_MMAP_SIZE>0
28515 /* If the file was just truncated to a size smaller than the currently
28516 ** mapped region, reduce the effective mapping size as well. SQLite will
28517 ** use read() and write() to access data beyond this point from now on.
28519 if( nByte<pFile->mmapSize ){
28520 pFile->mmapSize = nByte;
28522 #endif
28524 return SQLITE_OK;
28529 ** Determine the current size of a file in bytes
28531 static int unixFileSize(sqlite3_file *id, i64 *pSize){
28532 int rc;
28533 struct stat buf;
28534 assert( id );
28535 rc = osFstat(((unixFile*)id)->h, &buf);
28536 SimulateIOError( rc=1 );
28537 if( rc!=0 ){
28538 ((unixFile*)id)->lastErrno = errno;
28539 return SQLITE_IOERR_FSTAT;
28541 *pSize = buf.st_size;
28543 /* When opening a zero-size database, the findInodeInfo() procedure
28544 ** writes a single byte into that file in order to work around a bug
28545 ** in the OS-X msdos filesystem. In order to avoid problems with upper
28546 ** layers, we need to report this file size as zero even though it is
28547 ** really 1. Ticket #3260.
28549 if( *pSize==1 ) *pSize = 0;
28552 return SQLITE_OK;
28555 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28557 ** Handler for proxy-locking file-control verbs. Defined below in the
28558 ** proxying locking division.
28560 static int proxyFileControl(sqlite3_file*,int,void*);
28561 #endif
28564 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
28565 ** file-control operation. Enlarge the database to nBytes in size
28566 ** (rounded up to the next chunk-size). If the database is already
28567 ** nBytes or larger, this routine is a no-op.
28569 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
28570 if( pFile->szChunk>0 ){
28571 i64 nSize; /* Required file size */
28572 struct stat buf; /* Used to hold return values of fstat() */
28574 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
28576 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
28577 if( nSize>(i64)buf.st_size ){
28579 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
28580 /* The code below is handling the return value of osFallocate()
28581 ** correctly. posix_fallocate() is defined to "returns zero on success,
28582 ** or an error number on failure". See the manpage for details. */
28583 int err;
28585 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
28586 }while( err==EINTR );
28587 if( err ) return SQLITE_IOERR_WRITE;
28588 #else
28589 /* If the OS does not have posix_fallocate(), fake it. First use
28590 ** ftruncate() to set the file size, then write a single byte to
28591 ** the last byte in each block within the extended region. This
28592 ** is the same technique used by glibc to implement posix_fallocate()
28593 ** on systems that do not have a real fallocate() system call.
28595 int nBlk = buf.st_blksize; /* File-system block size */
28596 i64 iWrite; /* Next offset to write to */
28598 if( robust_ftruncate(pFile->h, nSize) ){
28599 pFile->lastErrno = errno;
28600 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28602 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
28603 while( iWrite<nSize ){
28604 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
28605 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
28606 iWrite += nBlk;
28608 #endif
28612 #if SQLITE_MAX_MMAP_SIZE>0
28613 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
28614 int rc;
28615 if( pFile->szChunk<=0 ){
28616 if( robust_ftruncate(pFile->h, nByte) ){
28617 pFile->lastErrno = errno;
28618 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28622 rc = unixMapfile(pFile, nByte);
28623 return rc;
28625 #endif
28627 return SQLITE_OK;
28631 ** If *pArg is initially negative then this is a query. Set *pArg to
28632 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
28634 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
28636 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
28637 if( *pArg<0 ){
28638 *pArg = (pFile->ctrlFlags & mask)!=0;
28639 }else if( (*pArg)==0 ){
28640 pFile->ctrlFlags &= ~mask;
28641 }else{
28642 pFile->ctrlFlags |= mask;
28646 /* Forward declaration */
28647 static int unixGetTempname(int nBuf, char *zBuf);
28650 ** Information and control of an open file handle.
28652 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
28653 unixFile *pFile = (unixFile*)id;
28654 switch( op ){
28655 case SQLITE_FCNTL_LOCKSTATE: {
28656 *(int*)pArg = pFile->eFileLock;
28657 return SQLITE_OK;
28659 case SQLITE_LAST_ERRNO: {
28660 *(int*)pArg = pFile->lastErrno;
28661 return SQLITE_OK;
28663 case SQLITE_FCNTL_CHUNK_SIZE: {
28664 pFile->szChunk = *(int *)pArg;
28665 return SQLITE_OK;
28667 case SQLITE_FCNTL_SIZE_HINT: {
28668 int rc;
28669 SimulateIOErrorBenign(1);
28670 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
28671 SimulateIOErrorBenign(0);
28672 return rc;
28674 case SQLITE_FCNTL_PERSIST_WAL: {
28675 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
28676 return SQLITE_OK;
28678 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
28679 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
28680 return SQLITE_OK;
28682 case SQLITE_FCNTL_VFSNAME: {
28683 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
28684 return SQLITE_OK;
28686 case SQLITE_FCNTL_TEMPFILENAME: {
28687 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
28688 if( zTFile ){
28689 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
28690 *(char**)pArg = zTFile;
28692 return SQLITE_OK;
28694 case SQLITE_FCNTL_HAS_MOVED: {
28695 *(int*)pArg = fileHasMoved(pFile);
28696 return SQLITE_OK;
28698 #if SQLITE_MAX_MMAP_SIZE>0
28699 case SQLITE_FCNTL_MMAP_SIZE: {
28700 i64 newLimit = *(i64*)pArg;
28701 int rc = SQLITE_OK;
28702 if( newLimit>sqlite3GlobalConfig.mxMmap ){
28703 newLimit = sqlite3GlobalConfig.mxMmap;
28705 *(i64*)pArg = pFile->mmapSizeMax;
28706 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
28707 pFile->mmapSizeMax = newLimit;
28708 if( pFile->mmapSize>0 ){
28709 unixUnmapfile(pFile);
28710 rc = unixMapfile(pFile, -1);
28713 return rc;
28715 #endif
28716 #ifdef SQLITE_DEBUG
28717 /* The pager calls this method to signal that it has done
28718 ** a rollback and that the database is therefore unchanged and
28719 ** it hence it is OK for the transaction change counter to be
28720 ** unchanged.
28722 case SQLITE_FCNTL_DB_UNCHANGED: {
28723 ((unixFile*)id)->dbUpdate = 0;
28724 return SQLITE_OK;
28726 #endif
28727 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28728 case SQLITE_SET_LOCKPROXYFILE:
28729 case SQLITE_GET_LOCKPROXYFILE: {
28730 return proxyFileControl(id,op,pArg);
28732 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
28734 return SQLITE_NOTFOUND;
28738 ** Return the sector size in bytes of the underlying block device for
28739 ** the specified file. This is almost always 512 bytes, but may be
28740 ** larger for some devices.
28742 ** SQLite code assumes this function cannot fail. It also assumes that
28743 ** if two files are created in the same file-system directory (i.e.
28744 ** a database and its journal file) that the sector size will be the
28745 ** same for both.
28747 #ifndef __QNXNTO__
28748 static int unixSectorSize(sqlite3_file *NotUsed){
28749 UNUSED_PARAMETER(NotUsed);
28750 return SQLITE_DEFAULT_SECTOR_SIZE;
28752 #endif
28755 ** The following version of unixSectorSize() is optimized for QNX.
28757 #ifdef __QNXNTO__
28758 #include <sys/dcmd_blk.h>
28759 #include <sys/statvfs.h>
28760 static int unixSectorSize(sqlite3_file *id){
28761 unixFile *pFile = (unixFile*)id;
28762 if( pFile->sectorSize == 0 ){
28763 struct statvfs fsInfo;
28765 /* Set defaults for non-supported filesystems */
28766 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
28767 pFile->deviceCharacteristics = 0;
28768 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
28769 return pFile->sectorSize;
28772 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
28773 pFile->sectorSize = fsInfo.f_bsize;
28774 pFile->deviceCharacteristics =
28775 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
28776 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
28777 ** the write succeeds */
28778 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
28779 ** so it is ordered */
28781 }else if( strstr(fsInfo.f_basetype, "etfs") ){
28782 pFile->sectorSize = fsInfo.f_bsize;
28783 pFile->deviceCharacteristics =
28784 /* etfs cluster size writes are atomic */
28785 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
28786 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
28787 ** the write succeeds */
28788 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
28789 ** so it is ordered */
28791 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
28792 pFile->sectorSize = fsInfo.f_bsize;
28793 pFile->deviceCharacteristics =
28794 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
28795 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
28796 ** the write succeeds */
28797 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
28798 ** so it is ordered */
28800 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
28801 pFile->sectorSize = fsInfo.f_bsize;
28802 pFile->deviceCharacteristics =
28803 /* full bitset of atomics from max sector size and smaller */
28804 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
28805 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
28806 ** so it is ordered */
28808 }else if( strstr(fsInfo.f_basetype, "dos") ){
28809 pFile->sectorSize = fsInfo.f_bsize;
28810 pFile->deviceCharacteristics =
28811 /* full bitset of atomics from max sector size and smaller */
28812 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
28813 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
28814 ** so it is ordered */
28816 }else{
28817 pFile->deviceCharacteristics =
28818 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
28819 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
28820 ** the write succeeds */
28824 /* Last chance verification. If the sector size isn't a multiple of 512
28825 ** then it isn't valid.*/
28826 if( pFile->sectorSize % 512 != 0 ){
28827 pFile->deviceCharacteristics = 0;
28828 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
28830 return pFile->sectorSize;
28832 #endif /* __QNXNTO__ */
28835 ** Return the device characteristics for the file.
28837 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
28838 ** However, that choice is controversial since technically the underlying
28839 ** file system does not always provide powersafe overwrites. (In other
28840 ** words, after a power-loss event, parts of the file that were never
28841 ** written might end up being altered.) However, non-PSOW behavior is very,
28842 ** very rare. And asserting PSOW makes a large reduction in the amount
28843 ** of required I/O for journaling, since a lot of padding is eliminated.
28844 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
28845 ** available to turn it off and URI query parameter available to turn it off.
28847 static int unixDeviceCharacteristics(sqlite3_file *id){
28848 unixFile *p = (unixFile*)id;
28849 int rc = 0;
28850 #ifdef __QNXNTO__
28851 if( p->sectorSize==0 ) unixSectorSize(id);
28852 rc = p->deviceCharacteristics;
28853 #endif
28854 if( p->ctrlFlags & UNIXFILE_PSOW ){
28855 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
28857 return rc;
28860 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
28863 ** Return the system page size.
28865 ** This function should not be called directly by other code in this file.
28866 ** Instead, it should be called via macro osGetpagesize().
28868 static int unixGetpagesize(void){
28869 #if defined(_BSD_SOURCE)
28870 return getpagesize();
28871 #else
28872 return (int)sysconf(_SC_PAGESIZE);
28873 #endif
28876 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
28878 #ifndef SQLITE_OMIT_WAL
28881 ** Object used to represent an shared memory buffer.
28883 ** When multiple threads all reference the same wal-index, each thread
28884 ** has its own unixShm object, but they all point to a single instance
28885 ** of this unixShmNode object. In other words, each wal-index is opened
28886 ** only once per process.
28888 ** Each unixShmNode object is connected to a single unixInodeInfo object.
28889 ** We could coalesce this object into unixInodeInfo, but that would mean
28890 ** every open file that does not use shared memory (in other words, most
28891 ** open files) would have to carry around this extra information. So
28892 ** the unixInodeInfo object contains a pointer to this unixShmNode object
28893 ** and the unixShmNode object is created only when needed.
28895 ** unixMutexHeld() must be true when creating or destroying
28896 ** this object or while reading or writing the following fields:
28898 ** nRef
28900 ** The following fields are read-only after the object is created:
28902 ** fid
28903 ** zFilename
28905 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
28906 ** unixMutexHeld() is true when reading or writing any other field
28907 ** in this structure.
28909 struct unixShmNode {
28910 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
28911 sqlite3_mutex *mutex; /* Mutex to access this object */
28912 char *zFilename; /* Name of the mmapped file */
28913 int h; /* Open file descriptor */
28914 int szRegion; /* Size of shared-memory regions */
28915 u16 nRegion; /* Size of array apRegion */
28916 u8 isReadonly; /* True if read-only */
28917 char **apRegion; /* Array of mapped shared-memory regions */
28918 int nRef; /* Number of unixShm objects pointing to this */
28919 unixShm *pFirst; /* All unixShm objects pointing to this */
28920 #ifdef SQLITE_DEBUG
28921 u8 exclMask; /* Mask of exclusive locks held */
28922 u8 sharedMask; /* Mask of shared locks held */
28923 u8 nextShmId; /* Next available unixShm.id value */
28924 #endif
28928 ** Structure used internally by this VFS to record the state of an
28929 ** open shared memory connection.
28931 ** The following fields are initialized when this object is created and
28932 ** are read-only thereafter:
28934 ** unixShm.pFile
28935 ** unixShm.id
28937 ** All other fields are read/write. The unixShm.pFile->mutex must be held
28938 ** while accessing any read/write fields.
28940 struct unixShm {
28941 unixShmNode *pShmNode; /* The underlying unixShmNode object */
28942 unixShm *pNext; /* Next unixShm with the same unixShmNode */
28943 u8 hasMutex; /* True if holding the unixShmNode mutex */
28944 u8 id; /* Id of this connection within its unixShmNode */
28945 u16 sharedMask; /* Mask of shared locks held */
28946 u16 exclMask; /* Mask of exclusive locks held */
28950 ** Constants used for locking
28952 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
28953 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
28956 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
28958 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
28959 ** otherwise.
28961 static int unixShmSystemLock(
28962 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
28963 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
28964 int ofst, /* First byte of the locking range */
28965 int n /* Number of bytes to lock */
28967 struct flock f; /* The posix advisory locking structure */
28968 int rc = SQLITE_OK; /* Result code form fcntl() */
28970 /* Access to the unixShmNode object is serialized by the caller */
28971 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
28973 /* Shared locks never span more than one byte */
28974 assert( n==1 || lockType!=F_RDLCK );
28976 /* Locks are within range */
28977 assert( n>=1 && n<SQLITE_SHM_NLOCK );
28979 if( pShmNode->h>=0 ){
28980 /* Initialize the locking parameters */
28981 memset(&f, 0, sizeof(f));
28982 f.l_type = lockType;
28983 f.l_whence = SEEK_SET;
28984 f.l_start = ofst;
28985 f.l_len = n;
28987 rc = osFcntl(pShmNode->h, F_SETLK, &f);
28988 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
28991 /* Update the global lock state and do debug tracing */
28992 #ifdef SQLITE_DEBUG
28993 { u16 mask;
28994 OSTRACE(("SHM-LOCK "));
28995 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
28996 if( rc==SQLITE_OK ){
28997 if( lockType==F_UNLCK ){
28998 OSTRACE(("unlock %d ok", ofst));
28999 pShmNode->exclMask &= ~mask;
29000 pShmNode->sharedMask &= ~mask;
29001 }else if( lockType==F_RDLCK ){
29002 OSTRACE(("read-lock %d ok", ofst));
29003 pShmNode->exclMask &= ~mask;
29004 pShmNode->sharedMask |= mask;
29005 }else{
29006 assert( lockType==F_WRLCK );
29007 OSTRACE(("write-lock %d ok", ofst));
29008 pShmNode->exclMask |= mask;
29009 pShmNode->sharedMask &= ~mask;
29011 }else{
29012 if( lockType==F_UNLCK ){
29013 OSTRACE(("unlock %d failed", ofst));
29014 }else if( lockType==F_RDLCK ){
29015 OSTRACE(("read-lock failed"));
29016 }else{
29017 assert( lockType==F_WRLCK );
29018 OSTRACE(("write-lock %d failed", ofst));
29021 OSTRACE((" - afterwards %03x,%03x\n",
29022 pShmNode->sharedMask, pShmNode->exclMask));
29024 #endif
29026 return rc;
29030 ** Return the minimum number of 32KB shm regions that should be mapped at
29031 ** a time, assuming that each mapping must be an integer multiple of the
29032 ** current system page-size.
29034 ** Usually, this is 1. The exception seems to be systems that are configured
29035 ** to use 64KB pages - in this case each mapping must cover at least two
29036 ** shm regions.
29038 static int unixShmRegionPerMap(void){
29039 int shmsz = 32*1024; /* SHM region size */
29040 int pgsz = osGetpagesize(); /* System page size */
29041 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
29042 if( pgsz<shmsz ) return 1;
29043 return pgsz/shmsz;
29047 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
29049 ** This is not a VFS shared-memory method; it is a utility function called
29050 ** by VFS shared-memory methods.
29052 static void unixShmPurge(unixFile *pFd){
29053 unixShmNode *p = pFd->pInode->pShmNode;
29054 assert( unixMutexHeld() );
29055 if( p && p->nRef==0 ){
29056 int nShmPerMap = unixShmRegionPerMap();
29057 int i;
29058 assert( p->pInode==pFd->pInode );
29059 sqlite3_mutex_free(p->mutex);
29060 for(i=0; i<p->nRegion; i+=nShmPerMap){
29061 if( p->h>=0 ){
29062 osMunmap(p->apRegion[i], p->szRegion);
29063 }else{
29064 sqlite3_free(p->apRegion[i]);
29067 sqlite3_free(p->apRegion);
29068 if( p->h>=0 ){
29069 robust_close(pFd, p->h, __LINE__);
29070 p->h = -1;
29072 p->pInode->pShmNode = 0;
29073 sqlite3_free(p);
29078 ** Open a shared-memory area associated with open database file pDbFd.
29079 ** This particular implementation uses mmapped files.
29081 ** The file used to implement shared-memory is in the same directory
29082 ** as the open database file and has the same name as the open database
29083 ** file with the "-shm" suffix added. For example, if the database file
29084 ** is "/home/user1/config.db" then the file that is created and mmapped
29085 ** for shared memory will be called "/home/user1/config.db-shm".
29087 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
29088 ** some other tmpfs mount. But if a file in a different directory
29089 ** from the database file is used, then differing access permissions
29090 ** or a chroot() might cause two different processes on the same
29091 ** database to end up using different files for shared memory -
29092 ** meaning that their memory would not really be shared - resulting
29093 ** in database corruption. Nevertheless, this tmpfs file usage
29094 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
29095 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
29096 ** option results in an incompatible build of SQLite; builds of SQLite
29097 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
29098 ** same database file at the same time, database corruption will likely
29099 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
29100 ** "unsupported" and may go away in a future SQLite release.
29102 ** When opening a new shared-memory file, if no other instances of that
29103 ** file are currently open, in this process or in other processes, then
29104 ** the file must be truncated to zero length or have its header cleared.
29106 ** If the original database file (pDbFd) is using the "unix-excl" VFS
29107 ** that means that an exclusive lock is held on the database file and
29108 ** that no other processes are able to read or write the database. In
29109 ** that case, we do not really need shared memory. No shared memory
29110 ** file is created. The shared memory will be simulated with heap memory.
29112 static int unixOpenSharedMemory(unixFile *pDbFd){
29113 struct unixShm *p = 0; /* The connection to be opened */
29114 struct unixShmNode *pShmNode; /* The underlying mmapped file */
29115 int rc; /* Result code */
29116 unixInodeInfo *pInode; /* The inode of fd */
29117 char *zShmFilename; /* Name of the file used for SHM */
29118 int nShmFilename; /* Size of the SHM filename in bytes */
29120 /* Allocate space for the new unixShm object. */
29121 p = sqlite3_malloc( sizeof(*p) );
29122 if( p==0 ) return SQLITE_NOMEM;
29123 memset(p, 0, sizeof(*p));
29124 assert( pDbFd->pShm==0 );
29126 /* Check to see if a unixShmNode object already exists. Reuse an existing
29127 ** one if present. Create a new one if necessary.
29129 unixEnterMutex();
29130 pInode = pDbFd->pInode;
29131 pShmNode = pInode->pShmNode;
29132 if( pShmNode==0 ){
29133 struct stat sStat; /* fstat() info for database file */
29135 /* Call fstat() to figure out the permissions on the database file. If
29136 ** a new *-shm file is created, an attempt will be made to create it
29137 ** with the same permissions.
29139 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
29140 rc = SQLITE_IOERR_FSTAT;
29141 goto shm_open_err;
29144 #ifdef SQLITE_SHM_DIRECTORY
29145 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
29146 #else
29147 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
29148 #endif
29149 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
29150 if( pShmNode==0 ){
29151 rc = SQLITE_NOMEM;
29152 goto shm_open_err;
29154 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
29155 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
29156 #ifdef SQLITE_SHM_DIRECTORY
29157 sqlite3_snprintf(nShmFilename, zShmFilename,
29158 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
29159 (u32)sStat.st_ino, (u32)sStat.st_dev);
29160 #else
29161 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
29162 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
29163 #endif
29164 pShmNode->h = -1;
29165 pDbFd->pInode->pShmNode = pShmNode;
29166 pShmNode->pInode = pDbFd->pInode;
29167 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
29168 if( pShmNode->mutex==0 ){
29169 rc = SQLITE_NOMEM;
29170 goto shm_open_err;
29173 if( pInode->bProcessLock==0 ){
29174 int openFlags = O_RDWR | O_CREAT;
29175 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
29176 openFlags = O_RDONLY;
29177 pShmNode->isReadonly = 1;
29179 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
29180 if( pShmNode->h<0 ){
29181 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
29182 goto shm_open_err;
29185 /* If this process is running as root, make sure that the SHM file
29186 ** is owned by the same user that owns the original database. Otherwise,
29187 ** the original owner will not be able to connect.
29189 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
29191 /* Check to see if another process is holding the dead-man switch.
29192 ** If not, truncate the file to zero length.
29194 rc = SQLITE_OK;
29195 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
29196 if( robust_ftruncate(pShmNode->h, 0) ){
29197 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
29200 if( rc==SQLITE_OK ){
29201 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
29203 if( rc ) goto shm_open_err;
29207 /* Make the new connection a child of the unixShmNode */
29208 p->pShmNode = pShmNode;
29209 #ifdef SQLITE_DEBUG
29210 p->id = pShmNode->nextShmId++;
29211 #endif
29212 pShmNode->nRef++;
29213 pDbFd->pShm = p;
29214 unixLeaveMutex();
29216 /* The reference count on pShmNode has already been incremented under
29217 ** the cover of the unixEnterMutex() mutex and the pointer from the
29218 ** new (struct unixShm) object to the pShmNode has been set. All that is
29219 ** left to do is to link the new object into the linked list starting
29220 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
29221 ** mutex.
29223 sqlite3_mutex_enter(pShmNode->mutex);
29224 p->pNext = pShmNode->pFirst;
29225 pShmNode->pFirst = p;
29226 sqlite3_mutex_leave(pShmNode->mutex);
29227 return SQLITE_OK;
29229 /* Jump here on any error */
29230 shm_open_err:
29231 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
29232 sqlite3_free(p);
29233 unixLeaveMutex();
29234 return rc;
29238 ** This function is called to obtain a pointer to region iRegion of the
29239 ** shared-memory associated with the database file fd. Shared-memory regions
29240 ** are numbered starting from zero. Each shared-memory region is szRegion
29241 ** bytes in size.
29243 ** If an error occurs, an error code is returned and *pp is set to NULL.
29245 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
29246 ** region has not been allocated (by any client, including one running in a
29247 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
29248 ** bExtend is non-zero and the requested shared-memory region has not yet
29249 ** been allocated, it is allocated by this function.
29251 ** If the shared-memory region has already been allocated or is allocated by
29252 ** this call as described above, then it is mapped into this processes
29253 ** address space (if it is not already), *pp is set to point to the mapped
29254 ** memory and SQLITE_OK returned.
29256 static int unixShmMap(
29257 sqlite3_file *fd, /* Handle open on database file */
29258 int iRegion, /* Region to retrieve */
29259 int szRegion, /* Size of regions */
29260 int bExtend, /* True to extend file if necessary */
29261 void volatile **pp /* OUT: Mapped memory */
29263 unixFile *pDbFd = (unixFile*)fd;
29264 unixShm *p;
29265 unixShmNode *pShmNode;
29266 int rc = SQLITE_OK;
29267 int nShmPerMap = unixShmRegionPerMap();
29268 int nReqRegion;
29270 /* If the shared-memory file has not yet been opened, open it now. */
29271 if( pDbFd->pShm==0 ){
29272 rc = unixOpenSharedMemory(pDbFd);
29273 if( rc!=SQLITE_OK ) return rc;
29276 p = pDbFd->pShm;
29277 pShmNode = p->pShmNode;
29278 sqlite3_mutex_enter(pShmNode->mutex);
29279 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
29280 assert( pShmNode->pInode==pDbFd->pInode );
29281 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
29282 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
29284 /* Minimum number of regions required to be mapped. */
29285 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
29287 if( pShmNode->nRegion<nReqRegion ){
29288 char **apNew; /* New apRegion[] array */
29289 int nByte = nReqRegion*szRegion; /* Minimum required file size */
29290 struct stat sStat; /* Used by fstat() */
29292 pShmNode->szRegion = szRegion;
29294 if( pShmNode->h>=0 ){
29295 /* The requested region is not mapped into this processes address space.
29296 ** Check to see if it has been allocated (i.e. if the wal-index file is
29297 ** large enough to contain the requested region).
29299 if( osFstat(pShmNode->h, &sStat) ){
29300 rc = SQLITE_IOERR_SHMSIZE;
29301 goto shmpage_out;
29304 if( sStat.st_size<nByte ){
29305 /* The requested memory region does not exist. If bExtend is set to
29306 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
29308 if( !bExtend ){
29309 goto shmpage_out;
29312 /* Alternatively, if bExtend is true, extend the file. Do this by
29313 ** writing a single byte to the end of each (OS) page being
29314 ** allocated or extended. Technically, we need only write to the
29315 ** last page in order to extend the file. But writing to all new
29316 ** pages forces the OS to allocate them immediately, which reduces
29317 ** the chances of SIGBUS while accessing the mapped region later on.
29319 else{
29320 static const int pgsz = 4096;
29321 int iPg;
29323 /* Write to the last byte of each newly allocated or extended page */
29324 assert( (nByte % pgsz)==0 );
29325 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
29326 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
29327 const char *zFile = pShmNode->zFilename;
29328 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
29329 goto shmpage_out;
29336 /* Map the requested memory region into this processes address space. */
29337 apNew = (char **)sqlite3_realloc(
29338 pShmNode->apRegion, nReqRegion*sizeof(char *)
29340 if( !apNew ){
29341 rc = SQLITE_IOERR_NOMEM;
29342 goto shmpage_out;
29344 pShmNode->apRegion = apNew;
29345 while( pShmNode->nRegion<nReqRegion ){
29346 int nMap = szRegion*nShmPerMap;
29347 int i;
29348 void *pMem;
29349 if( pShmNode->h>=0 ){
29350 pMem = osMmap(0, nMap,
29351 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
29352 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
29354 if( pMem==MAP_FAILED ){
29355 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
29356 goto shmpage_out;
29358 }else{
29359 pMem = sqlite3_malloc(szRegion);
29360 if( pMem==0 ){
29361 rc = SQLITE_NOMEM;
29362 goto shmpage_out;
29364 memset(pMem, 0, szRegion);
29367 for(i=0; i<nShmPerMap; i++){
29368 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
29370 pShmNode->nRegion += nShmPerMap;
29374 shmpage_out:
29375 if( pShmNode->nRegion>iRegion ){
29376 *pp = pShmNode->apRegion[iRegion];
29377 }else{
29378 *pp = 0;
29380 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
29381 sqlite3_mutex_leave(pShmNode->mutex);
29382 return rc;
29386 ** Change the lock state for a shared-memory segment.
29388 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
29389 ** different here than in posix. In xShmLock(), one can go from unlocked
29390 ** to shared and back or from unlocked to exclusive and back. But one may
29391 ** not go from shared to exclusive or from exclusive to shared.
29393 static int unixShmLock(
29394 sqlite3_file *fd, /* Database file holding the shared memory */
29395 int ofst, /* First lock to acquire or release */
29396 int n, /* Number of locks to acquire or release */
29397 int flags /* What to do with the lock */
29399 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
29400 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
29401 unixShm *pX; /* For looping over all siblings */
29402 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
29403 int rc = SQLITE_OK; /* Result code */
29404 u16 mask; /* Mask of locks to take or release */
29406 assert( pShmNode==pDbFd->pInode->pShmNode );
29407 assert( pShmNode->pInode==pDbFd->pInode );
29408 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
29409 assert( n>=1 );
29410 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
29411 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
29412 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
29413 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
29414 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
29415 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
29416 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
29418 mask = (1<<(ofst+n)) - (1<<ofst);
29419 assert( n>1 || mask==(1<<ofst) );
29420 sqlite3_mutex_enter(pShmNode->mutex);
29421 if( flags & SQLITE_SHM_UNLOCK ){
29422 u16 allMask = 0; /* Mask of locks held by siblings */
29424 /* See if any siblings hold this same lock */
29425 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29426 if( pX==p ) continue;
29427 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
29428 allMask |= pX->sharedMask;
29431 /* Unlock the system-level locks */
29432 if( (mask & allMask)==0 ){
29433 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
29434 }else{
29435 rc = SQLITE_OK;
29438 /* Undo the local locks */
29439 if( rc==SQLITE_OK ){
29440 p->exclMask &= ~mask;
29441 p->sharedMask &= ~mask;
29443 }else if( flags & SQLITE_SHM_SHARED ){
29444 u16 allShared = 0; /* Union of locks held by connections other than "p" */
29446 /* Find out which shared locks are already held by sibling connections.
29447 ** If any sibling already holds an exclusive lock, go ahead and return
29448 ** SQLITE_BUSY.
29450 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29451 if( (pX->exclMask & mask)!=0 ){
29452 rc = SQLITE_BUSY;
29453 break;
29455 allShared |= pX->sharedMask;
29458 /* Get shared locks at the system level, if necessary */
29459 if( rc==SQLITE_OK ){
29460 if( (allShared & mask)==0 ){
29461 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
29462 }else{
29463 rc = SQLITE_OK;
29467 /* Get the local shared locks */
29468 if( rc==SQLITE_OK ){
29469 p->sharedMask |= mask;
29471 }else{
29472 /* Make sure no sibling connections hold locks that will block this
29473 ** lock. If any do, return SQLITE_BUSY right away.
29475 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29476 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
29477 rc = SQLITE_BUSY;
29478 break;
29482 /* Get the exclusive locks at the system level. Then if successful
29483 ** also mark the local connection as being locked.
29485 if( rc==SQLITE_OK ){
29486 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
29487 if( rc==SQLITE_OK ){
29488 assert( (p->sharedMask & mask)==0 );
29489 p->exclMask |= mask;
29493 sqlite3_mutex_leave(pShmNode->mutex);
29494 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
29495 p->id, getpid(), p->sharedMask, p->exclMask));
29496 return rc;
29500 ** Implement a memory barrier or memory fence on shared memory.
29502 ** All loads and stores begun before the barrier must complete before
29503 ** any load or store begun after the barrier.
29505 static void unixShmBarrier(
29506 sqlite3_file *fd /* Database file holding the shared memory */
29508 UNUSED_PARAMETER(fd);
29509 unixEnterMutex();
29510 unixLeaveMutex();
29514 ** Close a connection to shared-memory. Delete the underlying
29515 ** storage if deleteFlag is true.
29517 ** If there is no shared memory associated with the connection then this
29518 ** routine is a harmless no-op.
29520 static int unixShmUnmap(
29521 sqlite3_file *fd, /* The underlying database file */
29522 int deleteFlag /* Delete shared-memory if true */
29524 unixShm *p; /* The connection to be closed */
29525 unixShmNode *pShmNode; /* The underlying shared-memory file */
29526 unixShm **pp; /* For looping over sibling connections */
29527 unixFile *pDbFd; /* The underlying database file */
29529 pDbFd = (unixFile*)fd;
29530 p = pDbFd->pShm;
29531 if( p==0 ) return SQLITE_OK;
29532 pShmNode = p->pShmNode;
29534 assert( pShmNode==pDbFd->pInode->pShmNode );
29535 assert( pShmNode->pInode==pDbFd->pInode );
29537 /* Remove connection p from the set of connections associated
29538 ** with pShmNode */
29539 sqlite3_mutex_enter(pShmNode->mutex);
29540 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
29541 *pp = p->pNext;
29543 /* Free the connection p */
29544 sqlite3_free(p);
29545 pDbFd->pShm = 0;
29546 sqlite3_mutex_leave(pShmNode->mutex);
29548 /* If pShmNode->nRef has reached 0, then close the underlying
29549 ** shared-memory file, too */
29550 unixEnterMutex();
29551 assert( pShmNode->nRef>0 );
29552 pShmNode->nRef--;
29553 if( pShmNode->nRef==0 ){
29554 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
29555 unixShmPurge(pDbFd);
29557 unixLeaveMutex();
29559 return SQLITE_OK;
29563 #else
29564 # define unixShmMap 0
29565 # define unixShmLock 0
29566 # define unixShmBarrier 0
29567 # define unixShmUnmap 0
29568 #endif /* #ifndef SQLITE_OMIT_WAL */
29570 #if SQLITE_MAX_MMAP_SIZE>0
29572 ** If it is currently memory mapped, unmap file pFd.
29574 static void unixUnmapfile(unixFile *pFd){
29575 assert( pFd->nFetchOut==0 );
29576 if( pFd->pMapRegion ){
29577 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
29578 pFd->pMapRegion = 0;
29579 pFd->mmapSize = 0;
29580 pFd->mmapSizeActual = 0;
29585 ** Attempt to set the size of the memory mapping maintained by file
29586 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
29588 ** If successful, this function sets the following variables:
29590 ** unixFile.pMapRegion
29591 ** unixFile.mmapSize
29592 ** unixFile.mmapSizeActual
29594 ** If unsuccessful, an error message is logged via sqlite3_log() and
29595 ** the three variables above are zeroed. In this case SQLite should
29596 ** continue accessing the database using the xRead() and xWrite()
29597 ** methods.
29599 static void unixRemapfile(
29600 unixFile *pFd, /* File descriptor object */
29601 i64 nNew /* Required mapping size */
29603 const char *zErr = "mmap";
29604 int h = pFd->h; /* File descriptor open on db file */
29605 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
29606 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
29607 u8 *pNew = 0; /* Location of new mapping */
29608 int flags = PROT_READ; /* Flags to pass to mmap() */
29610 assert( pFd->nFetchOut==0 );
29611 assert( nNew>pFd->mmapSize );
29612 assert( nNew<=pFd->mmapSizeMax );
29613 assert( nNew>0 );
29614 assert( pFd->mmapSizeActual>=pFd->mmapSize );
29615 assert( MAP_FAILED!=0 );
29617 #if !SQLITE_MMAP_READ_ONLY
29618 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
29619 #endif
29621 if( pOrig ){
29622 #if HAVE_MREMAP
29623 i64 nReuse = pFd->mmapSize;
29624 #else
29625 const int szSyspage = osGetpagesize();
29626 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
29627 #endif
29628 u8 *pReq = &pOrig[nReuse];
29630 /* Unmap any pages of the existing mapping that cannot be reused. */
29631 if( nReuse!=nOrig ){
29632 osMunmap(pReq, nOrig-nReuse);
29635 #if HAVE_MREMAP
29636 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
29637 zErr = "mremap";
29638 #else
29639 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
29640 if( pNew!=MAP_FAILED ){
29641 if( pNew!=pReq ){
29642 osMunmap(pNew, nNew - nReuse);
29643 pNew = 0;
29644 }else{
29645 pNew = pOrig;
29648 #endif
29650 /* The attempt to extend the existing mapping failed. Free it. */
29651 if( pNew==MAP_FAILED || pNew==0 ){
29652 osMunmap(pOrig, nReuse);
29656 /* If pNew is still NULL, try to create an entirely new mapping. */
29657 if( pNew==0 ){
29658 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
29661 if( pNew==MAP_FAILED ){
29662 pNew = 0;
29663 nNew = 0;
29664 unixLogError(SQLITE_OK, zErr, pFd->zPath);
29666 /* If the mmap() above failed, assume that all subsequent mmap() calls
29667 ** will probably fail too. Fall back to using xRead/xWrite exclusively
29668 ** in this case. */
29669 pFd->mmapSizeMax = 0;
29671 pFd->pMapRegion = (void *)pNew;
29672 pFd->mmapSize = pFd->mmapSizeActual = nNew;
29676 ** Memory map or remap the file opened by file-descriptor pFd (if the file
29677 ** is already mapped, the existing mapping is replaced by the new). Or, if
29678 ** there already exists a mapping for this file, and there are still
29679 ** outstanding xFetch() references to it, this function is a no-op.
29681 ** If parameter nByte is non-negative, then it is the requested size of
29682 ** the mapping to create. Otherwise, if nByte is less than zero, then the
29683 ** requested size is the size of the file on disk. The actual size of the
29684 ** created mapping is either the requested size or the value configured
29685 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
29687 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
29688 ** recreated as a result of outstanding references) or an SQLite error
29689 ** code otherwise.
29691 static int unixMapfile(unixFile *pFd, i64 nByte){
29692 i64 nMap = nByte;
29693 int rc;
29695 assert( nMap>=0 || pFd->nFetchOut==0 );
29696 if( pFd->nFetchOut>0 ) return SQLITE_OK;
29698 if( nMap<0 ){
29699 struct stat statbuf; /* Low-level file information */
29700 rc = osFstat(pFd->h, &statbuf);
29701 if( rc!=SQLITE_OK ){
29702 return SQLITE_IOERR_FSTAT;
29704 nMap = statbuf.st_size;
29706 if( nMap>pFd->mmapSizeMax ){
29707 nMap = pFd->mmapSizeMax;
29710 if( nMap!=pFd->mmapSize ){
29711 if( nMap>0 ){
29712 unixRemapfile(pFd, nMap);
29713 }else{
29714 unixUnmapfile(pFd);
29718 return SQLITE_OK;
29720 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
29723 ** If possible, return a pointer to a mapping of file fd starting at offset
29724 ** iOff. The mapping must be valid for at least nAmt bytes.
29726 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
29727 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
29728 ** Finally, if an error does occur, return an SQLite error code. The final
29729 ** value of *pp is undefined in this case.
29731 ** If this function does return a pointer, the caller must eventually
29732 ** release the reference by calling unixUnfetch().
29734 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
29735 #if SQLITE_MAX_MMAP_SIZE>0
29736 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
29737 #endif
29738 *pp = 0;
29740 #if SQLITE_MAX_MMAP_SIZE>0
29741 if( pFd->mmapSizeMax>0 ){
29742 if( pFd->pMapRegion==0 ){
29743 int rc = unixMapfile(pFd, -1);
29744 if( rc!=SQLITE_OK ) return rc;
29746 if( pFd->mmapSize >= iOff+nAmt ){
29747 *pp = &((u8 *)pFd->pMapRegion)[iOff];
29748 pFd->nFetchOut++;
29751 #endif
29752 return SQLITE_OK;
29756 ** If the third argument is non-NULL, then this function releases a
29757 ** reference obtained by an earlier call to unixFetch(). The second
29758 ** argument passed to this function must be the same as the corresponding
29759 ** argument that was passed to the unixFetch() invocation.
29761 ** Or, if the third argument is NULL, then this function is being called
29762 ** to inform the VFS layer that, according to POSIX, any existing mapping
29763 ** may now be invalid and should be unmapped.
29765 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
29766 #if SQLITE_MAX_MMAP_SIZE>0
29767 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
29768 UNUSED_PARAMETER(iOff);
29770 /* If p==0 (unmap the entire file) then there must be no outstanding
29771 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
29772 ** then there must be at least one outstanding. */
29773 assert( (p==0)==(pFd->nFetchOut==0) );
29775 /* If p!=0, it must match the iOff value. */
29776 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
29778 if( p ){
29779 pFd->nFetchOut--;
29780 }else{
29781 unixUnmapfile(pFd);
29784 assert( pFd->nFetchOut>=0 );
29785 #else
29786 UNUSED_PARAMETER(fd);
29787 UNUSED_PARAMETER(p);
29788 UNUSED_PARAMETER(iOff);
29789 #endif
29790 return SQLITE_OK;
29794 ** Here ends the implementation of all sqlite3_file methods.
29796 ********************** End sqlite3_file Methods *******************************
29797 ******************************************************************************/
29800 ** This division contains definitions of sqlite3_io_methods objects that
29801 ** implement various file locking strategies. It also contains definitions
29802 ** of "finder" functions. A finder-function is used to locate the appropriate
29803 ** sqlite3_io_methods object for a particular database file. The pAppData
29804 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
29805 ** the correct finder-function for that VFS.
29807 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
29808 ** object. The only interesting finder-function is autolockIoFinder, which
29809 ** looks at the filesystem type and tries to guess the best locking
29810 ** strategy from that.
29812 ** For finder-function F, two objects are created:
29814 ** (1) The real finder-function named "FImpt()".
29816 ** (2) A constant pointer to this function named just "F".
29819 ** A pointer to the F pointer is used as the pAppData value for VFS
29820 ** objects. We have to do this instead of letting pAppData point
29821 ** directly at the finder-function since C90 rules prevent a void*
29822 ** from be cast into a function pointer.
29825 ** Each instance of this macro generates two objects:
29827 ** * A constant sqlite3_io_methods object call METHOD that has locking
29828 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
29830 ** * An I/O method finder function called FINDER that returns a pointer
29831 ** to the METHOD object in the previous bullet.
29833 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK, SHMMAP) \
29834 static const sqlite3_io_methods METHOD = { \
29835 VERSION, /* iVersion */ \
29836 CLOSE, /* xClose */ \
29837 unixRead, /* xRead */ \
29838 unixWrite, /* xWrite */ \
29839 unixTruncate, /* xTruncate */ \
29840 unixSync, /* xSync */ \
29841 unixFileSize, /* xFileSize */ \
29842 LOCK, /* xLock */ \
29843 UNLOCK, /* xUnlock */ \
29844 CKLOCK, /* xCheckReservedLock */ \
29845 unixFileControl, /* xFileControl */ \
29846 unixSectorSize, /* xSectorSize */ \
29847 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
29848 SHMMAP, /* xShmMap */ \
29849 unixShmLock, /* xShmLock */ \
29850 unixShmBarrier, /* xShmBarrier */ \
29851 unixShmUnmap, /* xShmUnmap */ \
29852 unixFetch, /* xFetch */ \
29853 unixUnfetch, /* xUnfetch */ \
29854 }; \
29855 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
29856 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
29857 return &METHOD; \
29859 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
29860 = FINDER##Impl;
29863 ** Here are all of the sqlite3_io_methods objects for each of the
29864 ** locking strategies. Functions that return pointers to these methods
29865 ** are also created.
29867 IOMETHODS(
29868 posixIoFinder, /* Finder function name */
29869 posixIoMethods, /* sqlite3_io_methods object name */
29870 3, /* shared memory and mmap are enabled */
29871 unixClose, /* xClose method */
29872 unixLock, /* xLock method */
29873 unixUnlock, /* xUnlock method */
29874 unixCheckReservedLock, /* xCheckReservedLock method */
29875 unixShmMap /* xShmMap method */
29877 IOMETHODS(
29878 nolockIoFinder, /* Finder function name */
29879 nolockIoMethods, /* sqlite3_io_methods object name */
29880 3, /* shared memory is disabled */
29881 nolockClose, /* xClose method */
29882 nolockLock, /* xLock method */
29883 nolockUnlock, /* xUnlock method */
29884 nolockCheckReservedLock, /* xCheckReservedLock method */
29885 0 /* xShmMap method */
29887 IOMETHODS(
29888 dotlockIoFinder, /* Finder function name */
29889 dotlockIoMethods, /* sqlite3_io_methods object name */
29890 1, /* shared memory is disabled */
29891 dotlockClose, /* xClose method */
29892 dotlockLock, /* xLock method */
29893 dotlockUnlock, /* xUnlock method */
29894 dotlockCheckReservedLock, /* xCheckReservedLock method */
29895 0 /* xShmMap method */
29898 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
29899 IOMETHODS(
29900 flockIoFinder, /* Finder function name */
29901 flockIoMethods, /* sqlite3_io_methods object name */
29902 1, /* shared memory is disabled */
29903 flockClose, /* xClose method */
29904 flockLock, /* xLock method */
29905 flockUnlock, /* xUnlock method */
29906 flockCheckReservedLock, /* xCheckReservedLock method */
29907 0 /* xShmMap method */
29909 #endif
29911 #if OS_VXWORKS
29912 IOMETHODS(
29913 semIoFinder, /* Finder function name */
29914 semIoMethods, /* sqlite3_io_methods object name */
29915 1, /* shared memory is disabled */
29916 semClose, /* xClose method */
29917 semLock, /* xLock method */
29918 semUnlock, /* xUnlock method */
29919 semCheckReservedLock, /* xCheckReservedLock method */
29920 0 /* xShmMap method */
29922 #endif
29924 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29925 IOMETHODS(
29926 afpIoFinder, /* Finder function name */
29927 afpIoMethods, /* sqlite3_io_methods object name */
29928 1, /* shared memory is disabled */
29929 afpClose, /* xClose method */
29930 afpLock, /* xLock method */
29931 afpUnlock, /* xUnlock method */
29932 afpCheckReservedLock, /* xCheckReservedLock method */
29933 0 /* xShmMap method */
29935 #endif
29938 ** The proxy locking method is a "super-method" in the sense that it
29939 ** opens secondary file descriptors for the conch and lock files and
29940 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
29941 ** secondary files. For this reason, the division that implements
29942 ** proxy locking is located much further down in the file. But we need
29943 ** to go ahead and define the sqlite3_io_methods and finder function
29944 ** for proxy locking here. So we forward declare the I/O methods.
29946 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29947 static int proxyClose(sqlite3_file*);
29948 static int proxyLock(sqlite3_file*, int);
29949 static int proxyUnlock(sqlite3_file*, int);
29950 static int proxyCheckReservedLock(sqlite3_file*, int*);
29951 IOMETHODS(
29952 proxyIoFinder, /* Finder function name */
29953 proxyIoMethods, /* sqlite3_io_methods object name */
29954 1, /* shared memory is disabled */
29955 proxyClose, /* xClose method */
29956 proxyLock, /* xLock method */
29957 proxyUnlock, /* xUnlock method */
29958 proxyCheckReservedLock, /* xCheckReservedLock method */
29959 0 /* xShmMap method */
29961 #endif
29963 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
29964 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29965 IOMETHODS(
29966 nfsIoFinder, /* Finder function name */
29967 nfsIoMethods, /* sqlite3_io_methods object name */
29968 1, /* shared memory is disabled */
29969 unixClose, /* xClose method */
29970 unixLock, /* xLock method */
29971 nfsUnlock, /* xUnlock method */
29972 unixCheckReservedLock, /* xCheckReservedLock method */
29973 0 /* xShmMap method */
29975 #endif
29977 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29979 ** This "finder" function attempts to determine the best locking strategy
29980 ** for the database file "filePath". It then returns the sqlite3_io_methods
29981 ** object that implements that strategy.
29983 ** This is for MacOSX only.
29985 static const sqlite3_io_methods *autolockIoFinderImpl(
29986 const char *filePath, /* name of the database file */
29987 unixFile *pNew /* open file object for the database file */
29989 static const struct Mapping {
29990 const char *zFilesystem; /* Filesystem type name */
29991 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
29992 } aMap[] = {
29993 { "hfs", &posixIoMethods },
29994 { "ufs", &posixIoMethods },
29995 { "afpfs", &afpIoMethods },
29996 { "smbfs", &afpIoMethods },
29997 { "webdav", &nolockIoMethods },
29998 { 0, 0 }
30000 int i;
30001 struct statfs fsInfo;
30002 struct flock lockInfo;
30004 if( !filePath ){
30005 /* If filePath==NULL that means we are dealing with a transient file
30006 ** that does not need to be locked. */
30007 return &nolockIoMethods;
30009 if( statfs(filePath, &fsInfo) != -1 ){
30010 if( fsInfo.f_flags & MNT_RDONLY ){
30011 return &nolockIoMethods;
30013 for(i=0; aMap[i].zFilesystem; i++){
30014 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
30015 return aMap[i].pMethods;
30020 /* Default case. Handles, amongst others, "nfs".
30021 ** Test byte-range lock using fcntl(). If the call succeeds,
30022 ** assume that the file-system supports POSIX style locks.
30024 lockInfo.l_len = 1;
30025 lockInfo.l_start = 0;
30026 lockInfo.l_whence = SEEK_SET;
30027 lockInfo.l_type = F_RDLCK;
30028 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
30029 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
30030 return &nfsIoMethods;
30031 } else {
30032 return &posixIoMethods;
30034 }else{
30035 return &dotlockIoMethods;
30038 static const sqlite3_io_methods
30039 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
30041 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
30043 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
30045 ** This "finder" function attempts to determine the best locking strategy
30046 ** for the database file "filePath". It then returns the sqlite3_io_methods
30047 ** object that implements that strategy.
30049 ** This is for VXWorks only.
30051 static const sqlite3_io_methods *autolockIoFinderImpl(
30052 const char *filePath, /* name of the database file */
30053 unixFile *pNew /* the open file object */
30055 struct flock lockInfo;
30057 if( !filePath ){
30058 /* If filePath==NULL that means we are dealing with a transient file
30059 ** that does not need to be locked. */
30060 return &nolockIoMethods;
30063 /* Test if fcntl() is supported and use POSIX style locks.
30064 ** Otherwise fall back to the named semaphore method.
30066 lockInfo.l_len = 1;
30067 lockInfo.l_start = 0;
30068 lockInfo.l_whence = SEEK_SET;
30069 lockInfo.l_type = F_RDLCK;
30070 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
30071 return &posixIoMethods;
30072 }else{
30073 return &semIoMethods;
30076 static const sqlite3_io_methods
30077 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
30079 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
30082 ** An abstract type for a pointer to an IO method finder function:
30084 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
30087 /****************************************************************************
30088 **************************** sqlite3_vfs methods ****************************
30090 ** This division contains the implementation of methods on the
30091 ** sqlite3_vfs object.
30095 ** Initialize the contents of the unixFile structure pointed to by pId.
30097 static int fillInUnixFile(
30098 sqlite3_vfs *pVfs, /* Pointer to vfs object */
30099 int h, /* Open file descriptor of file being opened */
30100 sqlite3_file *pId, /* Write to the unixFile structure here */
30101 const char *zFilename, /* Name of the file being opened */
30102 int ctrlFlags /* Zero or more UNIXFILE_* values */
30104 const sqlite3_io_methods *pLockingStyle;
30105 unixFile *pNew = (unixFile *)pId;
30106 int rc = SQLITE_OK;
30108 assert( pNew->pInode==NULL );
30110 /* Usually the path zFilename should not be a relative pathname. The
30111 ** exception is when opening the proxy "conch" file in builds that
30112 ** include the special Apple locking styles.
30114 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30115 assert( zFilename==0 || zFilename[0]=='/'
30116 || pVfs->pAppData==(void*)&autolockIoFinder );
30117 #else
30118 assert( zFilename==0 || zFilename[0]=='/' );
30119 #endif
30121 /* No locking occurs in temporary files */
30122 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
30124 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
30125 pNew->h = h;
30126 pNew->pVfs = pVfs;
30127 pNew->zPath = zFilename;
30128 pNew->ctrlFlags = (u8)ctrlFlags;
30129 #if SQLITE_MAX_MMAP_SIZE>0
30130 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
30131 #endif
30132 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
30133 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
30134 pNew->ctrlFlags |= UNIXFILE_PSOW;
30136 if( strcmp(pVfs->zName,"unix-excl")==0 ){
30137 pNew->ctrlFlags |= UNIXFILE_EXCL;
30140 #if OS_VXWORKS
30141 pNew->pId = vxworksFindFileId(zFilename);
30142 if( pNew->pId==0 ){
30143 ctrlFlags |= UNIXFILE_NOLOCK;
30144 rc = SQLITE_NOMEM;
30146 #endif
30148 if( ctrlFlags & UNIXFILE_NOLOCK ){
30149 pLockingStyle = &nolockIoMethods;
30150 }else{
30151 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
30152 #if SQLITE_ENABLE_LOCKING_STYLE
30153 /* Cache zFilename in the locking context (AFP and dotlock override) for
30154 ** proxyLock activation is possible (remote proxy is based on db name)
30155 ** zFilename remains valid until file is closed, to support */
30156 pNew->lockingContext = (void*)zFilename;
30157 #endif
30160 if( pLockingStyle == &posixIoMethods
30161 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30162 || pLockingStyle == &nfsIoMethods
30163 #endif
30165 unixEnterMutex();
30166 rc = findInodeInfo(pNew, &pNew->pInode);
30167 if( rc!=SQLITE_OK ){
30168 /* If an error occurred in findInodeInfo(), close the file descriptor
30169 ** immediately, before releasing the mutex. findInodeInfo() may fail
30170 ** in two scenarios:
30172 ** (a) A call to fstat() failed.
30173 ** (b) A malloc failed.
30175 ** Scenario (b) may only occur if the process is holding no other
30176 ** file descriptors open on the same file. If there were other file
30177 ** descriptors on this file, then no malloc would be required by
30178 ** findInodeInfo(). If this is the case, it is quite safe to close
30179 ** handle h - as it is guaranteed that no posix locks will be released
30180 ** by doing so.
30182 ** If scenario (a) caused the error then things are not so safe. The
30183 ** implicit assumption here is that if fstat() fails, things are in
30184 ** such bad shape that dropping a lock or two doesn't matter much.
30186 robust_close(pNew, h, __LINE__);
30187 h = -1;
30189 unixLeaveMutex();
30192 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30193 else if( pLockingStyle == &afpIoMethods ){
30194 /* AFP locking uses the file path so it needs to be included in
30195 ** the afpLockingContext.
30197 afpLockingContext *pCtx;
30198 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
30199 if( pCtx==0 ){
30200 rc = SQLITE_NOMEM;
30201 }else{
30202 /* NB: zFilename exists and remains valid until the file is closed
30203 ** according to requirement F11141. So we do not need to make a
30204 ** copy of the filename. */
30205 pCtx->dbPath = zFilename;
30206 pCtx->reserved = 0;
30207 srandomdev();
30208 unixEnterMutex();
30209 rc = findInodeInfo(pNew, &pNew->pInode);
30210 if( rc!=SQLITE_OK ){
30211 sqlite3_free(pNew->lockingContext);
30212 robust_close(pNew, h, __LINE__);
30213 h = -1;
30215 unixLeaveMutex();
30218 #endif
30220 else if( pLockingStyle == &dotlockIoMethods ){
30221 /* Dotfile locking uses the file path so it needs to be included in
30222 ** the dotlockLockingContext
30224 char *zLockFile;
30225 int nFilename;
30226 assert( zFilename!=0 );
30227 nFilename = (int)strlen(zFilename) + 6;
30228 zLockFile = (char *)sqlite3_malloc(nFilename);
30229 if( zLockFile==0 ){
30230 rc = SQLITE_NOMEM;
30231 }else{
30232 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
30234 pNew->lockingContext = zLockFile;
30237 #if OS_VXWORKS
30238 else if( pLockingStyle == &semIoMethods ){
30239 /* Named semaphore locking uses the file path so it needs to be
30240 ** included in the semLockingContext
30242 unixEnterMutex();
30243 rc = findInodeInfo(pNew, &pNew->pInode);
30244 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
30245 char *zSemName = pNew->pInode->aSemName;
30246 int n;
30247 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
30248 pNew->pId->zCanonicalName);
30249 for( n=1; zSemName[n]; n++ )
30250 if( zSemName[n]=='/' ) zSemName[n] = '_';
30251 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
30252 if( pNew->pInode->pSem == SEM_FAILED ){
30253 rc = SQLITE_NOMEM;
30254 pNew->pInode->aSemName[0] = '\0';
30257 unixLeaveMutex();
30259 #endif
30261 pNew->lastErrno = 0;
30262 #if OS_VXWORKS
30263 if( rc!=SQLITE_OK ){
30264 if( h>=0 ) robust_close(pNew, h, __LINE__);
30265 h = -1;
30266 osUnlink(zFilename);
30267 pNew->ctrlFlags |= UNIXFILE_DELETE;
30269 #endif
30270 if( rc!=SQLITE_OK ){
30271 if( h>=0 ) robust_close(pNew, h, __LINE__);
30272 }else{
30273 pNew->pMethod = pLockingStyle;
30274 OpenCounter(+1);
30275 verifyDbFile(pNew);
30277 return rc;
30281 ** Return the name of a directory in which to put temporary files.
30282 ** If no suitable temporary file directory can be found, return NULL.
30284 static const char *unixTempFileDir(void){
30285 static const char *azDirs[] = {
30289 "/var/tmp",
30290 "/usr/tmp",
30291 "/tmp",
30292 0 /* List terminator */
30294 unsigned int i;
30295 struct stat buf;
30296 const char *zDir = 0;
30298 azDirs[0] = sqlite3_temp_directory;
30299 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
30300 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
30301 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
30302 if( zDir==0 ) continue;
30303 if( osStat(zDir, &buf) ) continue;
30304 if( !S_ISDIR(buf.st_mode) ) continue;
30305 if( osAccess(zDir, 07) ) continue;
30306 break;
30308 return zDir;
30312 ** Create a temporary file name in zBuf. zBuf must be allocated
30313 ** by the calling process and must be big enough to hold at least
30314 ** pVfs->mxPathname bytes.
30316 static int unixGetTempname(int nBuf, char *zBuf){
30317 static const unsigned char zChars[] =
30318 "abcdefghijklmnopqrstuvwxyz"
30319 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
30320 "0123456789";
30321 unsigned int i, j;
30322 const char *zDir;
30324 /* It's odd to simulate an io-error here, but really this is just
30325 ** using the io-error infrastructure to test that SQLite handles this
30326 ** function failing.
30328 SimulateIOError( return SQLITE_IOERR );
30330 zDir = unixTempFileDir();
30331 if( zDir==0 ) zDir = ".";
30333 /* Check that the output buffer is large enough for the temporary file
30334 ** name. If it is not, return SQLITE_ERROR.
30336 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
30337 return SQLITE_ERROR;
30341 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
30342 j = (int)strlen(zBuf);
30343 sqlite3_randomness(15, &zBuf[j]);
30344 for(i=0; i<15; i++, j++){
30345 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
30347 zBuf[j] = 0;
30348 zBuf[j+1] = 0;
30349 }while( osAccess(zBuf,0)==0 );
30350 return SQLITE_OK;
30353 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30355 ** Routine to transform a unixFile into a proxy-locking unixFile.
30356 ** Implementation in the proxy-lock division, but used by unixOpen()
30357 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
30359 static int proxyTransformUnixFile(unixFile*, const char*);
30360 #endif
30363 ** Search for an unused file descriptor that was opened on the database
30364 ** file (not a journal or master-journal file) identified by pathname
30365 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
30366 ** argument to this function.
30368 ** Such a file descriptor may exist if a database connection was closed
30369 ** but the associated file descriptor could not be closed because some
30370 ** other file descriptor open on the same file is holding a file-lock.
30371 ** Refer to comments in the unixClose() function and the lengthy comment
30372 ** describing "Posix Advisory Locking" at the start of this file for
30373 ** further details. Also, ticket #4018.
30375 ** If a suitable file descriptor is found, then it is returned. If no
30376 ** such file descriptor is located, -1 is returned.
30378 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
30379 UnixUnusedFd *pUnused = 0;
30381 /* Do not search for an unused file descriptor on vxworks. Not because
30382 ** vxworks would not benefit from the change (it might, we're not sure),
30383 ** but because no way to test it is currently available. It is better
30384 ** not to risk breaking vxworks support for the sake of such an obscure
30385 ** feature. */
30386 #if !OS_VXWORKS
30387 struct stat sStat; /* Results of stat() call */
30389 /* A stat() call may fail for various reasons. If this happens, it is
30390 ** almost certain that an open() call on the same path will also fail.
30391 ** For this reason, if an error occurs in the stat() call here, it is
30392 ** ignored and -1 is returned. The caller will try to open a new file
30393 ** descriptor on the same path, fail, and return an error to SQLite.
30395 ** Even if a subsequent open() call does succeed, the consequences of
30396 ** not searching for a reusable file descriptor are not dire. */
30397 if( 0==osStat(zPath, &sStat) ){
30398 unixInodeInfo *pInode;
30400 unixEnterMutex();
30401 pInode = inodeList;
30402 while( pInode && (pInode->fileId.dev!=sStat.st_dev
30403 || pInode->fileId.ino!=sStat.st_ino) ){
30404 pInode = pInode->pNext;
30406 if( pInode ){
30407 UnixUnusedFd **pp;
30408 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
30409 pUnused = *pp;
30410 if( pUnused ){
30411 *pp = pUnused->pNext;
30414 unixLeaveMutex();
30416 #endif /* if !OS_VXWORKS */
30417 return pUnused;
30421 ** This function is called by unixOpen() to determine the unix permissions
30422 ** to create new files with. If no error occurs, then SQLITE_OK is returned
30423 ** and a value suitable for passing as the third argument to open(2) is
30424 ** written to *pMode. If an IO error occurs, an SQLite error code is
30425 ** returned and the value of *pMode is not modified.
30427 ** In most cases, this routine sets *pMode to 0, which will become
30428 ** an indication to robust_open() to create the file using
30429 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
30430 ** But if the file being opened is a WAL or regular journal file, then
30431 ** this function queries the file-system for the permissions on the
30432 ** corresponding database file and sets *pMode to this value. Whenever
30433 ** possible, WAL and journal files are created using the same permissions
30434 ** as the associated database file.
30436 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
30437 ** original filename is unavailable. But 8_3_NAMES is only used for
30438 ** FAT filesystems and permissions do not matter there, so just use
30439 ** the default permissions.
30441 static int findCreateFileMode(
30442 const char *zPath, /* Path of file (possibly) being created */
30443 int flags, /* Flags passed as 4th argument to xOpen() */
30444 mode_t *pMode, /* OUT: Permissions to open file with */
30445 uid_t *pUid, /* OUT: uid to set on the file */
30446 gid_t *pGid /* OUT: gid to set on the file */
30448 int rc = SQLITE_OK; /* Return Code */
30449 *pMode = 0;
30450 *pUid = 0;
30451 *pGid = 0;
30452 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
30453 char zDb[MAX_PATHNAME+1]; /* Database file path */
30454 int nDb; /* Number of valid bytes in zDb */
30455 struct stat sStat; /* Output of stat() on database file */
30457 /* zPath is a path to a WAL or journal file. The following block derives
30458 ** the path to the associated database file from zPath. This block handles
30459 ** the following naming conventions:
30461 ** "<path to db>-journal"
30462 ** "<path to db>-wal"
30463 ** "<path to db>-journalNN"
30464 ** "<path to db>-walNN"
30466 ** where NN is a decimal number. The NN naming schemes are
30467 ** used by the test_multiplex.c module.
30469 nDb = sqlite3Strlen30(zPath) - 1;
30470 #ifdef SQLITE_ENABLE_8_3_NAMES
30471 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
30472 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
30473 #else
30474 while( zPath[nDb]!='-' ){
30475 assert( nDb>0 );
30476 assert( zPath[nDb]!='\n' );
30477 nDb--;
30479 #endif
30480 memcpy(zDb, zPath, nDb);
30481 zDb[nDb] = '\0';
30483 if( 0==osStat(zDb, &sStat) ){
30484 *pMode = sStat.st_mode & 0777;
30485 *pUid = sStat.st_uid;
30486 *pGid = sStat.st_gid;
30487 }else{
30488 rc = SQLITE_IOERR_FSTAT;
30490 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
30491 *pMode = 0600;
30493 return rc;
30497 ** Initializes a unixFile structure with zeros.
30499 CHROMIUM_SQLITE_API
30500 void chromium_sqlite3_initialize_unix_sqlite3_file(sqlite3_file* file) {
30501 memset(file, 0, sizeof(unixFile));
30504 CHROMIUM_SQLITE_API
30505 int chromium_sqlite3_fill_in_unix_sqlite3_file(sqlite3_vfs* vfs,
30506 int fd,
30507 int dirfd,
30508 sqlite3_file* file,
30509 const char* fileName,
30510 int noLock) {
30511 int ctrlFlags = (noLock ? UNIXFILE_NOLOCK : 0);
30512 return fillInUnixFile(vfs, fd, file, fileName, ctrlFlags);
30516 ** Search for an unused file descriptor that was opened on the database file.
30517 ** If a suitable file descriptor if found, then it is stored in *fd; otherwise,
30518 ** *fd is not modified.
30520 ** If a reusable file descriptor is not found, and a new UnixUnusedFd cannot
30521 ** be allocated, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK is returned.
30523 CHROMIUM_SQLITE_API
30524 int chromium_sqlite3_get_reusable_file_handle(sqlite3_file* file,
30525 const char* fileName,
30526 int flags,
30527 int* fd) {
30528 unixFile* unixSQLite3File = (unixFile*)file;
30529 int fileType = flags & 0xFFFFFF00;
30530 if (fileType == SQLITE_OPEN_MAIN_DB) {
30531 UnixUnusedFd *unusedFd = findReusableFd(fileName, flags);
30532 if (unusedFd) {
30533 *fd = unusedFd->fd;
30534 } else {
30535 unusedFd = sqlite3_malloc(sizeof(*unusedFd));
30536 if (!unusedFd) {
30537 return SQLITE_NOMEM;
30540 unixSQLite3File->pUnused = unusedFd;
30542 return SQLITE_OK;
30546 ** Marks 'fd' as the unused file descriptor for 'pFile'.
30548 CHROMIUM_SQLITE_API
30549 void chromium_sqlite3_update_reusable_file_handle(sqlite3_file* file,
30550 int fd,
30551 int flags) {
30552 unixFile* unixSQLite3File = (unixFile*)file;
30553 if (unixSQLite3File->pUnused) {
30554 unixSQLite3File->pUnused->fd = fd;
30555 unixSQLite3File->pUnused->flags = flags;
30560 ** Destroys pFile's field that keeps track of the unused file descriptor.
30562 CHROMIUM_SQLITE_API
30563 void chromium_sqlite3_destroy_reusable_file_handle(sqlite3_file* file) {
30564 unixFile* unixSQLite3File = (unixFile*)file;
30565 sqlite3_free(unixSQLite3File->pUnused);
30569 ** Open the file zPath.
30571 ** Previously, the SQLite OS layer used three functions in place of this
30572 ** one:
30574 ** sqlite3OsOpenReadWrite();
30575 ** sqlite3OsOpenReadOnly();
30576 ** sqlite3OsOpenExclusive();
30578 ** These calls correspond to the following combinations of flags:
30580 ** ReadWrite() -> (READWRITE | CREATE)
30581 ** ReadOnly() -> (READONLY)
30582 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
30584 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
30585 ** true, the file was configured to be automatically deleted when the
30586 ** file handle closed. To achieve the same effect using this new
30587 ** interface, add the DELETEONCLOSE flag to those specified above for
30588 ** OpenExclusive().
30590 static int unixOpen(
30591 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
30592 const char *zPath, /* Pathname of file to be opened */
30593 sqlite3_file *pFile, /* The file descriptor to be filled in */
30594 int flags, /* Input flags to control the opening */
30595 int *pOutFlags /* Output flags returned to SQLite core */
30597 unixFile *p = (unixFile *)pFile;
30598 int fd = -1; /* File descriptor returned by open() */
30599 int openFlags = 0; /* Flags to pass to open() */
30600 int eType = flags&0xFFFFFF00; /* Type of file to open */
30601 int noLock; /* True to omit locking primitives */
30602 int rc = SQLITE_OK; /* Function Return Code */
30603 int ctrlFlags = 0; /* UNIXFILE_* flags */
30605 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
30606 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
30607 int isCreate = (flags & SQLITE_OPEN_CREATE);
30608 int isReadonly = (flags & SQLITE_OPEN_READONLY);
30609 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
30610 #if SQLITE_ENABLE_LOCKING_STYLE
30611 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
30612 #endif
30613 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
30614 struct statfs fsInfo;
30615 #endif
30617 /* If creating a master or main-file journal, this function will open
30618 ** a file-descriptor on the directory too. The first time unixSync()
30619 ** is called the directory file descriptor will be fsync()ed and close()d.
30621 int syncDir = (isCreate && (
30622 eType==SQLITE_OPEN_MASTER_JOURNAL
30623 || eType==SQLITE_OPEN_MAIN_JOURNAL
30624 || eType==SQLITE_OPEN_WAL
30627 /* If argument zPath is a NULL pointer, this function is required to open
30628 ** a temporary file. Use this buffer to store the file name in.
30630 char zTmpname[MAX_PATHNAME+2];
30631 const char *zName = zPath;
30633 /* Check the following statements are true:
30635 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
30636 ** (b) if CREATE is set, then READWRITE must also be set, and
30637 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
30638 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
30640 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
30641 assert(isCreate==0 || isReadWrite);
30642 assert(isExclusive==0 || isCreate);
30643 assert(isDelete==0 || isCreate);
30645 /* The main DB, main journal, WAL file and master journal are never
30646 ** automatically deleted. Nor are they ever temporary files. */
30647 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
30648 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
30649 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
30650 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
30652 /* Assert that the upper layer has set one of the "file-type" flags. */
30653 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
30654 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
30655 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
30656 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
30659 /* Detect a pid change and reset the PRNG. There is a race condition
30660 ** here such that two or more threads all trying to open databases at
30661 ** the same instant might all reset the PRNG. But multiple resets
30662 ** are harmless.
30664 if( randomnessPid!=getpid() ){
30665 randomnessPid = getpid();
30666 sqlite3_randomness(0,0);
30669 chromium_sqlite3_initialize_unix_sqlite3_file(pFile);
30671 if( eType==SQLITE_OPEN_MAIN_DB ){
30672 rc = chromium_sqlite3_get_reusable_file_handle(pFile, zName, flags, &fd);
30673 if( rc!=SQLITE_OK ){
30674 return rc;
30677 /* Database filenames are double-zero terminated if they are not
30678 ** URIs with parameters. Hence, they can always be passed into
30679 ** sqlite3_uri_parameter(). */
30680 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
30682 }else if( !zName ){
30683 /* If zName is NULL, the upper layer is requesting a temp file. */
30684 assert(isDelete && !syncDir);
30685 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
30686 if( rc!=SQLITE_OK ){
30687 return rc;
30689 zName = zTmpname;
30691 /* Generated temporary filenames are always double-zero terminated
30692 ** for use by sqlite3_uri_parameter(). */
30693 assert( zName[strlen(zName)+1]==0 );
30696 /* Determine the value of the flags parameter passed to POSIX function
30697 ** open(). These must be calculated even if open() is not called, as
30698 ** they may be stored as part of the file handle and used by the
30699 ** 'conch file' locking functions later on. */
30700 if( isReadonly ) openFlags |= O_RDONLY;
30701 if( isReadWrite ) openFlags |= O_RDWR;
30702 if( isCreate ) openFlags |= O_CREAT;
30703 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
30704 openFlags |= (O_LARGEFILE|O_BINARY);
30706 if( fd<0 ){
30707 mode_t openMode; /* Permissions to create file with */
30708 uid_t uid; /* Userid for the file */
30709 gid_t gid; /* Groupid for the file */
30710 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
30711 if( rc!=SQLITE_OK ){
30712 assert( !p->pUnused );
30713 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
30714 return rc;
30716 fd = robust_open(zName, openFlags, openMode);
30717 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
30718 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
30719 /* Failed to open the file for read/write access. Try read-only. */
30720 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
30721 openFlags &= ~(O_RDWR|O_CREAT);
30722 flags |= SQLITE_OPEN_READONLY;
30723 openFlags |= O_RDONLY;
30724 isReadonly = 1;
30725 fd = robust_open(zName, openFlags, openMode);
30727 if( fd<0 ){
30728 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
30729 goto open_finished;
30732 /* If this process is running as root and if creating a new rollback
30733 ** journal or WAL file, set the ownership of the journal or WAL to be
30734 ** the same as the original database.
30736 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
30737 osFchown(fd, uid, gid);
30740 assert( fd>=0 );
30741 if( pOutFlags ){
30742 *pOutFlags = flags;
30745 chromium_sqlite3_update_reusable_file_handle(pFile, fd, flags);
30747 if( isDelete ){
30748 #if OS_VXWORKS
30749 zPath = zName;
30750 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
30751 zPath = sqlite3_mprintf("%s", zName);
30752 if( zPath==0 ){
30753 robust_close(p, fd, __LINE__);
30754 return SQLITE_NOMEM;
30756 #else
30757 osUnlink(zName);
30758 #endif
30760 #if SQLITE_ENABLE_LOCKING_STYLE
30761 else{
30762 p->openFlags = openFlags;
30764 #endif
30766 noLock = eType!=SQLITE_OPEN_MAIN_DB;
30769 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
30770 if( fstatfs(fd, &fsInfo) == -1 ){
30771 ((unixFile*)pFile)->lastErrno = errno;
30772 robust_close(p, fd, __LINE__);
30773 return SQLITE_IOERR_ACCESS;
30775 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
30776 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
30778 #endif
30780 /* Set up appropriate ctrlFlags */
30781 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
30782 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
30783 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
30784 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
30785 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
30787 #if SQLITE_ENABLE_LOCKING_STYLE
30788 #if SQLITE_PREFER_PROXY_LOCKING
30789 isAutoProxy = 1;
30790 #endif
30791 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
30792 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
30793 int useProxy = 0;
30795 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
30796 ** never use proxy, NULL means use proxy for non-local files only. */
30797 if( envforce!=NULL ){
30798 useProxy = atoi(envforce)>0;
30799 }else{
30800 if( statfs(zPath, &fsInfo) == -1 ){
30801 /* In theory, the close(fd) call is sub-optimal. If the file opened
30802 ** with fd is a database file, and there are other connections open
30803 ** on that file that are currently holding advisory locks on it,
30804 ** then the call to close() will cancel those locks. In practice,
30805 ** we're assuming that statfs() doesn't fail very often. At least
30806 ** not while other file descriptors opened by the same process on
30807 ** the same file are working. */
30808 p->lastErrno = errno;
30809 robust_close(p, fd, __LINE__);
30810 rc = SQLITE_IOERR_ACCESS;
30811 goto open_finished;
30813 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
30815 if( useProxy ){
30816 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
30817 if( rc==SQLITE_OK ){
30818 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
30819 if( rc!=SQLITE_OK ){
30820 /* Use unixClose to clean up the resources added in fillInUnixFile
30821 ** and clear all the structure's references. Specifically,
30822 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
30824 unixClose(pFile);
30825 return rc;
30828 goto open_finished;
30831 #endif
30833 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
30835 open_finished:
30836 if( rc!=SQLITE_OK ){
30837 chromium_sqlite3_destroy_reusable_file_handle(pFile);
30839 return rc;
30844 ** Delete the file at zPath. If the dirSync argument is true, fsync()
30845 ** the directory after deleting the file.
30847 static int unixDelete(
30848 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
30849 const char *zPath, /* Name of file to be deleted */
30850 int dirSync /* If true, fsync() directory after deleting file */
30852 int rc = SQLITE_OK;
30853 UNUSED_PARAMETER(NotUsed);
30854 SimulateIOError(return SQLITE_IOERR_DELETE);
30855 if( osUnlink(zPath)==(-1) ){
30856 if( errno==ENOENT
30857 #if OS_VXWORKS
30858 || osAccess(zPath,0)!=0
30859 #endif
30861 rc = SQLITE_IOERR_DELETE_NOENT;
30862 }else{
30863 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
30865 return rc;
30867 #ifndef SQLITE_DISABLE_DIRSYNC
30868 if( (dirSync & 1)!=0 ){
30869 int fd;
30870 rc = osOpenDirectory(zPath, &fd);
30871 if( rc==SQLITE_OK ){
30872 #if OS_VXWORKS
30873 if( fsync(fd)==-1 )
30874 #else
30875 if( fsync(fd) )
30876 #endif
30878 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
30880 robust_close(0, fd, __LINE__);
30881 }else if( rc==SQLITE_CANTOPEN ){
30882 rc = SQLITE_OK;
30885 #endif
30886 return rc;
30890 ** Test the existence of or access permissions of file zPath. The
30891 ** test performed depends on the value of flags:
30893 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
30894 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
30895 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
30897 ** Otherwise return 0.
30899 static int unixAccess(
30900 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
30901 const char *zPath, /* Path of the file to examine */
30902 int flags, /* What do we want to learn about the zPath file? */
30903 int *pResOut /* Write result boolean here */
30905 int amode = 0;
30906 UNUSED_PARAMETER(NotUsed);
30907 SimulateIOError( return SQLITE_IOERR_ACCESS; );
30908 switch( flags ){
30909 case SQLITE_ACCESS_EXISTS:
30910 amode = F_OK;
30911 break;
30912 case SQLITE_ACCESS_READWRITE:
30913 amode = W_OK|R_OK;
30914 break;
30915 case SQLITE_ACCESS_READ:
30916 amode = R_OK;
30917 break;
30919 default:
30920 assert(!"Invalid flags argument");
30922 *pResOut = (osAccess(zPath, amode)==0);
30923 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
30924 struct stat buf;
30925 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
30926 *pResOut = 0;
30929 return SQLITE_OK;
30934 ** Turn a relative pathname into a full pathname. The relative path
30935 ** is stored as a nul-terminated string in the buffer pointed to by
30936 ** zPath.
30938 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
30939 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
30940 ** this buffer before returning.
30942 static int unixFullPathname(
30943 sqlite3_vfs *pVfs, /* Pointer to vfs object */
30944 const char *zPath, /* Possibly relative input path */
30945 int nOut, /* Size of output buffer in bytes */
30946 char *zOut /* Output buffer */
30949 /* It's odd to simulate an io-error here, but really this is just
30950 ** using the io-error infrastructure to test that SQLite handles this
30951 ** function failing. This function could fail if, for example, the
30952 ** current working directory has been unlinked.
30954 SimulateIOError( return SQLITE_ERROR );
30956 assert( pVfs->mxPathname==MAX_PATHNAME );
30957 UNUSED_PARAMETER(pVfs);
30959 zOut[nOut-1] = '\0';
30960 if( zPath[0]=='/' ){
30961 sqlite3_snprintf(nOut, zOut, "%s", zPath);
30962 }else{
30963 int nCwd;
30964 if( osGetcwd(zOut, nOut-1)==0 ){
30965 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
30967 nCwd = (int)strlen(zOut);
30968 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
30970 return SQLITE_OK;
30974 #ifndef SQLITE_OMIT_LOAD_EXTENSION
30976 ** Interfaces for opening a shared library, finding entry points
30977 ** within the shared library, and closing the shared library.
30979 #include <dlfcn.h>
30980 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
30981 UNUSED_PARAMETER(NotUsed);
30982 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
30986 ** SQLite calls this function immediately after a call to unixDlSym() or
30987 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
30988 ** message is available, it is written to zBufOut. If no error message
30989 ** is available, zBufOut is left unmodified and SQLite uses a default
30990 ** error message.
30992 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
30993 const char *zErr;
30994 UNUSED_PARAMETER(NotUsed);
30995 unixEnterMutex();
30996 zErr = dlerror();
30997 if( zErr ){
30998 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
31000 unixLeaveMutex();
31002 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
31004 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
31005 ** cast into a pointer to a function. And yet the library dlsym() routine
31006 ** returns a void* which is really a pointer to a function. So how do we
31007 ** use dlsym() with -pedantic-errors?
31009 ** Variable x below is defined to be a pointer to a function taking
31010 ** parameters void* and const char* and returning a pointer to a function.
31011 ** We initialize x by assigning it a pointer to the dlsym() function.
31012 ** (That assignment requires a cast.) Then we call the function that
31013 ** x points to.
31015 ** This work-around is unlikely to work correctly on any system where
31016 ** you really cannot cast a function pointer into void*. But then, on the
31017 ** other hand, dlsym() will not work on such a system either, so we have
31018 ** not really lost anything.
31020 void (*(*x)(void*,const char*))(void);
31021 UNUSED_PARAMETER(NotUsed);
31022 x = (void(*(*)(void*,const char*))(void))dlsym;
31023 return (*x)(p, zSym);
31025 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
31026 UNUSED_PARAMETER(NotUsed);
31027 dlclose(pHandle);
31029 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
31030 #define unixDlOpen 0
31031 #define unixDlError 0
31032 #define unixDlSym 0
31033 #define unixDlClose 0
31034 #endif
31037 ** Write nBuf bytes of random data to the supplied buffer zBuf.
31039 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
31040 UNUSED_PARAMETER(NotUsed);
31041 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
31043 /* We have to initialize zBuf to prevent valgrind from reporting
31044 ** errors. The reports issued by valgrind are incorrect - we would
31045 ** prefer that the randomness be increased by making use of the
31046 ** uninitialized space in zBuf - but valgrind errors tend to worry
31047 ** some users. Rather than argue, it seems easier just to initialize
31048 ** the whole array and silence valgrind, even if that means less randomness
31049 ** in the random seed.
31051 ** When testing, initializing zBuf[] to zero is all we do. That means
31052 ** that we always use the same random number sequence. This makes the
31053 ** tests repeatable.
31055 memset(zBuf, 0, nBuf);
31056 randomnessPid = getpid();
31057 #if !defined(SQLITE_TEST)
31059 int fd, got;
31060 fd = robust_open("/dev/urandom", O_RDONLY, 0);
31061 if( fd<0 ){
31062 time_t t;
31063 time(&t);
31064 memcpy(zBuf, &t, sizeof(t));
31065 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
31066 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
31067 nBuf = sizeof(t) + sizeof(randomnessPid);
31068 }else{
31069 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
31070 robust_close(0, fd, __LINE__);
31073 #endif
31074 return nBuf;
31079 ** Sleep for a little while. Return the amount of time slept.
31080 ** The argument is the number of microseconds we want to sleep.
31081 ** The return value is the number of microseconds of sleep actually
31082 ** requested from the underlying operating system, a number which
31083 ** might be greater than or equal to the argument, but not less
31084 ** than the argument.
31086 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
31087 #if OS_VXWORKS
31088 struct timespec sp;
31090 sp.tv_sec = microseconds / 1000000;
31091 sp.tv_nsec = (microseconds % 1000000) * 1000;
31092 nanosleep(&sp, NULL);
31093 UNUSED_PARAMETER(NotUsed);
31094 return microseconds;
31095 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
31096 usleep(microseconds);
31097 UNUSED_PARAMETER(NotUsed);
31098 return microseconds;
31099 #else
31100 int seconds = (microseconds+999999)/1000000;
31101 sleep(seconds);
31102 UNUSED_PARAMETER(NotUsed);
31103 return seconds*1000000;
31104 #endif
31108 ** The following variable, if set to a non-zero value, is interpreted as
31109 ** the number of seconds since 1970 and is used to set the result of
31110 ** sqlite3OsCurrentTime() during testing.
31112 #ifdef SQLITE_TEST
31113 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
31114 #endif
31117 ** Find the current time (in Universal Coordinated Time). Write into *piNow
31118 ** the current time and date as a Julian Day number times 86_400_000. In
31119 ** other words, write into *piNow the number of milliseconds since the Julian
31120 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
31121 ** proleptic Gregorian calendar.
31123 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
31124 ** cannot be found.
31126 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
31127 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
31128 int rc = SQLITE_OK;
31129 #if defined(NO_GETTOD)
31130 time_t t;
31131 time(&t);
31132 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
31133 #elif OS_VXWORKS
31134 struct timespec sNow;
31135 clock_gettime(CLOCK_REALTIME, &sNow);
31136 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
31137 #else
31138 struct timeval sNow;
31139 if( gettimeofday(&sNow, 0)==0 ){
31140 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
31141 }else{
31142 rc = SQLITE_ERROR;
31144 #endif
31146 #ifdef SQLITE_TEST
31147 if( sqlite3_current_time ){
31148 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
31150 #endif
31151 UNUSED_PARAMETER(NotUsed);
31152 return rc;
31156 ** Find the current time (in Universal Coordinated Time). Write the
31157 ** current time and date as a Julian Day number into *prNow and
31158 ** return 0. Return 1 if the time and date cannot be found.
31160 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
31161 sqlite3_int64 i = 0;
31162 int rc;
31163 UNUSED_PARAMETER(NotUsed);
31164 rc = unixCurrentTimeInt64(0, &i);
31165 *prNow = i/86400000.0;
31166 return rc;
31170 ** We added the xGetLastError() method with the intention of providing
31171 ** better low-level error messages when operating-system problems come up
31172 ** during SQLite operation. But so far, none of that has been implemented
31173 ** in the core. So this routine is never called. For now, it is merely
31174 ** a place-holder.
31176 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
31177 UNUSED_PARAMETER(NotUsed);
31178 UNUSED_PARAMETER(NotUsed2);
31179 UNUSED_PARAMETER(NotUsed3);
31180 return 0;
31185 ************************ End of sqlite3_vfs methods ***************************
31186 ******************************************************************************/
31188 /******************************************************************************
31189 ************************** Begin Proxy Locking ********************************
31191 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
31192 ** other locking methods on secondary lock files. Proxy locking is a
31193 ** meta-layer over top of the primitive locking implemented above. For
31194 ** this reason, the division that implements of proxy locking is deferred
31195 ** until late in the file (here) after all of the other I/O methods have
31196 ** been defined - so that the primitive locking methods are available
31197 ** as services to help with the implementation of proxy locking.
31199 ****
31201 ** The default locking schemes in SQLite use byte-range locks on the
31202 ** database file to coordinate safe, concurrent access by multiple readers
31203 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
31204 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
31205 ** as POSIX read & write locks over fixed set of locations (via fsctl),
31206 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
31207 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
31208 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
31209 ** address in the shared range is taken for a SHARED lock, the entire
31210 ** shared range is taken for an EXCLUSIVE lock):
31212 ** PENDING_BYTE 0x40000000
31213 ** RESERVED_BYTE 0x40000001
31214 ** SHARED_RANGE 0x40000002 -> 0x40000200
31216 ** This works well on the local file system, but shows a nearly 100x
31217 ** slowdown in read performance on AFP because the AFP client disables
31218 ** the read cache when byte-range locks are present. Enabling the read
31219 ** cache exposes a cache coherency problem that is present on all OS X
31220 ** supported network file systems. NFS and AFP both observe the
31221 ** close-to-open semantics for ensuring cache coherency
31222 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
31223 ** address the requirements for concurrent database access by multiple
31224 ** readers and writers
31225 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
31227 ** To address the performance and cache coherency issues, proxy file locking
31228 ** changes the way database access is controlled by limiting access to a
31229 ** single host at a time and moving file locks off of the database file
31230 ** and onto a proxy file on the local file system.
31233 ** Using proxy locks
31234 ** -----------------
31236 ** C APIs
31238 ** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
31239 ** <proxy_path> | ":auto:");
31240 ** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
31243 ** SQL pragmas
31245 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
31246 ** PRAGMA [database.]lock_proxy_file
31248 ** Specifying ":auto:" means that if there is a conch file with a matching
31249 ** host ID in it, the proxy path in the conch file will be used, otherwise
31250 ** a proxy path based on the user's temp dir
31251 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
31252 ** actual proxy file name is generated from the name and path of the
31253 ** database file. For example:
31255 ** For database path "/Users/me/foo.db"
31256 ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
31258 ** Once a lock proxy is configured for a database connection, it can not
31259 ** be removed, however it may be switched to a different proxy path via
31260 ** the above APIs (assuming the conch file is not being held by another
31261 ** connection or process).
31264 ** How proxy locking works
31265 ** -----------------------
31267 ** Proxy file locking relies primarily on two new supporting files:
31269 ** * conch file to limit access to the database file to a single host
31270 ** at a time
31272 ** * proxy file to act as a proxy for the advisory locks normally
31273 ** taken on the database
31275 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
31276 ** by taking an sqlite-style shared lock on the conch file, reading the
31277 ** contents and comparing the host's unique host ID (see below) and lock
31278 ** proxy path against the values stored in the conch. The conch file is
31279 ** stored in the same directory as the database file and the file name
31280 ** is patterned after the database file name as ".<databasename>-conch".
31281 ** If the conch file does not exist, or its contents do not match the
31282 ** host ID and/or proxy path, then the lock is escalated to an exclusive
31283 ** lock and the conch file contents is updated with the host ID and proxy
31284 ** path and the lock is downgraded to a shared lock again. If the conch
31285 ** is held by another process (with a shared lock), the exclusive lock
31286 ** will fail and SQLITE_BUSY is returned.
31288 ** The proxy file - a single-byte file used for all advisory file locks
31289 ** normally taken on the database file. This allows for safe sharing
31290 ** of the database file for multiple readers and writers on the same
31291 ** host (the conch ensures that they all use the same local lock file).
31293 ** Requesting the lock proxy does not immediately take the conch, it is
31294 ** only taken when the first request to lock database file is made.
31295 ** This matches the semantics of the traditional locking behavior, where
31296 ** opening a connection to a database file does not take a lock on it.
31297 ** The shared lock and an open file descriptor are maintained until
31298 ** the connection to the database is closed.
31300 ** The proxy file and the lock file are never deleted so they only need
31301 ** to be created the first time they are used.
31303 ** Configuration options
31304 ** ---------------------
31306 ** SQLITE_PREFER_PROXY_LOCKING
31308 ** Database files accessed on non-local file systems are
31309 ** automatically configured for proxy locking, lock files are
31310 ** named automatically using the same logic as
31311 ** PRAGMA lock_proxy_file=":auto:"
31313 ** SQLITE_PROXY_DEBUG
31315 ** Enables the logging of error messages during host id file
31316 ** retrieval and creation
31318 ** LOCKPROXYDIR
31320 ** Overrides the default directory used for lock proxy files that
31321 ** are named automatically via the ":auto:" setting
31323 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
31325 ** Permissions to use when creating a directory for storing the
31326 ** lock proxy files, only used when LOCKPROXYDIR is not set.
31329 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
31330 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
31331 ** force proxy locking to be used for every database file opened, and 0
31332 ** will force automatic proxy locking to be disabled for all database
31333 ** files (explicitly calling the SQLITE_SET_LOCKPROXYFILE pragma or
31334 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
31338 ** Proxy locking is only available on MacOSX
31340 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31343 ** The proxyLockingContext has the path and file structures for the remote
31344 ** and local proxy files in it
31346 typedef struct proxyLockingContext proxyLockingContext;
31347 struct proxyLockingContext {
31348 unixFile *conchFile; /* Open conch file */
31349 char *conchFilePath; /* Name of the conch file */
31350 unixFile *lockProxy; /* Open proxy lock file */
31351 char *lockProxyPath; /* Name of the proxy lock file */
31352 char *dbPath; /* Name of the open file */
31353 int conchHeld; /* 1 if the conch is held, -1 if lockless */
31354 void *oldLockingContext; /* Original lockingcontext to restore on close */
31355 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
31359 ** The proxy lock file path for the database at dbPath is written into lPath,
31360 ** which must point to valid, writable memory large enough for a maxLen length
31361 ** file path.
31363 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
31364 int len;
31365 int dbLen;
31366 int i;
31368 #ifdef LOCKPROXYDIR
31369 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
31370 #else
31371 # ifdef _CS_DARWIN_USER_TEMP_DIR
31373 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
31374 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
31375 lPath, errno, getpid()));
31376 return SQLITE_IOERR_LOCK;
31378 len = strlcat(lPath, "sqliteplocks", maxLen);
31380 # else
31381 len = strlcpy(lPath, "/tmp/", maxLen);
31382 # endif
31383 #endif
31385 if( lPath[len-1]!='/' ){
31386 len = strlcat(lPath, "/", maxLen);
31389 /* transform the db path to a unique cache name */
31390 dbLen = (int)strlen(dbPath);
31391 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
31392 char c = dbPath[i];
31393 lPath[i+len] = (c=='/')?'_':c;
31395 lPath[i+len]='\0';
31396 strlcat(lPath, ":auto:", maxLen);
31397 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
31398 return SQLITE_OK;
31402 ** Creates the lock file and any missing directories in lockPath
31404 static int proxyCreateLockPath(const char *lockPath){
31405 int i, len;
31406 char buf[MAXPATHLEN];
31407 int start = 0;
31409 assert(lockPath!=NULL);
31410 /* try to create all the intermediate directories */
31411 len = (int)strlen(lockPath);
31412 buf[0] = lockPath[0];
31413 for( i=1; i<len; i++ ){
31414 if( lockPath[i] == '/' && (i - start > 0) ){
31415 /* only mkdir if leaf dir != "." or "/" or ".." */
31416 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
31417 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
31418 buf[i]='\0';
31419 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
31420 int err=errno;
31421 if( err!=EEXIST ) {
31422 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
31423 "'%s' proxy lock path=%s pid=%d\n",
31424 buf, strerror(err), lockPath, getpid()));
31425 return err;
31429 start=i+1;
31431 buf[i] = lockPath[i];
31433 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
31434 return 0;
31438 ** Create a new VFS file descriptor (stored in memory obtained from
31439 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
31441 ** The caller is responsible not only for closing the file descriptor
31442 ** but also for freeing the memory associated with the file descriptor.
31444 static int proxyCreateUnixFile(
31445 const char *path, /* path for the new unixFile */
31446 unixFile **ppFile, /* unixFile created and returned by ref */
31447 int islockfile /* if non zero missing dirs will be created */
31449 int fd = -1;
31450 unixFile *pNew;
31451 int rc = SQLITE_OK;
31452 int openFlags = O_RDWR | O_CREAT;
31453 sqlite3_vfs dummyVfs;
31454 int terrno = 0;
31455 UnixUnusedFd *pUnused = NULL;
31457 /* 1. first try to open/create the file
31458 ** 2. if that fails, and this is a lock file (not-conch), try creating
31459 ** the parent directories and then try again.
31460 ** 3. if that fails, try to open the file read-only
31461 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
31463 pUnused = findReusableFd(path, openFlags);
31464 if( pUnused ){
31465 fd = pUnused->fd;
31466 }else{
31467 pUnused = sqlite3_malloc(sizeof(*pUnused));
31468 if( !pUnused ){
31469 return SQLITE_NOMEM;
31472 if( fd<0 ){
31473 fd = robust_open(path, openFlags, 0);
31474 terrno = errno;
31475 if( fd<0 && errno==ENOENT && islockfile ){
31476 if( proxyCreateLockPath(path) == SQLITE_OK ){
31477 fd = robust_open(path, openFlags, 0);
31481 if( fd<0 ){
31482 openFlags = O_RDONLY;
31483 fd = robust_open(path, openFlags, 0);
31484 terrno = errno;
31486 if( fd<0 ){
31487 if( islockfile ){
31488 return SQLITE_BUSY;
31490 switch (terrno) {
31491 case EACCES:
31492 return SQLITE_PERM;
31493 case EIO:
31494 return SQLITE_IOERR_LOCK; /* even though it is the conch */
31495 default:
31496 return SQLITE_CANTOPEN_BKPT;
31500 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
31501 if( pNew==NULL ){
31502 rc = SQLITE_NOMEM;
31503 goto end_create_proxy;
31505 memset(pNew, 0, sizeof(unixFile));
31506 pNew->openFlags = openFlags;
31507 memset(&dummyVfs, 0, sizeof(dummyVfs));
31508 dummyVfs.pAppData = (void*)&autolockIoFinder;
31509 dummyVfs.zName = "dummy";
31510 pUnused->fd = fd;
31511 pUnused->flags = openFlags;
31512 pNew->pUnused = pUnused;
31514 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
31515 if( rc==SQLITE_OK ){
31516 *ppFile = pNew;
31517 return SQLITE_OK;
31519 end_create_proxy:
31520 robust_close(pNew, fd, __LINE__);
31521 sqlite3_free(pNew);
31522 sqlite3_free(pUnused);
31523 return rc;
31526 #ifdef SQLITE_TEST
31527 /* simulate multiple hosts by creating unique hostid file paths */
31528 SQLITE_API int sqlite3_hostid_num = 0;
31529 #endif
31531 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
31533 /* Not always defined in the headers as it ought to be */
31534 extern int gethostuuid(uuid_t id, const struct timespec *wait);
31536 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
31537 ** bytes of writable memory.
31539 static int proxyGetHostID(unsigned char *pHostID, int *pError){
31540 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
31541 memset(pHostID, 0, PROXY_HOSTIDLEN);
31542 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
31543 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
31545 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
31546 if( gethostuuid(pHostID, &timeout) ){
31547 int err = errno;
31548 if( pError ){
31549 *pError = err;
31551 return SQLITE_IOERR;
31554 #else
31555 UNUSED_PARAMETER(pError);
31556 #endif
31557 #ifdef SQLITE_TEST
31558 /* simulate multiple hosts by creating unique hostid file paths */
31559 if( sqlite3_hostid_num != 0){
31560 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
31562 #endif
31564 return SQLITE_OK;
31567 /* The conch file contains the header, host id and lock file path
31569 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
31570 #define PROXY_HEADERLEN 1 /* conch file header length */
31571 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
31572 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
31575 ** Takes an open conch file, copies the contents to a new path and then moves
31576 ** it back. The newly created file's file descriptor is assigned to the
31577 ** conch file structure and finally the original conch file descriptor is
31578 ** closed. Returns zero if successful.
31580 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
31581 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31582 unixFile *conchFile = pCtx->conchFile;
31583 char tPath[MAXPATHLEN];
31584 char buf[PROXY_MAXCONCHLEN];
31585 char *cPath = pCtx->conchFilePath;
31586 size_t readLen = 0;
31587 size_t pathLen = 0;
31588 char errmsg[64] = "";
31589 int fd = -1;
31590 int rc = -1;
31591 UNUSED_PARAMETER(myHostID);
31593 /* create a new path by replace the trailing '-conch' with '-break' */
31594 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
31595 if( pathLen>MAXPATHLEN || pathLen<6 ||
31596 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
31597 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
31598 goto end_breaklock;
31600 /* read the conch content */
31601 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
31602 if( readLen<PROXY_PATHINDEX ){
31603 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
31604 goto end_breaklock;
31606 /* write it out to the temporary break file */
31607 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
31608 if( fd<0 ){
31609 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
31610 goto end_breaklock;
31612 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
31613 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
31614 goto end_breaklock;
31616 if( rename(tPath, cPath) ){
31617 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
31618 goto end_breaklock;
31620 rc = 0;
31621 fprintf(stderr, "broke stale lock on %s\n", cPath);
31622 robust_close(pFile, conchFile->h, __LINE__);
31623 conchFile->h = fd;
31624 conchFile->openFlags = O_RDWR | O_CREAT;
31626 end_breaklock:
31627 if( rc ){
31628 if( fd>=0 ){
31629 osUnlink(tPath);
31630 robust_close(pFile, fd, __LINE__);
31632 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
31634 return rc;
31637 /* Take the requested lock on the conch file and break a stale lock if the
31638 ** host id matches.
31640 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
31641 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31642 unixFile *conchFile = pCtx->conchFile;
31643 int rc = SQLITE_OK;
31644 int nTries = 0;
31645 struct timespec conchModTime;
31647 memset(&conchModTime, 0, sizeof(conchModTime));
31648 do {
31649 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
31650 nTries ++;
31651 if( rc==SQLITE_BUSY ){
31652 /* If the lock failed (busy):
31653 * 1st try: get the mod time of the conch, wait 0.5s and try again.
31654 * 2nd try: fail if the mod time changed or host id is different, wait
31655 * 10 sec and try again
31656 * 3rd try: break the lock unless the mod time has changed.
31658 struct stat buf;
31659 if( osFstat(conchFile->h, &buf) ){
31660 pFile->lastErrno = errno;
31661 return SQLITE_IOERR_LOCK;
31664 if( nTries==1 ){
31665 conchModTime = buf.st_mtimespec;
31666 usleep(500000); /* wait 0.5 sec and try the lock again*/
31667 continue;
31670 assert( nTries>1 );
31671 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
31672 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
31673 return SQLITE_BUSY;
31676 if( nTries==2 ){
31677 char tBuf[PROXY_MAXCONCHLEN];
31678 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
31679 if( len<0 ){
31680 pFile->lastErrno = errno;
31681 return SQLITE_IOERR_LOCK;
31683 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
31684 /* don't break the lock if the host id doesn't match */
31685 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
31686 return SQLITE_BUSY;
31688 }else{
31689 /* don't break the lock on short read or a version mismatch */
31690 return SQLITE_BUSY;
31692 usleep(10000000); /* wait 10 sec and try the lock again */
31693 continue;
31696 assert( nTries==3 );
31697 if( 0==proxyBreakConchLock(pFile, myHostID) ){
31698 rc = SQLITE_OK;
31699 if( lockType==EXCLUSIVE_LOCK ){
31700 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
31702 if( !rc ){
31703 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
31707 } while( rc==SQLITE_BUSY && nTries<3 );
31709 return rc;
31712 /* Takes the conch by taking a shared lock and read the contents conch, if
31713 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
31714 ** lockPath means that the lockPath in the conch file will be used if the
31715 ** host IDs match, or a new lock path will be generated automatically
31716 ** and written to the conch file.
31718 static int proxyTakeConch(unixFile *pFile){
31719 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31721 if( pCtx->conchHeld!=0 ){
31722 return SQLITE_OK;
31723 }else{
31724 unixFile *conchFile = pCtx->conchFile;
31725 uuid_t myHostID;
31726 int pError = 0;
31727 char readBuf[PROXY_MAXCONCHLEN];
31728 char lockPath[MAXPATHLEN];
31729 char *tempLockPath = NULL;
31730 int rc = SQLITE_OK;
31731 int createConch = 0;
31732 int hostIdMatch = 0;
31733 int readLen = 0;
31734 int tryOldLockPath = 0;
31735 int forceNewLockPath = 0;
31737 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
31738 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
31740 rc = proxyGetHostID(myHostID, &pError);
31741 if( (rc&0xff)==SQLITE_IOERR ){
31742 pFile->lastErrno = pError;
31743 goto end_takeconch;
31745 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
31746 if( rc!=SQLITE_OK ){
31747 goto end_takeconch;
31749 /* read the existing conch file */
31750 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
31751 if( readLen<0 ){
31752 /* I/O error: lastErrno set by seekAndRead */
31753 pFile->lastErrno = conchFile->lastErrno;
31754 rc = SQLITE_IOERR_READ;
31755 goto end_takeconch;
31756 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
31757 readBuf[0]!=(char)PROXY_CONCHVERSION ){
31758 /* a short read or version format mismatch means we need to create a new
31759 ** conch file.
31761 createConch = 1;
31763 /* if the host id matches and the lock path already exists in the conch
31764 ** we'll try to use the path there, if we can't open that path, we'll
31765 ** retry with a new auto-generated path
31767 do { /* in case we need to try again for an :auto: named lock file */
31769 if( !createConch && !forceNewLockPath ){
31770 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
31771 PROXY_HOSTIDLEN);
31772 /* if the conch has data compare the contents */
31773 if( !pCtx->lockProxyPath ){
31774 /* for auto-named local lock file, just check the host ID and we'll
31775 ** use the local lock file path that's already in there
31777 if( hostIdMatch ){
31778 size_t pathLen = (readLen - PROXY_PATHINDEX);
31780 if( pathLen>=MAXPATHLEN ){
31781 pathLen=MAXPATHLEN-1;
31783 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
31784 lockPath[pathLen] = 0;
31785 tempLockPath = lockPath;
31786 tryOldLockPath = 1;
31787 /* create a copy of the lock path if the conch is taken */
31788 goto end_takeconch;
31790 }else if( hostIdMatch
31791 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
31792 readLen-PROXY_PATHINDEX)
31794 /* conch host and lock path match */
31795 goto end_takeconch;
31799 /* if the conch isn't writable and doesn't match, we can't take it */
31800 if( (conchFile->openFlags&O_RDWR) == 0 ){
31801 rc = SQLITE_BUSY;
31802 goto end_takeconch;
31805 /* either the conch didn't match or we need to create a new one */
31806 if( !pCtx->lockProxyPath ){
31807 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
31808 tempLockPath = lockPath;
31809 /* create a copy of the lock path _only_ if the conch is taken */
31812 /* update conch with host and path (this will fail if other process
31813 ** has a shared lock already), if the host id matches, use the big
31814 ** stick.
31816 futimes(conchFile->h, NULL);
31817 if( hostIdMatch && !createConch ){
31818 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
31819 /* We are trying for an exclusive lock but another thread in this
31820 ** same process is still holding a shared lock. */
31821 rc = SQLITE_BUSY;
31822 } else {
31823 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
31825 }else{
31826 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
31828 if( rc==SQLITE_OK ){
31829 char writeBuffer[PROXY_MAXCONCHLEN];
31830 int writeSize = 0;
31832 writeBuffer[0] = (char)PROXY_CONCHVERSION;
31833 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
31834 if( pCtx->lockProxyPath!=NULL ){
31835 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
31836 }else{
31837 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
31839 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
31840 robust_ftruncate(conchFile->h, writeSize);
31841 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
31842 fsync(conchFile->h);
31843 /* If we created a new conch file (not just updated the contents of a
31844 ** valid conch file), try to match the permissions of the database
31846 if( rc==SQLITE_OK && createConch ){
31847 struct stat buf;
31848 int err = osFstat(pFile->h, &buf);
31849 if( err==0 ){
31850 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
31851 S_IROTH|S_IWOTH);
31852 /* try to match the database file R/W permissions, ignore failure */
31853 #ifndef SQLITE_PROXY_DEBUG
31854 osFchmod(conchFile->h, cmode);
31855 #else
31857 rc = osFchmod(conchFile->h, cmode);
31858 }while( rc==(-1) && errno==EINTR );
31859 if( rc!=0 ){
31860 int code = errno;
31861 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
31862 cmode, code, strerror(code));
31863 } else {
31864 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
31866 }else{
31867 int code = errno;
31868 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
31869 err, code, strerror(code));
31870 #endif
31874 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
31876 end_takeconch:
31877 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
31878 if( rc==SQLITE_OK && pFile->openFlags ){
31879 int fd;
31880 if( pFile->h>=0 ){
31881 robust_close(pFile, pFile->h, __LINE__);
31883 pFile->h = -1;
31884 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
31885 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
31886 if( fd>=0 ){
31887 pFile->h = fd;
31888 }else{
31889 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
31890 during locking */
31893 if( rc==SQLITE_OK && !pCtx->lockProxy ){
31894 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
31895 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
31896 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
31897 /* we couldn't create the proxy lock file with the old lock file path
31898 ** so try again via auto-naming
31900 forceNewLockPath = 1;
31901 tryOldLockPath = 0;
31902 continue; /* go back to the do {} while start point, try again */
31905 if( rc==SQLITE_OK ){
31906 /* Need to make a copy of path if we extracted the value
31907 ** from the conch file or the path was allocated on the stack
31909 if( tempLockPath ){
31910 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
31911 if( !pCtx->lockProxyPath ){
31912 rc = SQLITE_NOMEM;
31916 if( rc==SQLITE_OK ){
31917 pCtx->conchHeld = 1;
31919 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
31920 afpLockingContext *afpCtx;
31921 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
31922 afpCtx->dbPath = pCtx->lockProxyPath;
31924 } else {
31925 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
31927 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
31928 rc==SQLITE_OK?"ok":"failed"));
31929 return rc;
31930 } while (1); /* in case we need to retry the :auto: lock file -
31931 ** we should never get here except via the 'continue' call. */
31936 ** If pFile holds a lock on a conch file, then release that lock.
31938 static int proxyReleaseConch(unixFile *pFile){
31939 int rc = SQLITE_OK; /* Subroutine return code */
31940 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
31941 unixFile *conchFile; /* Name of the conch file */
31943 pCtx = (proxyLockingContext *)pFile->lockingContext;
31944 conchFile = pCtx->conchFile;
31945 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
31946 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
31947 getpid()));
31948 if( pCtx->conchHeld>0 ){
31949 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
31951 pCtx->conchHeld = 0;
31952 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
31953 (rc==SQLITE_OK ? "ok" : "failed")));
31954 return rc;
31958 ** Given the name of a database file, compute the name of its conch file.
31959 ** Store the conch filename in memory obtained from sqlite3_malloc().
31960 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
31961 ** or SQLITE_NOMEM if unable to obtain memory.
31963 ** The caller is responsible for ensuring that the allocated memory
31964 ** space is eventually freed.
31966 ** *pConchPath is set to NULL if a memory allocation error occurs.
31968 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
31969 int i; /* Loop counter */
31970 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
31971 char *conchPath; /* buffer in which to construct conch name */
31973 /* Allocate space for the conch filename and initialize the name to
31974 ** the name of the original database file. */
31975 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
31976 if( conchPath==0 ){
31977 return SQLITE_NOMEM;
31979 memcpy(conchPath, dbPath, len+1);
31981 /* now insert a "." before the last / character */
31982 for( i=(len-1); i>=0; i-- ){
31983 if( conchPath[i]=='/' ){
31984 i++;
31985 break;
31988 conchPath[i]='.';
31989 while ( i<len ){
31990 conchPath[i+1]=dbPath[i];
31991 i++;
31994 /* append the "-conch" suffix to the file */
31995 memcpy(&conchPath[i+1], "-conch", 7);
31996 assert( (int)strlen(conchPath) == len+7 );
31998 return SQLITE_OK;
32002 /* Takes a fully configured proxy locking-style unix file and switches
32003 ** the local lock file path
32005 static int switchLockProxyPath(unixFile *pFile, const char *path) {
32006 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
32007 char *oldPath = pCtx->lockProxyPath;
32008 int rc = SQLITE_OK;
32010 if( pFile->eFileLock!=NO_LOCK ){
32011 return SQLITE_BUSY;
32014 /* nothing to do if the path is NULL, :auto: or matches the existing path */
32015 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
32016 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
32017 return SQLITE_OK;
32018 }else{
32019 unixFile *lockProxy = pCtx->lockProxy;
32020 pCtx->lockProxy=NULL;
32021 pCtx->conchHeld = 0;
32022 if( lockProxy!=NULL ){
32023 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
32024 if( rc ) return rc;
32025 sqlite3_free(lockProxy);
32027 sqlite3_free(oldPath);
32028 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
32031 return rc;
32035 ** pFile is a file that has been opened by a prior xOpen call. dbPath
32036 ** is a string buffer at least MAXPATHLEN+1 characters in size.
32038 ** This routine find the filename associated with pFile and writes it
32039 ** int dbPath.
32041 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
32042 #if defined(__APPLE__)
32043 if( pFile->pMethod == &afpIoMethods ){
32044 /* afp style keeps a reference to the db path in the filePath field
32045 ** of the struct */
32046 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
32047 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
32048 } else
32049 #endif
32050 if( pFile->pMethod == &dotlockIoMethods ){
32051 /* dot lock style uses the locking context to store the dot lock
32052 ** file path */
32053 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
32054 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
32055 }else{
32056 /* all other styles use the locking context to store the db file path */
32057 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
32058 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
32060 return SQLITE_OK;
32064 ** Takes an already filled in unix file and alters it so all file locking
32065 ** will be performed on the local proxy lock file. The following fields
32066 ** are preserved in the locking context so that they can be restored and
32067 ** the unix structure properly cleaned up at close time:
32068 ** ->lockingContext
32069 ** ->pMethod
32071 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
32072 proxyLockingContext *pCtx;
32073 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
32074 char *lockPath=NULL;
32075 int rc = SQLITE_OK;
32077 if( pFile->eFileLock!=NO_LOCK ){
32078 return SQLITE_BUSY;
32080 proxyGetDbPathForUnixFile(pFile, dbPath);
32081 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
32082 lockPath=NULL;
32083 }else{
32084 lockPath=(char *)path;
32087 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
32088 (lockPath ? lockPath : ":auto:"), getpid()));
32090 pCtx = sqlite3_malloc( sizeof(*pCtx) );
32091 if( pCtx==0 ){
32092 return SQLITE_NOMEM;
32094 memset(pCtx, 0, sizeof(*pCtx));
32096 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
32097 if( rc==SQLITE_OK ){
32098 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
32099 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
32100 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
32101 ** (c) the file system is read-only, then enable no-locking access.
32102 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
32103 ** that openFlags will have only one of O_RDONLY or O_RDWR.
32105 struct statfs fsInfo;
32106 struct stat conchInfo;
32107 int goLockless = 0;
32109 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
32110 int err = errno;
32111 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
32112 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
32115 if( goLockless ){
32116 pCtx->conchHeld = -1; /* read only FS/ lockless */
32117 rc = SQLITE_OK;
32121 if( rc==SQLITE_OK && lockPath ){
32122 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
32125 if( rc==SQLITE_OK ){
32126 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
32127 if( pCtx->dbPath==NULL ){
32128 rc = SQLITE_NOMEM;
32131 if( rc==SQLITE_OK ){
32132 /* all memory is allocated, proxys are created and assigned,
32133 ** switch the locking context and pMethod then return.
32135 pCtx->oldLockingContext = pFile->lockingContext;
32136 pFile->lockingContext = pCtx;
32137 pCtx->pOldMethod = pFile->pMethod;
32138 pFile->pMethod = &proxyIoMethods;
32139 }else{
32140 if( pCtx->conchFile ){
32141 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
32142 sqlite3_free(pCtx->conchFile);
32144 sqlite3DbFree(0, pCtx->lockProxyPath);
32145 sqlite3_free(pCtx->conchFilePath);
32146 sqlite3_free(pCtx);
32148 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
32149 (rc==SQLITE_OK ? "ok" : "failed")));
32150 return rc;
32155 ** This routine handles sqlite3_file_control() calls that are specific
32156 ** to proxy locking.
32158 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
32159 switch( op ){
32160 case SQLITE_GET_LOCKPROXYFILE: {
32161 unixFile *pFile = (unixFile*)id;
32162 if( pFile->pMethod == &proxyIoMethods ){
32163 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
32164 proxyTakeConch(pFile);
32165 if( pCtx->lockProxyPath ){
32166 *(const char **)pArg = pCtx->lockProxyPath;
32167 }else{
32168 *(const char **)pArg = ":auto: (not held)";
32170 } else {
32171 *(const char **)pArg = NULL;
32173 return SQLITE_OK;
32175 case SQLITE_SET_LOCKPROXYFILE: {
32176 unixFile *pFile = (unixFile*)id;
32177 int rc = SQLITE_OK;
32178 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
32179 if( pArg==NULL || (const char *)pArg==0 ){
32180 if( isProxyStyle ){
32181 /* turn off proxy locking - not supported */
32182 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
32183 }else{
32184 /* turn off proxy locking - already off - NOOP */
32185 rc = SQLITE_OK;
32187 }else{
32188 const char *proxyPath = (const char *)pArg;
32189 if( isProxyStyle ){
32190 proxyLockingContext *pCtx =
32191 (proxyLockingContext*)pFile->lockingContext;
32192 if( !strcmp(pArg, ":auto:")
32193 || (pCtx->lockProxyPath &&
32194 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
32196 rc = SQLITE_OK;
32197 }else{
32198 rc = switchLockProxyPath(pFile, proxyPath);
32200 }else{
32201 /* turn on proxy file locking */
32202 rc = proxyTransformUnixFile(pFile, proxyPath);
32205 return rc;
32207 default: {
32208 assert( 0 ); /* The call assures that only valid opcodes are sent */
32211 /*NOTREACHED*/
32212 return SQLITE_ERROR;
32216 ** Within this division (the proxying locking implementation) the procedures
32217 ** above this point are all utilities. The lock-related methods of the
32218 ** proxy-locking sqlite3_io_method object follow.
32223 ** This routine checks if there is a RESERVED lock held on the specified
32224 ** file by this or any other process. If such a lock is held, set *pResOut
32225 ** to a non-zero value otherwise *pResOut is set to zero. The return value
32226 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32228 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
32229 unixFile *pFile = (unixFile*)id;
32230 int rc = proxyTakeConch(pFile);
32231 if( rc==SQLITE_OK ){
32232 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32233 if( pCtx->conchHeld>0 ){
32234 unixFile *proxy = pCtx->lockProxy;
32235 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
32236 }else{ /* conchHeld < 0 is lockless */
32237 pResOut=0;
32240 return rc;
32244 ** Lock the file with the lock specified by parameter eFileLock - one
32245 ** of the following:
32247 ** (1) SHARED_LOCK
32248 ** (2) RESERVED_LOCK
32249 ** (3) PENDING_LOCK
32250 ** (4) EXCLUSIVE_LOCK
32252 ** Sometimes when requesting one lock state, additional lock states
32253 ** are inserted in between. The locking might fail on one of the later
32254 ** transitions leaving the lock state different from what it started but
32255 ** still short of its goal. The following chart shows the allowed
32256 ** transitions and the inserted intermediate states:
32258 ** UNLOCKED -> SHARED
32259 ** SHARED -> RESERVED
32260 ** SHARED -> (PENDING) -> EXCLUSIVE
32261 ** RESERVED -> (PENDING) -> EXCLUSIVE
32262 ** PENDING -> EXCLUSIVE
32264 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
32265 ** routine to lower a locking level.
32267 static int proxyLock(sqlite3_file *id, int eFileLock) {
32268 unixFile *pFile = (unixFile*)id;
32269 int rc = proxyTakeConch(pFile);
32270 if( rc==SQLITE_OK ){
32271 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32272 if( pCtx->conchHeld>0 ){
32273 unixFile *proxy = pCtx->lockProxy;
32274 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
32275 pFile->eFileLock = proxy->eFileLock;
32276 }else{
32277 /* conchHeld < 0 is lockless */
32280 return rc;
32285 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
32286 ** must be either NO_LOCK or SHARED_LOCK.
32288 ** If the locking level of the file descriptor is already at or below
32289 ** the requested locking level, this routine is a no-op.
32291 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
32292 unixFile *pFile = (unixFile*)id;
32293 int rc = proxyTakeConch(pFile);
32294 if( rc==SQLITE_OK ){
32295 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32296 if( pCtx->conchHeld>0 ){
32297 unixFile *proxy = pCtx->lockProxy;
32298 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
32299 pFile->eFileLock = proxy->eFileLock;
32300 }else{
32301 /* conchHeld < 0 is lockless */
32304 return rc;
32308 ** Close a file that uses proxy locks.
32310 static int proxyClose(sqlite3_file *id) {
32311 if( id ){
32312 unixFile *pFile = (unixFile*)id;
32313 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32314 unixFile *lockProxy = pCtx->lockProxy;
32315 unixFile *conchFile = pCtx->conchFile;
32316 int rc = SQLITE_OK;
32318 if( lockProxy ){
32319 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
32320 if( rc ) return rc;
32321 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
32322 if( rc ) return rc;
32323 sqlite3_free(lockProxy);
32324 pCtx->lockProxy = 0;
32326 if( conchFile ){
32327 if( pCtx->conchHeld ){
32328 rc = proxyReleaseConch(pFile);
32329 if( rc ) return rc;
32331 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
32332 if( rc ) return rc;
32333 sqlite3_free(conchFile);
32335 sqlite3DbFree(0, pCtx->lockProxyPath);
32336 sqlite3_free(pCtx->conchFilePath);
32337 sqlite3DbFree(0, pCtx->dbPath);
32338 /* restore the original locking context and pMethod then close it */
32339 pFile->lockingContext = pCtx->oldLockingContext;
32340 pFile->pMethod = pCtx->pOldMethod;
32341 sqlite3_free(pCtx);
32342 return pFile->pMethod->xClose(id);
32344 return SQLITE_OK;
32349 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32351 ** The proxy locking style is intended for use with AFP filesystems.
32352 ** And since AFP is only supported on MacOSX, the proxy locking is also
32353 ** restricted to MacOSX.
32356 ******************* End of the proxy lock implementation **********************
32357 ******************************************************************************/
32360 ** Initialize the operating system interface.
32362 ** This routine registers all VFS implementations for unix-like operating
32363 ** systems. This routine, and the sqlite3_os_end() routine that follows,
32364 ** should be the only routines in this file that are visible from other
32365 ** files.
32367 ** This routine is called once during SQLite initialization and by a
32368 ** single thread. The memory allocation and mutex subsystems have not
32369 ** necessarily been initialized when this routine is called, and so they
32370 ** should not be used.
32372 SQLITE_API int sqlite3_os_init(void){
32374 ** The following macro defines an initializer for an sqlite3_vfs object.
32375 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
32376 ** to the "finder" function. (pAppData is a pointer to a pointer because
32377 ** silly C90 rules prohibit a void* from being cast to a function pointer
32378 ** and so we have to go through the intermediate pointer to avoid problems
32379 ** when compiling with -pedantic-errors on GCC.)
32381 ** The FINDER parameter to this macro is the name of the pointer to the
32382 ** finder-function. The finder-function returns a pointer to the
32383 ** sqlite_io_methods object that implements the desired locking
32384 ** behaviors. See the division above that contains the IOMETHODS
32385 ** macro for addition information on finder-functions.
32387 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
32388 ** object. But the "autolockIoFinder" available on MacOSX does a little
32389 ** more than that; it looks at the filesystem type that hosts the
32390 ** database file and tries to choose an locking method appropriate for
32391 ** that filesystem time.
32393 #define UNIXVFS(VFSNAME, FINDER) { \
32394 3, /* iVersion */ \
32395 sizeof(unixFile), /* szOsFile */ \
32396 MAX_PATHNAME, /* mxPathname */ \
32397 0, /* pNext */ \
32398 VFSNAME, /* zName */ \
32399 (void*)&FINDER, /* pAppData */ \
32400 unixOpen, /* xOpen */ \
32401 unixDelete, /* xDelete */ \
32402 unixAccess, /* xAccess */ \
32403 unixFullPathname, /* xFullPathname */ \
32404 unixDlOpen, /* xDlOpen */ \
32405 unixDlError, /* xDlError */ \
32406 unixDlSym, /* xDlSym */ \
32407 unixDlClose, /* xDlClose */ \
32408 unixRandomness, /* xRandomness */ \
32409 unixSleep, /* xSleep */ \
32410 unixCurrentTime, /* xCurrentTime */ \
32411 unixGetLastError, /* xGetLastError */ \
32412 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
32413 unixSetSystemCall, /* xSetSystemCall */ \
32414 unixGetSystemCall, /* xGetSystemCall */ \
32415 unixNextSystemCall, /* xNextSystemCall */ \
32419 ** All default VFSes for unix are contained in the following array.
32421 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
32422 ** by the SQLite core when the VFS is registered. So the following
32423 ** array cannot be const.
32425 static sqlite3_vfs aVfs[] = {
32426 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
32427 UNIXVFS("unix", autolockIoFinder ),
32428 #else
32429 UNIXVFS("unix", posixIoFinder ),
32430 #endif
32431 UNIXVFS("unix-none", nolockIoFinder ),
32432 UNIXVFS("unix-dotfile", dotlockIoFinder ),
32433 UNIXVFS("unix-excl", posixIoFinder ),
32434 #if OS_VXWORKS
32435 UNIXVFS("unix-namedsem", semIoFinder ),
32436 #endif
32437 #if SQLITE_ENABLE_LOCKING_STYLE
32438 UNIXVFS("unix-posix", posixIoFinder ),
32439 #if !OS_VXWORKS
32440 UNIXVFS("unix-flock", flockIoFinder ),
32441 #endif
32442 #endif
32443 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
32444 UNIXVFS("unix-afp", afpIoFinder ),
32445 UNIXVFS("unix-nfs", nfsIoFinder ),
32446 UNIXVFS("unix-proxy", proxyIoFinder ),
32447 #endif
32449 unsigned int i; /* Loop counter */
32451 /* Double-check that the aSyscall[] array has been constructed
32452 ** correctly. See ticket [bb3a86e890c8e96ab] */
32453 assert( ArraySize(aSyscall)==25 );
32455 /* Register all VFSes defined in the aVfs[] array */
32456 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
32457 sqlite3_vfs_register(&aVfs[i], i==0);
32459 return SQLITE_OK;
32463 ** Shutdown the operating system interface.
32465 ** Some operating systems might need to do some cleanup in this routine,
32466 ** to release dynamically allocated objects. But not on unix.
32467 ** This routine is a no-op for unix.
32469 SQLITE_API int sqlite3_os_end(void){
32470 return SQLITE_OK;
32473 #endif /* SQLITE_OS_UNIX */
32475 /************** End of os_unix.c *********************************************/
32476 /************** Begin file os_win.c ******************************************/
32478 ** 2004 May 22
32480 ** The author disclaims copyright to this source code. In place of
32481 ** a legal notice, here is a blessing:
32483 ** May you do good and not evil.
32484 ** May you find forgiveness for yourself and forgive others.
32485 ** May you share freely, never taking more than you give.
32487 ******************************************************************************
32489 ** This file contains code that is specific to Windows.
32491 #if SQLITE_OS_WIN /* This file is used for Windows only */
32494 ** Include code that is common to all os_*.c files
32496 /************** Include os_common.h in the middle of os_win.c ****************/
32497 /************** Begin file os_common.h ***************************************/
32499 ** 2004 May 22
32501 ** The author disclaims copyright to this source code. In place of
32502 ** a legal notice, here is a blessing:
32504 ** May you do good and not evil.
32505 ** May you find forgiveness for yourself and forgive others.
32506 ** May you share freely, never taking more than you give.
32508 ******************************************************************************
32510 ** This file contains macros and a little bit of code that is common to
32511 ** all of the platform-specific files (os_*.c) and is #included into those
32512 ** files.
32514 ** This file should be #included by the os_*.c files only. It is not a
32515 ** general purpose header file.
32517 #ifndef _OS_COMMON_H_
32518 #define _OS_COMMON_H_
32521 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
32522 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
32523 ** switch. The following code should catch this problem at compile-time.
32525 #ifdef MEMORY_DEBUG
32526 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
32527 #endif
32529 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
32530 # ifndef SQLITE_DEBUG_OS_TRACE
32531 # define SQLITE_DEBUG_OS_TRACE 0
32532 # endif
32533 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
32534 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
32535 #else
32536 # define OSTRACE(X)
32537 #endif
32540 ** Macros for performance tracing. Normally turned off. Only works
32541 ** on i486 hardware.
32543 #ifdef SQLITE_PERFORMANCE_TRACE
32546 ** hwtime.h contains inline assembler code for implementing
32547 ** high-performance timing routines.
32549 /************** Include hwtime.h in the middle of os_common.h ****************/
32550 /************** Begin file hwtime.h ******************************************/
32552 ** 2008 May 27
32554 ** The author disclaims copyright to this source code. In place of
32555 ** a legal notice, here is a blessing:
32557 ** May you do good and not evil.
32558 ** May you find forgiveness for yourself and forgive others.
32559 ** May you share freely, never taking more than you give.
32561 ******************************************************************************
32563 ** This file contains inline asm code for retrieving "high-performance"
32564 ** counters for x86 class CPUs.
32566 #ifndef _HWTIME_H_
32567 #define _HWTIME_H_
32570 ** The following routine only works on pentium-class (or newer) processors.
32571 ** It uses the RDTSC opcode to read the cycle count value out of the
32572 ** processor and returns that value. This can be used for high-res
32573 ** profiling.
32575 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
32576 (defined(i386) || defined(__i386__) || defined(_M_IX86))
32578 #if defined(__GNUC__)
32580 __inline__ sqlite_uint64 sqlite3Hwtime(void){
32581 unsigned int lo, hi;
32582 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
32583 return (sqlite_uint64)hi << 32 | lo;
32586 #elif defined(_MSC_VER)
32588 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
32589 __asm {
32590 rdtsc
32591 ret ; return value at EDX:EAX
32595 #endif
32597 #elif (defined(__GNUC__) && defined(__x86_64__))
32599 __inline__ sqlite_uint64 sqlite3Hwtime(void){
32600 unsigned long val;
32601 __asm__ __volatile__ ("rdtsc" : "=A" (val));
32602 return val;
32605 #elif (defined(__GNUC__) && defined(__ppc__))
32607 __inline__ sqlite_uint64 sqlite3Hwtime(void){
32608 unsigned long long retval;
32609 unsigned long junk;
32610 __asm__ __volatile__ ("\n\
32611 1: mftbu %1\n\
32612 mftb %L0\n\
32613 mftbu %0\n\
32614 cmpw %0,%1\n\
32615 bne 1b"
32616 : "=r" (retval), "=r" (junk));
32617 return retval;
32620 #else
32622 #error Need implementation of sqlite3Hwtime() for your platform.
32625 ** To compile without implementing sqlite3Hwtime() for your platform,
32626 ** you can remove the above #error and use the following
32627 ** stub function. You will lose timing support for many
32628 ** of the debugging and testing utilities, but it should at
32629 ** least compile and run.
32631 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
32633 #endif
32635 #endif /* !defined(_HWTIME_H_) */
32637 /************** End of hwtime.h **********************************************/
32638 /************** Continuing where we left off in os_common.h ******************/
32640 static sqlite_uint64 g_start;
32641 static sqlite_uint64 g_elapsed;
32642 #define TIMER_START g_start=sqlite3Hwtime()
32643 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
32644 #define TIMER_ELAPSED g_elapsed
32645 #else
32646 #define TIMER_START
32647 #define TIMER_END
32648 #define TIMER_ELAPSED ((sqlite_uint64)0)
32649 #endif
32652 ** If we compile with the SQLITE_TEST macro set, then the following block
32653 ** of code will give us the ability to simulate a disk I/O error. This
32654 ** is used for testing the I/O recovery logic.
32656 #ifdef SQLITE_TEST
32657 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
32658 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
32659 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
32660 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
32661 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
32662 SQLITE_API int sqlite3_diskfull_pending = 0;
32663 SQLITE_API int sqlite3_diskfull = 0;
32664 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
32665 #define SimulateIOError(CODE) \
32666 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
32667 || sqlite3_io_error_pending-- == 1 ) \
32668 { local_ioerr(); CODE; }
32669 static void local_ioerr(){
32670 IOTRACE(("IOERR\n"));
32671 sqlite3_io_error_hit++;
32672 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
32674 #define SimulateDiskfullError(CODE) \
32675 if( sqlite3_diskfull_pending ){ \
32676 if( sqlite3_diskfull_pending == 1 ){ \
32677 local_ioerr(); \
32678 sqlite3_diskfull = 1; \
32679 sqlite3_io_error_hit = 1; \
32680 CODE; \
32681 }else{ \
32682 sqlite3_diskfull_pending--; \
32685 #else
32686 #define SimulateIOErrorBenign(X)
32687 #define SimulateIOError(A)
32688 #define SimulateDiskfullError(A)
32689 #endif
32692 ** When testing, keep a count of the number of open files.
32694 #ifdef SQLITE_TEST
32695 SQLITE_API int sqlite3_open_file_count = 0;
32696 #define OpenCounter(X) sqlite3_open_file_count+=(X)
32697 #else
32698 #define OpenCounter(X)
32699 #endif
32701 #endif /* !defined(_OS_COMMON_H_) */
32703 /************** End of os_common.h *******************************************/
32704 /************** Continuing where we left off in os_win.c *********************/
32707 ** Include the header file for the Windows VFS.
32711 ** Compiling and using WAL mode requires several APIs that are only
32712 ** available in Windows platforms based on the NT kernel.
32714 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
32715 # error "WAL mode requires support from the Windows NT kernel, compile\
32716 with SQLITE_OMIT_WAL."
32717 #endif
32720 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
32721 ** based on the sub-platform)?
32723 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
32724 # define SQLITE_WIN32_HAS_ANSI
32725 #endif
32728 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
32729 ** based on the sub-platform)?
32731 #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
32732 !defined(SQLITE_WIN32_NO_WIDE)
32733 # define SQLITE_WIN32_HAS_WIDE
32734 #endif
32737 ** Make sure at least one set of Win32 APIs is available.
32739 #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
32740 # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
32741 must be defined."
32742 #endif
32745 ** Define the required Windows SDK version constants if they are not
32746 ** already available.
32748 #ifndef NTDDI_WIN8
32749 # define NTDDI_WIN8 0x06020000
32750 #endif
32752 #ifndef NTDDI_WINBLUE
32753 # define NTDDI_WINBLUE 0x06030000
32754 #endif
32757 ** Check to see if the GetVersionEx[AW] functions are deprecated on the
32758 ** target system. GetVersionEx was first deprecated in Win8.1.
32760 #ifndef SQLITE_WIN32_GETVERSIONEX
32761 # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
32762 # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
32763 # else
32764 # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
32765 # endif
32766 #endif
32769 ** This constant should already be defined (in the "WinDef.h" SDK file).
32771 #ifndef MAX_PATH
32772 # define MAX_PATH (260)
32773 #endif
32776 ** Maximum pathname length (in chars) for Win32. This should normally be
32777 ** MAX_PATH.
32779 #ifndef SQLITE_WIN32_MAX_PATH_CHARS
32780 # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
32781 #endif
32784 ** This constant should already be defined (in the "WinNT.h" SDK file).
32786 #ifndef UNICODE_STRING_MAX_CHARS
32787 # define UNICODE_STRING_MAX_CHARS (32767)
32788 #endif
32791 ** Maximum pathname length (in chars) for WinNT. This should normally be
32792 ** UNICODE_STRING_MAX_CHARS.
32794 #ifndef SQLITE_WINNT_MAX_PATH_CHARS
32795 # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
32796 #endif
32799 ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
32800 ** characters, so we allocate 4 bytes per character assuming worst-case of
32801 ** 4-bytes-per-character for UTF8.
32803 #ifndef SQLITE_WIN32_MAX_PATH_BYTES
32804 # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
32805 #endif
32808 ** Maximum pathname length (in bytes) for WinNT. This should normally be
32809 ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
32811 #ifndef SQLITE_WINNT_MAX_PATH_BYTES
32812 # define SQLITE_WINNT_MAX_PATH_BYTES \
32813 (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
32814 #endif
32817 ** Maximum error message length (in chars) for WinRT.
32819 #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
32820 # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
32821 #endif
32824 ** Returns non-zero if the character should be treated as a directory
32825 ** separator.
32827 #ifndef winIsDirSep
32828 # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
32829 #endif
32832 ** This macro is used when a local variable is set to a value that is
32833 ** [sometimes] not used by the code (e.g. via conditional compilation).
32835 #ifndef UNUSED_VARIABLE_VALUE
32836 # define UNUSED_VARIABLE_VALUE(x) (void)(x)
32837 #endif
32840 ** Returns the character that should be used as the directory separator.
32842 #ifndef winGetDirSep
32843 # define winGetDirSep() '\\'
32844 #endif
32847 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
32848 ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
32849 ** are not present in the header file)?
32851 #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
32853 ** Two of the file mapping APIs are different under WinRT. Figure out which
32854 ** set we need.
32856 #if SQLITE_OS_WINRT
32857 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
32858 LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
32860 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
32861 #else
32862 #if defined(SQLITE_WIN32_HAS_ANSI)
32863 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
32864 DWORD, DWORD, DWORD, LPCSTR);
32865 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
32867 #if defined(SQLITE_WIN32_HAS_WIDE)
32868 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
32869 DWORD, DWORD, DWORD, LPCWSTR);
32870 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
32872 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
32873 #endif /* SQLITE_OS_WINRT */
32876 ** This file mapping API is common to both Win32 and WinRT.
32878 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
32879 #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
32882 ** Some Microsoft compilers lack this definition.
32884 #ifndef INVALID_FILE_ATTRIBUTES
32885 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
32886 #endif
32888 #ifndef FILE_FLAG_MASK
32889 # define FILE_FLAG_MASK (0xFF3C0000)
32890 #endif
32892 #ifndef FILE_ATTRIBUTE_MASK
32893 # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
32894 #endif
32896 #ifndef SQLITE_OMIT_WAL
32897 /* Forward references to structures used for WAL */
32898 typedef struct winShm winShm; /* A connection to shared-memory */
32899 typedef struct winShmNode winShmNode; /* A region of shared-memory */
32900 #endif
32903 ** WinCE lacks native support for file locking so we have to fake it
32904 ** with some code of our own.
32906 #if SQLITE_OS_WINCE
32907 typedef struct winceLock {
32908 int nReaders; /* Number of reader locks obtained */
32909 BOOL bPending; /* Indicates a pending lock has been obtained */
32910 BOOL bReserved; /* Indicates a reserved lock has been obtained */
32911 BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
32912 } winceLock;
32913 #endif
32916 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
32917 ** portability layer.
32919 typedef struct winFile winFile;
32920 struct winFile {
32921 const sqlite3_io_methods *pMethod; /*** Must be first ***/
32922 sqlite3_vfs *pVfs; /* The VFS used to open this file */
32923 HANDLE h; /* Handle for accessing the file */
32924 u8 locktype; /* Type of lock currently held on this file */
32925 short sharedLockByte; /* Randomly chosen byte used as a shared lock */
32926 u8 ctrlFlags; /* Flags. See WINFILE_* below */
32927 DWORD lastErrno; /* The Windows errno from the last I/O error */
32928 #ifndef SQLITE_OMIT_WAL
32929 winShm *pShm; /* Instance of shared memory on this file */
32930 #endif
32931 const char *zPath; /* Full pathname of this file */
32932 int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
32933 #if SQLITE_OS_WINCE
32934 LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
32935 HANDLE hMutex; /* Mutex used to control access to shared lock */
32936 HANDLE hShared; /* Shared memory segment used for locking */
32937 winceLock local; /* Locks obtained by this instance of winFile */
32938 winceLock *shared; /* Global shared lock memory for the file */
32939 #endif
32940 #if SQLITE_MAX_MMAP_SIZE>0
32941 int nFetchOut; /* Number of outstanding xFetch references */
32942 HANDLE hMap; /* Handle for accessing memory mapping */
32943 void *pMapRegion; /* Area memory mapped */
32944 sqlite3_int64 mmapSize; /* Usable size of mapped region */
32945 sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
32946 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
32947 #endif
32951 ** Allowed values for winFile.ctrlFlags
32953 #define WINFILE_RDONLY 0x02 /* Connection is read only */
32954 #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
32955 #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
32958 * The size of the buffer used by sqlite3_win32_write_debug().
32960 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
32961 # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
32962 #endif
32965 * The value used with sqlite3_win32_set_directory() to specify that
32966 * the data directory should be changed.
32968 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
32969 # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
32970 #endif
32973 * The value used with sqlite3_win32_set_directory() to specify that
32974 * the temporary directory should be changed.
32976 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
32977 # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
32978 #endif
32981 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
32982 * various Win32 API heap functions instead of our own.
32984 #ifdef SQLITE_WIN32_MALLOC
32987 * If this is non-zero, an isolated heap will be created by the native Win32
32988 * allocator subsystem; otherwise, the default process heap will be used. This
32989 * setting has no effect when compiling for WinRT. By default, this is enabled
32990 * and an isolated heap will be created to store all allocated data.
32992 ******************************************************************************
32993 * WARNING: It is important to note that when this setting is non-zero and the
32994 * winMemShutdown function is called (e.g. by the sqlite3_shutdown
32995 * function), all data that was allocated using the isolated heap will
32996 * be freed immediately and any attempt to access any of that freed
32997 * data will almost certainly result in an immediate access violation.
32998 ******************************************************************************
33000 #ifndef SQLITE_WIN32_HEAP_CREATE
33001 # define SQLITE_WIN32_HEAP_CREATE (TRUE)
33002 #endif
33005 * The initial size of the Win32-specific heap. This value may be zero.
33007 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
33008 # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
33009 (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
33010 #endif
33013 * The maximum size of the Win32-specific heap. This value may be zero.
33015 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
33016 # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
33017 #endif
33020 * The extra flags to use in calls to the Win32 heap APIs. This value may be
33021 * zero for the default behavior.
33023 #ifndef SQLITE_WIN32_HEAP_FLAGS
33024 # define SQLITE_WIN32_HEAP_FLAGS (0)
33025 #endif
33029 ** The winMemData structure stores information required by the Win32-specific
33030 ** sqlite3_mem_methods implementation.
33032 typedef struct winMemData winMemData;
33033 struct winMemData {
33034 #ifndef NDEBUG
33035 u32 magic1; /* Magic number to detect structure corruption. */
33036 #endif
33037 HANDLE hHeap; /* The handle to our heap. */
33038 BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
33039 #ifndef NDEBUG
33040 u32 magic2; /* Magic number to detect structure corruption. */
33041 #endif
33044 #ifndef NDEBUG
33045 #define WINMEM_MAGIC1 0x42b2830b
33046 #define WINMEM_MAGIC2 0xbd4d7cf4
33047 #endif
33049 static struct winMemData win_mem_data = {
33050 #ifndef NDEBUG
33051 WINMEM_MAGIC1,
33052 #endif
33053 NULL, FALSE
33054 #ifndef NDEBUG
33055 ,WINMEM_MAGIC2
33056 #endif
33059 #ifndef NDEBUG
33060 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
33061 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
33062 #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
33063 #else
33064 #define winMemAssertMagic()
33065 #endif
33067 #define winMemGetDataPtr() &win_mem_data
33068 #define winMemGetHeap() win_mem_data.hHeap
33069 #define winMemGetOwned() win_mem_data.bOwned
33071 static void *winMemMalloc(int nBytes);
33072 static void winMemFree(void *pPrior);
33073 static void *winMemRealloc(void *pPrior, int nBytes);
33074 static int winMemSize(void *p);
33075 static int winMemRoundup(int n);
33076 static int winMemInit(void *pAppData);
33077 static void winMemShutdown(void *pAppData);
33079 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
33080 #endif /* SQLITE_WIN32_MALLOC */
33083 ** The following variable is (normally) set once and never changes
33084 ** thereafter. It records whether the operating system is Win9x
33085 ** or WinNT.
33087 ** 0: Operating system unknown.
33088 ** 1: Operating system is Win9x.
33089 ** 2: Operating system is WinNT.
33091 ** In order to facilitate testing on a WinNT system, the test fixture
33092 ** can manually set this value to 1 to emulate Win98 behavior.
33094 #ifdef SQLITE_TEST
33095 SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
33096 #else
33097 static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
33098 #endif
33100 #ifndef SYSCALL
33101 # define SYSCALL sqlite3_syscall_ptr
33102 #endif
33105 ** This function is not available on Windows CE or WinRT.
33108 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
33109 # define osAreFileApisANSI() 1
33110 #endif
33113 ** Many system calls are accessed through pointer-to-functions so that
33114 ** they may be overridden at runtime to facilitate fault injection during
33115 ** testing and sandboxing. The following array holds the names and pointers
33116 ** to all overrideable system calls.
33118 static struct win_syscall {
33119 const char *zName; /* Name of the system call */
33120 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
33121 sqlite3_syscall_ptr pDefault; /* Default value */
33122 } aSyscall[] = {
33123 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33124 { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
33125 #else
33126 { "AreFileApisANSI", (SYSCALL)0, 0 },
33127 #endif
33129 #ifndef osAreFileApisANSI
33130 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
33131 #endif
33133 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
33134 { "CharLowerW", (SYSCALL)CharLowerW, 0 },
33135 #else
33136 { "CharLowerW", (SYSCALL)0, 0 },
33137 #endif
33139 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
33141 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
33142 { "CharUpperW", (SYSCALL)CharUpperW, 0 },
33143 #else
33144 { "CharUpperW", (SYSCALL)0, 0 },
33145 #endif
33147 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
33149 { "CloseHandle", (SYSCALL)CloseHandle, 0 },
33151 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
33153 #if defined(SQLITE_WIN32_HAS_ANSI)
33154 { "CreateFileA", (SYSCALL)CreateFileA, 0 },
33155 #else
33156 { "CreateFileA", (SYSCALL)0, 0 },
33157 #endif
33159 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
33160 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
33162 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33163 { "CreateFileW", (SYSCALL)CreateFileW, 0 },
33164 #else
33165 { "CreateFileW", (SYSCALL)0, 0 },
33166 #endif
33168 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
33169 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
33171 #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
33172 !defined(SQLITE_OMIT_WAL))
33173 { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
33174 #else
33175 { "CreateFileMappingA", (SYSCALL)0, 0 },
33176 #endif
33178 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
33179 DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
33181 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
33182 !defined(SQLITE_OMIT_WAL))
33183 { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
33184 #else
33185 { "CreateFileMappingW", (SYSCALL)0, 0 },
33186 #endif
33188 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
33189 DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
33191 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33192 { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
33193 #else
33194 { "CreateMutexW", (SYSCALL)0, 0 },
33195 #endif
33197 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
33198 LPCWSTR))aSyscall[8].pCurrent)
33200 #if defined(SQLITE_WIN32_HAS_ANSI)
33201 { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
33202 #else
33203 { "DeleteFileA", (SYSCALL)0, 0 },
33204 #endif
33206 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
33208 #if defined(SQLITE_WIN32_HAS_WIDE)
33209 { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
33210 #else
33211 { "DeleteFileW", (SYSCALL)0, 0 },
33212 #endif
33214 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
33216 #if SQLITE_OS_WINCE
33217 { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
33218 #else
33219 { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
33220 #endif
33222 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
33223 LPFILETIME))aSyscall[11].pCurrent)
33225 #if SQLITE_OS_WINCE
33226 { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
33227 #else
33228 { "FileTimeToSystemTime", (SYSCALL)0, 0 },
33229 #endif
33231 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
33232 LPSYSTEMTIME))aSyscall[12].pCurrent)
33234 { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
33236 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
33238 #if defined(SQLITE_WIN32_HAS_ANSI)
33239 { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
33240 #else
33241 { "FormatMessageA", (SYSCALL)0, 0 },
33242 #endif
33244 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
33245 DWORD,va_list*))aSyscall[14].pCurrent)
33247 #if defined(SQLITE_WIN32_HAS_WIDE)
33248 { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
33249 #else
33250 { "FormatMessageW", (SYSCALL)0, 0 },
33251 #endif
33253 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
33254 DWORD,va_list*))aSyscall[15].pCurrent)
33256 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
33257 { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
33258 #else
33259 { "FreeLibrary", (SYSCALL)0, 0 },
33260 #endif
33262 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
33264 { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
33266 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
33268 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
33269 { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
33270 #else
33271 { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
33272 #endif
33274 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
33275 LPDWORD))aSyscall[18].pCurrent)
33277 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33278 { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
33279 #else
33280 { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
33281 #endif
33283 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
33284 LPDWORD))aSyscall[19].pCurrent)
33286 #if defined(SQLITE_WIN32_HAS_ANSI)
33287 { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
33288 #else
33289 { "GetFileAttributesA", (SYSCALL)0, 0 },
33290 #endif
33292 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
33294 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33295 { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
33296 #else
33297 { "GetFileAttributesW", (SYSCALL)0, 0 },
33298 #endif
33300 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
33302 #if defined(SQLITE_WIN32_HAS_WIDE)
33303 { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
33304 #else
33305 { "GetFileAttributesExW", (SYSCALL)0, 0 },
33306 #endif
33308 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
33309 LPVOID))aSyscall[22].pCurrent)
33311 #if !SQLITE_OS_WINRT
33312 { "GetFileSize", (SYSCALL)GetFileSize, 0 },
33313 #else
33314 { "GetFileSize", (SYSCALL)0, 0 },
33315 #endif
33317 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
33319 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
33320 { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
33321 #else
33322 { "GetFullPathNameA", (SYSCALL)0, 0 },
33323 #endif
33325 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
33326 LPSTR*))aSyscall[24].pCurrent)
33328 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33329 { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
33330 #else
33331 { "GetFullPathNameW", (SYSCALL)0, 0 },
33332 #endif
33334 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
33335 LPWSTR*))aSyscall[25].pCurrent)
33337 { "GetLastError", (SYSCALL)GetLastError, 0 },
33339 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
33341 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
33342 #if SQLITE_OS_WINCE
33343 /* The GetProcAddressA() routine is only available on Windows CE. */
33344 { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
33345 #else
33346 /* All other Windows platforms expect GetProcAddress() to take
33347 ** an ANSI string regardless of the _UNICODE setting */
33348 { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
33349 #endif
33350 #else
33351 { "GetProcAddressA", (SYSCALL)0, 0 },
33352 #endif
33354 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
33355 LPCSTR))aSyscall[27].pCurrent)
33357 #if !SQLITE_OS_WINRT
33358 { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
33359 #else
33360 { "GetSystemInfo", (SYSCALL)0, 0 },
33361 #endif
33363 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
33365 { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
33367 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
33369 #if !SQLITE_OS_WINCE
33370 { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
33371 #else
33372 { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
33373 #endif
33375 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
33376 LPFILETIME))aSyscall[30].pCurrent)
33378 #if defined(SQLITE_WIN32_HAS_ANSI)
33379 { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
33380 #else
33381 { "GetTempPathA", (SYSCALL)0, 0 },
33382 #endif
33384 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
33386 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33387 { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
33388 #else
33389 { "GetTempPathW", (SYSCALL)0, 0 },
33390 #endif
33392 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
33394 #if !SQLITE_OS_WINRT
33395 { "GetTickCount", (SYSCALL)GetTickCount, 0 },
33396 #else
33397 { "GetTickCount", (SYSCALL)0, 0 },
33398 #endif
33400 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
33402 #if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
33403 SQLITE_WIN32_GETVERSIONEX
33404 { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
33405 #else
33406 { "GetVersionExA", (SYSCALL)0, 0 },
33407 #endif
33409 #define osGetVersionExA ((BOOL(WINAPI*)( \
33410 LPOSVERSIONINFOA))aSyscall[34].pCurrent)
33412 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
33413 defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
33414 { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
33415 #else
33416 { "GetVersionExW", (SYSCALL)0, 0 },
33417 #endif
33419 #define osGetVersionExW ((BOOL(WINAPI*)( \
33420 LPOSVERSIONINFOW))aSyscall[35].pCurrent)
33422 { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
33424 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
33425 SIZE_T))aSyscall[36].pCurrent)
33427 #if !SQLITE_OS_WINRT
33428 { "HeapCreate", (SYSCALL)HeapCreate, 0 },
33429 #else
33430 { "HeapCreate", (SYSCALL)0, 0 },
33431 #endif
33433 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
33434 SIZE_T))aSyscall[37].pCurrent)
33436 #if !SQLITE_OS_WINRT
33437 { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
33438 #else
33439 { "HeapDestroy", (SYSCALL)0, 0 },
33440 #endif
33442 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
33444 { "HeapFree", (SYSCALL)HeapFree, 0 },
33446 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
33448 { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
33450 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
33451 SIZE_T))aSyscall[40].pCurrent)
33453 { "HeapSize", (SYSCALL)HeapSize, 0 },
33455 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
33456 LPCVOID))aSyscall[41].pCurrent)
33458 #if !SQLITE_OS_WINRT
33459 { "HeapValidate", (SYSCALL)HeapValidate, 0 },
33460 #else
33461 { "HeapValidate", (SYSCALL)0, 0 },
33462 #endif
33464 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
33465 LPCVOID))aSyscall[42].pCurrent)
33467 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33468 { "HeapCompact", (SYSCALL)HeapCompact, 0 },
33469 #else
33470 { "HeapCompact", (SYSCALL)0, 0 },
33471 #endif
33473 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
33475 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
33476 { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
33477 #else
33478 { "LoadLibraryA", (SYSCALL)0, 0 },
33479 #endif
33481 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
33483 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
33484 !defined(SQLITE_OMIT_LOAD_EXTENSION)
33485 { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
33486 #else
33487 { "LoadLibraryW", (SYSCALL)0, 0 },
33488 #endif
33490 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
33492 #if !SQLITE_OS_WINRT
33493 { "LocalFree", (SYSCALL)LocalFree, 0 },
33494 #else
33495 { "LocalFree", (SYSCALL)0, 0 },
33496 #endif
33498 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
33500 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33501 { "LockFile", (SYSCALL)LockFile, 0 },
33502 #else
33503 { "LockFile", (SYSCALL)0, 0 },
33504 #endif
33506 #ifndef osLockFile
33507 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
33508 DWORD))aSyscall[47].pCurrent)
33509 #endif
33511 #if !SQLITE_OS_WINCE
33512 { "LockFileEx", (SYSCALL)LockFileEx, 0 },
33513 #else
33514 { "LockFileEx", (SYSCALL)0, 0 },
33515 #endif
33517 #ifndef osLockFileEx
33518 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
33519 LPOVERLAPPED))aSyscall[48].pCurrent)
33520 #endif
33522 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
33523 { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
33524 #else
33525 { "MapViewOfFile", (SYSCALL)0, 0 },
33526 #endif
33528 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
33529 SIZE_T))aSyscall[49].pCurrent)
33531 { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
33533 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
33534 int))aSyscall[50].pCurrent)
33536 { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
33538 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
33539 LARGE_INTEGER*))aSyscall[51].pCurrent)
33541 { "ReadFile", (SYSCALL)ReadFile, 0 },
33543 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
33544 LPOVERLAPPED))aSyscall[52].pCurrent)
33546 { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
33548 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
33550 #if !SQLITE_OS_WINRT
33551 { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
33552 #else
33553 { "SetFilePointer", (SYSCALL)0, 0 },
33554 #endif
33556 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
33557 DWORD))aSyscall[54].pCurrent)
33559 #if !SQLITE_OS_WINRT
33560 { "Sleep", (SYSCALL)Sleep, 0 },
33561 #else
33562 { "Sleep", (SYSCALL)0, 0 },
33563 #endif
33565 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
33567 { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
33569 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
33570 LPFILETIME))aSyscall[56].pCurrent)
33572 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33573 { "UnlockFile", (SYSCALL)UnlockFile, 0 },
33574 #else
33575 { "UnlockFile", (SYSCALL)0, 0 },
33576 #endif
33578 #ifndef osUnlockFile
33579 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
33580 DWORD))aSyscall[57].pCurrent)
33581 #endif
33583 #if !SQLITE_OS_WINCE
33584 { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
33585 #else
33586 { "UnlockFileEx", (SYSCALL)0, 0 },
33587 #endif
33589 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
33590 LPOVERLAPPED))aSyscall[58].pCurrent)
33592 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
33593 { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
33594 #else
33595 { "UnmapViewOfFile", (SYSCALL)0, 0 },
33596 #endif
33598 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
33600 { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
33602 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
33603 LPCSTR,LPBOOL))aSyscall[60].pCurrent)
33605 { "WriteFile", (SYSCALL)WriteFile, 0 },
33607 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
33608 LPOVERLAPPED))aSyscall[61].pCurrent)
33610 #if SQLITE_OS_WINRT
33611 { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
33612 #else
33613 { "CreateEventExW", (SYSCALL)0, 0 },
33614 #endif
33616 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
33617 DWORD,DWORD))aSyscall[62].pCurrent)
33619 #if !SQLITE_OS_WINRT
33620 { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
33621 #else
33622 { "WaitForSingleObject", (SYSCALL)0, 0 },
33623 #endif
33625 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
33626 DWORD))aSyscall[63].pCurrent)
33628 #if !SQLITE_OS_WINCE
33629 { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
33630 #else
33631 { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
33632 #endif
33634 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
33635 BOOL))aSyscall[64].pCurrent)
33637 #if SQLITE_OS_WINRT
33638 { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
33639 #else
33640 { "SetFilePointerEx", (SYSCALL)0, 0 },
33641 #endif
33643 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
33644 PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
33646 #if SQLITE_OS_WINRT
33647 { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
33648 #else
33649 { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
33650 #endif
33652 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
33653 FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
33655 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
33656 { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
33657 #else
33658 { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
33659 #endif
33661 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
33662 SIZE_T))aSyscall[67].pCurrent)
33664 #if SQLITE_OS_WINRT
33665 { "CreateFile2", (SYSCALL)CreateFile2, 0 },
33666 #else
33667 { "CreateFile2", (SYSCALL)0, 0 },
33668 #endif
33670 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
33671 LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
33673 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
33674 { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
33675 #else
33676 { "LoadPackagedLibrary", (SYSCALL)0, 0 },
33677 #endif
33679 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
33680 DWORD))aSyscall[69].pCurrent)
33682 #if SQLITE_OS_WINRT
33683 { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
33684 #else
33685 { "GetTickCount64", (SYSCALL)0, 0 },
33686 #endif
33688 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
33690 #if SQLITE_OS_WINRT
33691 { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
33692 #else
33693 { "GetNativeSystemInfo", (SYSCALL)0, 0 },
33694 #endif
33696 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
33697 LPSYSTEM_INFO))aSyscall[71].pCurrent)
33699 #if defined(SQLITE_WIN32_HAS_ANSI)
33700 { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
33701 #else
33702 { "OutputDebugStringA", (SYSCALL)0, 0 },
33703 #endif
33705 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
33707 #if defined(SQLITE_WIN32_HAS_WIDE)
33708 { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
33709 #else
33710 { "OutputDebugStringW", (SYSCALL)0, 0 },
33711 #endif
33713 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
33715 { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
33717 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
33719 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
33720 { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
33721 #else
33722 { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
33723 #endif
33725 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
33726 LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
33729 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
33730 ** is really just a macro that uses a compiler intrinsic (e.g. x64).
33731 ** So do not try to make this is into a redefinable interface.
33733 #if defined(InterlockedCompareExchange)
33734 { "InterlockedCompareExchange", (SYSCALL)0, 0 },
33736 #define osInterlockedCompareExchange InterlockedCompareExchange
33737 #else
33738 { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
33740 #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
33741 SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
33742 #endif /* defined(InterlockedCompareExchange) */
33744 }; /* End of the overrideable system calls */
33747 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
33748 ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
33749 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
33750 ** system call named zName.
33752 static int winSetSystemCall(
33753 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
33754 const char *zName, /* Name of system call to override */
33755 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
33757 unsigned int i;
33758 int rc = SQLITE_NOTFOUND;
33760 UNUSED_PARAMETER(pNotUsed);
33761 if( zName==0 ){
33762 /* If no zName is given, restore all system calls to their default
33763 ** settings and return NULL
33765 rc = SQLITE_OK;
33766 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
33767 if( aSyscall[i].pDefault ){
33768 aSyscall[i].pCurrent = aSyscall[i].pDefault;
33771 }else{
33772 /* If zName is specified, operate on only the one system call
33773 ** specified.
33775 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
33776 if( strcmp(zName, aSyscall[i].zName)==0 ){
33777 if( aSyscall[i].pDefault==0 ){
33778 aSyscall[i].pDefault = aSyscall[i].pCurrent;
33780 rc = SQLITE_OK;
33781 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
33782 aSyscall[i].pCurrent = pNewFunc;
33783 break;
33787 return rc;
33791 ** Return the value of a system call. Return NULL if zName is not a
33792 ** recognized system call name. NULL is also returned if the system call
33793 ** is currently undefined.
33795 static sqlite3_syscall_ptr winGetSystemCall(
33796 sqlite3_vfs *pNotUsed,
33797 const char *zName
33799 unsigned int i;
33801 UNUSED_PARAMETER(pNotUsed);
33802 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
33803 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
33805 return 0;
33809 ** Return the name of the first system call after zName. If zName==NULL
33810 ** then return the name of the first system call. Return NULL if zName
33811 ** is the last system call or if zName is not the name of a valid
33812 ** system call.
33814 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
33815 int i = -1;
33817 UNUSED_PARAMETER(p);
33818 if( zName ){
33819 for(i=0; i<ArraySize(aSyscall)-1; i++){
33820 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
33823 for(i++; i<ArraySize(aSyscall); i++){
33824 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
33826 return 0;
33829 #ifdef SQLITE_WIN32_MALLOC
33831 ** If a Win32 native heap has been configured, this function will attempt to
33832 ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
33833 ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
33834 ** "pnLargest" argument, if non-zero, will be used to return the size of the
33835 ** largest committed free block in the heap, in bytes.
33837 SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
33838 int rc = SQLITE_OK;
33839 UINT nLargest = 0;
33840 HANDLE hHeap;
33842 winMemAssertMagic();
33843 hHeap = winMemGetHeap();
33844 assert( hHeap!=0 );
33845 assert( hHeap!=INVALID_HANDLE_VALUE );
33846 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33847 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
33848 #endif
33849 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33850 if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
33851 DWORD lastErrno = osGetLastError();
33852 if( lastErrno==NO_ERROR ){
33853 sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
33854 (void*)hHeap);
33855 rc = SQLITE_NOMEM;
33856 }else{
33857 sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
33858 osGetLastError(), (void*)hHeap);
33859 rc = SQLITE_ERROR;
33862 #else
33863 sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
33864 (void*)hHeap);
33865 rc = SQLITE_NOTFOUND;
33866 #endif
33867 if( pnLargest ) *pnLargest = nLargest;
33868 return rc;
33872 ** If a Win32 native heap has been configured, this function will attempt to
33873 ** destroy and recreate it. If the Win32 native heap is not isolated and/or
33874 ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
33875 ** be returned and no changes will be made to the Win32 native heap.
33877 SQLITE_API int sqlite3_win32_reset_heap(){
33878 int rc;
33879 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
33880 MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
33881 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
33882 MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
33883 sqlite3_mutex_enter(pMaster);
33884 sqlite3_mutex_enter(pMem);
33885 winMemAssertMagic();
33886 if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
33888 ** At this point, there should be no outstanding memory allocations on
33889 ** the heap. Also, since both the master and memsys locks are currently
33890 ** being held by us, no other function (i.e. from another thread) should
33891 ** be able to even access the heap. Attempt to destroy and recreate our
33892 ** isolated Win32 native heap now.
33894 assert( winMemGetHeap()!=NULL );
33895 assert( winMemGetOwned() );
33896 assert( sqlite3_memory_used()==0 );
33897 winMemShutdown(winMemGetDataPtr());
33898 assert( winMemGetHeap()==NULL );
33899 assert( !winMemGetOwned() );
33900 assert( sqlite3_memory_used()==0 );
33901 rc = winMemInit(winMemGetDataPtr());
33902 assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
33903 assert( rc!=SQLITE_OK || winMemGetOwned() );
33904 assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
33905 }else{
33907 ** The Win32 native heap cannot be modified because it may be in use.
33909 rc = SQLITE_BUSY;
33911 sqlite3_mutex_leave(pMem);
33912 sqlite3_mutex_leave(pMaster);
33913 return rc;
33915 #endif /* SQLITE_WIN32_MALLOC */
33918 ** This function outputs the specified (ANSI) string to the Win32 debugger
33919 ** (if available).
33922 SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
33923 char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
33924 int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
33925 if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
33926 assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
33927 #if defined(SQLITE_WIN32_HAS_ANSI)
33928 if( nMin>0 ){
33929 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
33930 memcpy(zDbgBuf, zBuf, nMin);
33931 osOutputDebugStringA(zDbgBuf);
33932 }else{
33933 osOutputDebugStringA(zBuf);
33935 #elif defined(SQLITE_WIN32_HAS_WIDE)
33936 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
33937 if ( osMultiByteToWideChar(
33938 osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
33939 nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
33940 return;
33942 osOutputDebugStringW((LPCWSTR)zDbgBuf);
33943 #else
33944 if( nMin>0 ){
33945 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
33946 memcpy(zDbgBuf, zBuf, nMin);
33947 fprintf(stderr, "%s", zDbgBuf);
33948 }else{
33949 fprintf(stderr, "%s", zBuf);
33951 #endif
33955 ** The following routine suspends the current thread for at least ms
33956 ** milliseconds. This is equivalent to the Win32 Sleep() interface.
33958 #if SQLITE_OS_WINRT
33959 static HANDLE sleepObj = NULL;
33960 #endif
33962 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
33963 #if SQLITE_OS_WINRT
33964 if ( sleepObj==NULL ){
33965 sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
33966 SYNCHRONIZE);
33968 assert( sleepObj!=NULL );
33969 osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
33970 #else
33971 osSleep(milliseconds);
33972 #endif
33975 #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
33976 SQLITE_THREADSAFE>0
33977 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
33978 DWORD rc;
33979 while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
33980 TRUE))==WAIT_IO_COMPLETION ){}
33981 return rc;
33983 #endif
33986 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
33987 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
33989 ** Here is an interesting observation: Win95, Win98, and WinME lack
33990 ** the LockFileEx() API. But we can still statically link against that
33991 ** API as long as we don't call it when running Win95/98/ME. A call to
33992 ** this routine is used to determine if the host is Win95/98/ME or
33993 ** WinNT/2K/XP so that we will know whether or not we can safely call
33994 ** the LockFileEx() API.
33997 #if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
33998 # define osIsNT() (1)
33999 #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
34000 # define osIsNT() (1)
34001 #elif !defined(SQLITE_WIN32_HAS_WIDE)
34002 # define osIsNT() (0)
34003 #else
34004 # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
34005 #endif
34008 ** This function determines if the machine is running a version of Windows
34009 ** based on the NT kernel.
34011 SQLITE_API int sqlite3_win32_is_nt(void){
34012 #if SQLITE_OS_WINRT
34014 ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
34015 ** kernel.
34017 return 1;
34018 #elif defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
34019 if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
34020 #if defined(SQLITE_WIN32_HAS_ANSI)
34021 OSVERSIONINFOA sInfo;
34022 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
34023 osGetVersionExA(&sInfo);
34024 osInterlockedCompareExchange(&sqlite3_os_type,
34025 (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
34026 #elif defined(SQLITE_WIN32_HAS_WIDE)
34027 OSVERSIONINFOW sInfo;
34028 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
34029 osGetVersionExW(&sInfo);
34030 osInterlockedCompareExchange(&sqlite3_os_type,
34031 (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
34032 #endif
34034 return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
34035 #elif SQLITE_TEST
34036 return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
34037 #else
34039 ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
34040 ** deprecated are always assumed to be based on the NT kernel.
34042 return 1;
34043 #endif
34046 #ifdef SQLITE_WIN32_MALLOC
34048 ** Allocate nBytes of memory.
34050 static void *winMemMalloc(int nBytes){
34051 HANDLE hHeap;
34052 void *p;
34054 winMemAssertMagic();
34055 hHeap = winMemGetHeap();
34056 assert( hHeap!=0 );
34057 assert( hHeap!=INVALID_HANDLE_VALUE );
34058 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34059 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
34060 #endif
34061 assert( nBytes>=0 );
34062 p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
34063 if( !p ){
34064 sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
34065 nBytes, osGetLastError(), (void*)hHeap);
34067 return p;
34071 ** Free memory.
34073 static void winMemFree(void *pPrior){
34074 HANDLE hHeap;
34076 winMemAssertMagic();
34077 hHeap = winMemGetHeap();
34078 assert( hHeap!=0 );
34079 assert( hHeap!=INVALID_HANDLE_VALUE );
34080 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34081 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
34082 #endif
34083 if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
34084 if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
34085 sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
34086 pPrior, osGetLastError(), (void*)hHeap);
34091 ** Change the size of an existing memory allocation
34093 static void *winMemRealloc(void *pPrior, int nBytes){
34094 HANDLE hHeap;
34095 void *p;
34097 winMemAssertMagic();
34098 hHeap = winMemGetHeap();
34099 assert( hHeap!=0 );
34100 assert( hHeap!=INVALID_HANDLE_VALUE );
34101 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34102 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
34103 #endif
34104 assert( nBytes>=0 );
34105 if( !pPrior ){
34106 p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
34107 }else{
34108 p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
34110 if( !p ){
34111 sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
34112 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
34113 (void*)hHeap);
34115 return p;
34119 ** Return the size of an outstanding allocation, in bytes.
34121 static int winMemSize(void *p){
34122 HANDLE hHeap;
34123 SIZE_T n;
34125 winMemAssertMagic();
34126 hHeap = winMemGetHeap();
34127 assert( hHeap!=0 );
34128 assert( hHeap!=INVALID_HANDLE_VALUE );
34129 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34130 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
34131 #endif
34132 if( !p ) return 0;
34133 n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
34134 if( n==(SIZE_T)-1 ){
34135 sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
34136 p, osGetLastError(), (void*)hHeap);
34137 return 0;
34139 return (int)n;
34143 ** Round up a request size to the next valid allocation size.
34145 static int winMemRoundup(int n){
34146 return n;
34150 ** Initialize this module.
34152 static int winMemInit(void *pAppData){
34153 winMemData *pWinMemData = (winMemData *)pAppData;
34155 if( !pWinMemData ) return SQLITE_ERROR;
34156 assert( pWinMemData->magic1==WINMEM_MAGIC1 );
34157 assert( pWinMemData->magic2==WINMEM_MAGIC2 );
34159 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
34160 if( !pWinMemData->hHeap ){
34161 DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
34162 DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
34163 if( dwMaximumSize==0 ){
34164 dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
34165 }else if( dwInitialSize>dwMaximumSize ){
34166 dwInitialSize = dwMaximumSize;
34168 pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
34169 dwInitialSize, dwMaximumSize);
34170 if( !pWinMemData->hHeap ){
34171 sqlite3_log(SQLITE_NOMEM,
34172 "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
34173 osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
34174 dwMaximumSize);
34175 return SQLITE_NOMEM;
34177 pWinMemData->bOwned = TRUE;
34178 assert( pWinMemData->bOwned );
34180 #else
34181 pWinMemData->hHeap = osGetProcessHeap();
34182 if( !pWinMemData->hHeap ){
34183 sqlite3_log(SQLITE_NOMEM,
34184 "failed to GetProcessHeap (%lu)", osGetLastError());
34185 return SQLITE_NOMEM;
34187 pWinMemData->bOwned = FALSE;
34188 assert( !pWinMemData->bOwned );
34189 #endif
34190 assert( pWinMemData->hHeap!=0 );
34191 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
34192 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34193 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
34194 #endif
34195 return SQLITE_OK;
34199 ** Deinitialize this module.
34201 static void winMemShutdown(void *pAppData){
34202 winMemData *pWinMemData = (winMemData *)pAppData;
34204 if( !pWinMemData ) return;
34205 assert( pWinMemData->magic1==WINMEM_MAGIC1 );
34206 assert( pWinMemData->magic2==WINMEM_MAGIC2 );
34208 if( pWinMemData->hHeap ){
34209 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
34210 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34211 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
34212 #endif
34213 if( pWinMemData->bOwned ){
34214 if( !osHeapDestroy(pWinMemData->hHeap) ){
34215 sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
34216 osGetLastError(), (void*)pWinMemData->hHeap);
34218 pWinMemData->bOwned = FALSE;
34220 pWinMemData->hHeap = NULL;
34225 ** Populate the low-level memory allocation function pointers in
34226 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
34227 ** arguments specify the block of memory to manage.
34229 ** This routine is only called by sqlite3_config(), and therefore
34230 ** is not required to be threadsafe (it is not).
34232 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
34233 static const sqlite3_mem_methods winMemMethods = {
34234 winMemMalloc,
34235 winMemFree,
34236 winMemRealloc,
34237 winMemSize,
34238 winMemRoundup,
34239 winMemInit,
34240 winMemShutdown,
34241 &win_mem_data
34243 return &winMemMethods;
34246 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
34247 sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
34249 #endif /* SQLITE_WIN32_MALLOC */
34252 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
34254 ** Space to hold the returned string is obtained from malloc.
34256 static LPWSTR winUtf8ToUnicode(const char *zFilename){
34257 int nChar;
34258 LPWSTR zWideFilename;
34260 nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
34261 if( nChar==0 ){
34262 return 0;
34264 zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
34265 if( zWideFilename==0 ){
34266 return 0;
34268 nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
34269 nChar);
34270 if( nChar==0 ){
34271 sqlite3_free(zWideFilename);
34272 zWideFilename = 0;
34274 return zWideFilename;
34278 ** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
34279 ** obtained from sqlite3_malloc().
34281 static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
34282 int nByte;
34283 char *zFilename;
34285 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
34286 if( nByte == 0 ){
34287 return 0;
34289 zFilename = sqlite3MallocZero( nByte );
34290 if( zFilename==0 ){
34291 return 0;
34293 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
34294 0, 0);
34295 if( nByte == 0 ){
34296 sqlite3_free(zFilename);
34297 zFilename = 0;
34299 return zFilename;
34303 ** Convert an ANSI string to Microsoft Unicode, based on the
34304 ** current codepage settings for file apis.
34306 ** Space to hold the returned string is obtained
34307 ** from sqlite3_malloc.
34309 static LPWSTR winMbcsToUnicode(const char *zFilename){
34310 int nByte;
34311 LPWSTR zMbcsFilename;
34312 int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
34314 nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
34315 0)*sizeof(WCHAR);
34316 if( nByte==0 ){
34317 return 0;
34319 zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
34320 if( zMbcsFilename==0 ){
34321 return 0;
34323 nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
34324 nByte);
34325 if( nByte==0 ){
34326 sqlite3_free(zMbcsFilename);
34327 zMbcsFilename = 0;
34329 return zMbcsFilename;
34333 ** Convert Microsoft Unicode to multi-byte character string, based on the
34334 ** user's ANSI codepage.
34336 ** Space to hold the returned string is obtained from
34337 ** sqlite3_malloc().
34339 static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
34340 int nByte;
34341 char *zFilename;
34342 int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
34344 nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
34345 if( nByte == 0 ){
34346 return 0;
34348 zFilename = sqlite3MallocZero( nByte );
34349 if( zFilename==0 ){
34350 return 0;
34352 nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
34353 nByte, 0, 0);
34354 if( nByte == 0 ){
34355 sqlite3_free(zFilename);
34356 zFilename = 0;
34358 return zFilename;
34362 ** Convert multibyte character string to UTF-8. Space to hold the
34363 ** returned string is obtained from sqlite3_malloc().
34365 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
34366 char *zFilenameUtf8;
34367 LPWSTR zTmpWide;
34369 zTmpWide = winMbcsToUnicode(zFilename);
34370 if( zTmpWide==0 ){
34371 return 0;
34373 zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
34374 sqlite3_free(zTmpWide);
34375 return zFilenameUtf8;
34379 ** Convert UTF-8 to multibyte character string. Space to hold the
34380 ** returned string is obtained from sqlite3_malloc().
34382 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
34383 char *zFilenameMbcs;
34384 LPWSTR zTmpWide;
34386 zTmpWide = winUtf8ToUnicode(zFilename);
34387 if( zTmpWide==0 ){
34388 return 0;
34390 zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
34391 sqlite3_free(zTmpWide);
34392 return zFilenameMbcs;
34396 ** This function sets the data directory or the temporary directory based on
34397 ** the provided arguments. The type argument must be 1 in order to set the
34398 ** data directory or 2 in order to set the temporary directory. The zValue
34399 ** argument is the name of the directory to use. The return value will be
34400 ** SQLITE_OK if successful.
34402 SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
34403 char **ppDirectory = 0;
34404 #ifndef SQLITE_OMIT_AUTOINIT
34405 int rc = sqlite3_initialize();
34406 if( rc ) return rc;
34407 #endif
34408 if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
34409 ppDirectory = &sqlite3_data_directory;
34410 }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
34411 ppDirectory = &sqlite3_temp_directory;
34413 assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
34414 || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
34416 assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
34417 if( ppDirectory ){
34418 char *zValueUtf8 = 0;
34419 if( zValue && zValue[0] ){
34420 zValueUtf8 = winUnicodeToUtf8(zValue);
34421 if ( zValueUtf8==0 ){
34422 return SQLITE_NOMEM;
34425 sqlite3_free(*ppDirectory);
34426 *ppDirectory = zValueUtf8;
34427 return SQLITE_OK;
34429 return SQLITE_ERROR;
34433 ** The return value of winGetLastErrorMsg
34434 ** is zero if the error message fits in the buffer, or non-zero
34435 ** otherwise (if the message was truncated).
34437 static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
34438 /* FormatMessage returns 0 on failure. Otherwise it
34439 ** returns the number of TCHARs written to the output
34440 ** buffer, excluding the terminating null char.
34442 DWORD dwLen = 0;
34443 char *zOut = 0;
34445 if( osIsNT() ){
34446 #if SQLITE_OS_WINRT
34447 WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
34448 dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
34449 FORMAT_MESSAGE_IGNORE_INSERTS,
34450 NULL,
34451 lastErrno,
34453 zTempWide,
34454 SQLITE_WIN32_MAX_ERRMSG_CHARS,
34456 #else
34457 LPWSTR zTempWide = NULL;
34458 dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
34459 FORMAT_MESSAGE_FROM_SYSTEM |
34460 FORMAT_MESSAGE_IGNORE_INSERTS,
34461 NULL,
34462 lastErrno,
34464 (LPWSTR) &zTempWide,
34467 #endif
34468 if( dwLen > 0 ){
34469 /* allocate a buffer and convert to UTF8 */
34470 sqlite3BeginBenignMalloc();
34471 zOut = winUnicodeToUtf8(zTempWide);
34472 sqlite3EndBenignMalloc();
34473 #if !SQLITE_OS_WINRT
34474 /* free the system buffer allocated by FormatMessage */
34475 osLocalFree(zTempWide);
34476 #endif
34479 #ifdef SQLITE_WIN32_HAS_ANSI
34480 else{
34481 char *zTemp = NULL;
34482 dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
34483 FORMAT_MESSAGE_FROM_SYSTEM |
34484 FORMAT_MESSAGE_IGNORE_INSERTS,
34485 NULL,
34486 lastErrno,
34488 (LPSTR) &zTemp,
34491 if( dwLen > 0 ){
34492 /* allocate a buffer and convert to UTF8 */
34493 sqlite3BeginBenignMalloc();
34494 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
34495 sqlite3EndBenignMalloc();
34496 /* free the system buffer allocated by FormatMessage */
34497 osLocalFree(zTemp);
34500 #endif
34501 if( 0 == dwLen ){
34502 sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
34503 }else{
34504 /* copy a maximum of nBuf chars to output buffer */
34505 sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
34506 /* free the UTF8 buffer */
34507 sqlite3_free(zOut);
34509 return 0;
34514 ** This function - winLogErrorAtLine() - is only ever called via the macro
34515 ** winLogError().
34517 ** This routine is invoked after an error occurs in an OS function.
34518 ** It logs a message using sqlite3_log() containing the current value of
34519 ** error code and, if possible, the human-readable equivalent from
34520 ** FormatMessage.
34522 ** The first argument passed to the macro should be the error code that
34523 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
34524 ** The two subsequent arguments should be the name of the OS function that
34525 ** failed and the associated file-system path, if any.
34527 #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
34528 static int winLogErrorAtLine(
34529 int errcode, /* SQLite error code */
34530 DWORD lastErrno, /* Win32 last error */
34531 const char *zFunc, /* Name of OS function that failed */
34532 const char *zPath, /* File path associated with error */
34533 int iLine /* Source line number where error occurred */
34535 char zMsg[500]; /* Human readable error text */
34536 int i; /* Loop counter */
34538 zMsg[0] = 0;
34539 winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
34540 assert( errcode!=SQLITE_OK );
34541 if( zPath==0 ) zPath = "";
34542 for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
34543 zMsg[i] = 0;
34544 sqlite3_log(errcode,
34545 "os_win.c:%d: (%lu) %s(%s) - %s",
34546 iLine, lastErrno, zFunc, zPath, zMsg
34549 return errcode;
34553 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
34554 ** will be retried following a locking error - probably caused by
34555 ** antivirus software. Also the initial delay before the first retry.
34556 ** The delay increases linearly with each retry.
34558 #ifndef SQLITE_WIN32_IOERR_RETRY
34559 # define SQLITE_WIN32_IOERR_RETRY 10
34560 #endif
34561 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
34562 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
34563 #endif
34564 static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
34565 static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
34568 ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
34569 ** error code obtained via GetLastError() is eligible to be retried. It
34570 ** must accept the error code DWORD as its only argument and should return
34571 ** non-zero if the error code is transient in nature and the operation
34572 ** responsible for generating the original error might succeed upon being
34573 ** retried. The argument to this macro should be a variable.
34575 ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
34576 ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
34577 ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
34578 ** may be used to include additional error codes in the set that should
34579 ** result in the failing I/O operation being retried by the caller. If
34580 ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
34581 ** identical to those of the "winIoerrCanRetry1" macro.
34583 #if !defined(winIoerrCanRetry1)
34584 #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
34585 ((a)==ERROR_SHARING_VIOLATION) || \
34586 ((a)==ERROR_LOCK_VIOLATION) || \
34587 ((a)==ERROR_DEV_NOT_EXIST) || \
34588 ((a)==ERROR_NETNAME_DELETED) || \
34589 ((a)==ERROR_SEM_TIMEOUT) || \
34590 ((a)==ERROR_NETWORK_UNREACHABLE))
34591 #endif
34594 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
34595 ** to see if it should be retried. Return TRUE to retry. Return FALSE
34596 ** to give up with an error.
34598 static int winRetryIoerr(int *pnRetry, DWORD *pError){
34599 DWORD e = osGetLastError();
34600 if( *pnRetry>=winIoerrRetry ){
34601 if( pError ){
34602 *pError = e;
34604 return 0;
34606 if( winIoerrCanRetry1(e) ){
34607 sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
34608 ++*pnRetry;
34609 return 1;
34611 #if defined(winIoerrCanRetry2)
34612 else if( winIoerrCanRetry2(e) ){
34613 sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
34614 ++*pnRetry;
34615 return 1;
34617 #endif
34618 if( pError ){
34619 *pError = e;
34621 return 0;
34625 ** Log a I/O error retry episode.
34627 static void winLogIoerr(int nRetry){
34628 if( nRetry ){
34629 sqlite3_log(SQLITE_IOERR,
34630 "delayed %dms for lock/sharing conflict",
34631 winIoerrRetryDelay*nRetry*(nRetry+1)/2
34636 #if SQLITE_OS_WINCE
34637 /*************************************************************************
34638 ** This section contains code for WinCE only.
34640 #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
34642 ** The MSVC CRT on Windows CE may not have a localtime() function. So
34643 ** create a substitute.
34645 /* #include <time.h> */
34646 struct tm *__cdecl localtime(const time_t *t)
34648 static struct tm y;
34649 FILETIME uTm, lTm;
34650 SYSTEMTIME pTm;
34651 sqlite3_int64 t64;
34652 t64 = *t;
34653 t64 = (t64 + 11644473600)*10000000;
34654 uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
34655 uTm.dwHighDateTime= (DWORD)(t64 >> 32);
34656 osFileTimeToLocalFileTime(&uTm,&lTm);
34657 osFileTimeToSystemTime(&lTm,&pTm);
34658 y.tm_year = pTm.wYear - 1900;
34659 y.tm_mon = pTm.wMonth - 1;
34660 y.tm_wday = pTm.wDayOfWeek;
34661 y.tm_mday = pTm.wDay;
34662 y.tm_hour = pTm.wHour;
34663 y.tm_min = pTm.wMinute;
34664 y.tm_sec = pTm.wSecond;
34665 return &y;
34667 #endif
34669 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
34672 ** Acquire a lock on the handle h
34674 static void winceMutexAcquire(HANDLE h){
34675 DWORD dwErr;
34676 do {
34677 dwErr = osWaitForSingleObject(h, INFINITE);
34678 } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
34681 ** Release a lock acquired by winceMutexAcquire()
34683 #define winceMutexRelease(h) ReleaseMutex(h)
34686 ** Create the mutex and shared memory used for locking in the file
34687 ** descriptor pFile
34689 static int winceCreateLock(const char *zFilename, winFile *pFile){
34690 LPWSTR zTok;
34691 LPWSTR zName;
34692 DWORD lastErrno;
34693 BOOL bLogged = FALSE;
34694 BOOL bInit = TRUE;
34696 zName = winUtf8ToUnicode(zFilename);
34697 if( zName==0 ){
34698 /* out of memory */
34699 return SQLITE_IOERR_NOMEM;
34702 /* Initialize the local lockdata */
34703 memset(&pFile->local, 0, sizeof(pFile->local));
34705 /* Replace the backslashes from the filename and lowercase it
34706 ** to derive a mutex name. */
34707 zTok = osCharLowerW(zName);
34708 for (;*zTok;zTok++){
34709 if (*zTok == '\\') *zTok = '_';
34712 /* Create/open the named mutex */
34713 pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
34714 if (!pFile->hMutex){
34715 pFile->lastErrno = osGetLastError();
34716 sqlite3_free(zName);
34717 return winLogError(SQLITE_IOERR, pFile->lastErrno,
34718 "winceCreateLock1", zFilename);
34721 /* Acquire the mutex before continuing */
34722 winceMutexAcquire(pFile->hMutex);
34724 /* Since the names of named mutexes, semaphores, file mappings etc are
34725 ** case-sensitive, take advantage of that by uppercasing the mutex name
34726 ** and using that as the shared filemapping name.
34728 osCharUpperW(zName);
34729 pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
34730 PAGE_READWRITE, 0, sizeof(winceLock),
34731 zName);
34733 /* Set a flag that indicates we're the first to create the memory so it
34734 ** must be zero-initialized */
34735 lastErrno = osGetLastError();
34736 if (lastErrno == ERROR_ALREADY_EXISTS){
34737 bInit = FALSE;
34740 sqlite3_free(zName);
34742 /* If we succeeded in making the shared memory handle, map it. */
34743 if( pFile->hShared ){
34744 pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
34745 FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
34746 /* If mapping failed, close the shared memory handle and erase it */
34747 if( !pFile->shared ){
34748 pFile->lastErrno = osGetLastError();
34749 winLogError(SQLITE_IOERR, pFile->lastErrno,
34750 "winceCreateLock2", zFilename);
34751 bLogged = TRUE;
34752 osCloseHandle(pFile->hShared);
34753 pFile->hShared = NULL;
34757 /* If shared memory could not be created, then close the mutex and fail */
34758 if( pFile->hShared==NULL ){
34759 if( !bLogged ){
34760 pFile->lastErrno = lastErrno;
34761 winLogError(SQLITE_IOERR, pFile->lastErrno,
34762 "winceCreateLock3", zFilename);
34763 bLogged = TRUE;
34765 winceMutexRelease(pFile->hMutex);
34766 osCloseHandle(pFile->hMutex);
34767 pFile->hMutex = NULL;
34768 return SQLITE_IOERR;
34771 /* Initialize the shared memory if we're supposed to */
34772 if( bInit ){
34773 memset(pFile->shared, 0, sizeof(winceLock));
34776 winceMutexRelease(pFile->hMutex);
34777 return SQLITE_OK;
34781 ** Destroy the part of winFile that deals with wince locks
34783 static void winceDestroyLock(winFile *pFile){
34784 if (pFile->hMutex){
34785 /* Acquire the mutex */
34786 winceMutexAcquire(pFile->hMutex);
34788 /* The following blocks should probably assert in debug mode, but they
34789 are to cleanup in case any locks remained open */
34790 if (pFile->local.nReaders){
34791 pFile->shared->nReaders --;
34793 if (pFile->local.bReserved){
34794 pFile->shared->bReserved = FALSE;
34796 if (pFile->local.bPending){
34797 pFile->shared->bPending = FALSE;
34799 if (pFile->local.bExclusive){
34800 pFile->shared->bExclusive = FALSE;
34803 /* De-reference and close our copy of the shared memory handle */
34804 osUnmapViewOfFile(pFile->shared);
34805 osCloseHandle(pFile->hShared);
34807 /* Done with the mutex */
34808 winceMutexRelease(pFile->hMutex);
34809 osCloseHandle(pFile->hMutex);
34810 pFile->hMutex = NULL;
34815 ** An implementation of the LockFile() API of Windows for CE
34817 static BOOL winceLockFile(
34818 LPHANDLE phFile,
34819 DWORD dwFileOffsetLow,
34820 DWORD dwFileOffsetHigh,
34821 DWORD nNumberOfBytesToLockLow,
34822 DWORD nNumberOfBytesToLockHigh
34824 winFile *pFile = HANDLE_TO_WINFILE(phFile);
34825 BOOL bReturn = FALSE;
34827 UNUSED_PARAMETER(dwFileOffsetHigh);
34828 UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
34830 if (!pFile->hMutex) return TRUE;
34831 winceMutexAcquire(pFile->hMutex);
34833 /* Wanting an exclusive lock? */
34834 if (dwFileOffsetLow == (DWORD)SHARED_FIRST
34835 && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
34836 if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
34837 pFile->shared->bExclusive = TRUE;
34838 pFile->local.bExclusive = TRUE;
34839 bReturn = TRUE;
34843 /* Want a read-only lock? */
34844 else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
34845 nNumberOfBytesToLockLow == 1){
34846 if (pFile->shared->bExclusive == 0){
34847 pFile->local.nReaders ++;
34848 if (pFile->local.nReaders == 1){
34849 pFile->shared->nReaders ++;
34851 bReturn = TRUE;
34855 /* Want a pending lock? */
34856 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
34857 && nNumberOfBytesToLockLow == 1){
34858 /* If no pending lock has been acquired, then acquire it */
34859 if (pFile->shared->bPending == 0) {
34860 pFile->shared->bPending = TRUE;
34861 pFile->local.bPending = TRUE;
34862 bReturn = TRUE;
34866 /* Want a reserved lock? */
34867 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
34868 && nNumberOfBytesToLockLow == 1){
34869 if (pFile->shared->bReserved == 0) {
34870 pFile->shared->bReserved = TRUE;
34871 pFile->local.bReserved = TRUE;
34872 bReturn = TRUE;
34876 winceMutexRelease(pFile->hMutex);
34877 return bReturn;
34881 ** An implementation of the UnlockFile API of Windows for CE
34883 static BOOL winceUnlockFile(
34884 LPHANDLE phFile,
34885 DWORD dwFileOffsetLow,
34886 DWORD dwFileOffsetHigh,
34887 DWORD nNumberOfBytesToUnlockLow,
34888 DWORD nNumberOfBytesToUnlockHigh
34890 winFile *pFile = HANDLE_TO_WINFILE(phFile);
34891 BOOL bReturn = FALSE;
34893 UNUSED_PARAMETER(dwFileOffsetHigh);
34894 UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
34896 if (!pFile->hMutex) return TRUE;
34897 winceMutexAcquire(pFile->hMutex);
34899 /* Releasing a reader lock or an exclusive lock */
34900 if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
34901 /* Did we have an exclusive lock? */
34902 if (pFile->local.bExclusive){
34903 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
34904 pFile->local.bExclusive = FALSE;
34905 pFile->shared->bExclusive = FALSE;
34906 bReturn = TRUE;
34909 /* Did we just have a reader lock? */
34910 else if (pFile->local.nReaders){
34911 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
34912 || nNumberOfBytesToUnlockLow == 1);
34913 pFile->local.nReaders --;
34914 if (pFile->local.nReaders == 0)
34916 pFile->shared->nReaders --;
34918 bReturn = TRUE;
34922 /* Releasing a pending lock */
34923 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
34924 && nNumberOfBytesToUnlockLow == 1){
34925 if (pFile->local.bPending){
34926 pFile->local.bPending = FALSE;
34927 pFile->shared->bPending = FALSE;
34928 bReturn = TRUE;
34931 /* Releasing a reserved lock */
34932 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
34933 && nNumberOfBytesToUnlockLow == 1){
34934 if (pFile->local.bReserved) {
34935 pFile->local.bReserved = FALSE;
34936 pFile->shared->bReserved = FALSE;
34937 bReturn = TRUE;
34941 winceMutexRelease(pFile->hMutex);
34942 return bReturn;
34945 ** End of the special code for wince
34946 *****************************************************************************/
34947 #endif /* SQLITE_OS_WINCE */
34950 ** Lock a file region.
34952 static BOOL winLockFile(
34953 LPHANDLE phFile,
34954 DWORD flags,
34955 DWORD offsetLow,
34956 DWORD offsetHigh,
34957 DWORD numBytesLow,
34958 DWORD numBytesHigh
34960 #if SQLITE_OS_WINCE
34962 ** NOTE: Windows CE is handled differently here due its lack of the Win32
34963 ** API LockFile.
34965 return winceLockFile(phFile, offsetLow, offsetHigh,
34966 numBytesLow, numBytesHigh);
34967 #else
34968 if( osIsNT() ){
34969 OVERLAPPED ovlp;
34970 memset(&ovlp, 0, sizeof(OVERLAPPED));
34971 ovlp.Offset = offsetLow;
34972 ovlp.OffsetHigh = offsetHigh;
34973 return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
34974 }else{
34975 return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
34976 numBytesHigh);
34978 #endif
34982 ** Unlock a file region.
34984 static BOOL winUnlockFile(
34985 LPHANDLE phFile,
34986 DWORD offsetLow,
34987 DWORD offsetHigh,
34988 DWORD numBytesLow,
34989 DWORD numBytesHigh
34991 #if SQLITE_OS_WINCE
34993 ** NOTE: Windows CE is handled differently here due its lack of the Win32
34994 ** API UnlockFile.
34996 return winceUnlockFile(phFile, offsetLow, offsetHigh,
34997 numBytesLow, numBytesHigh);
34998 #else
34999 if( osIsNT() ){
35000 OVERLAPPED ovlp;
35001 memset(&ovlp, 0, sizeof(OVERLAPPED));
35002 ovlp.Offset = offsetLow;
35003 ovlp.OffsetHigh = offsetHigh;
35004 return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
35005 }else{
35006 return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
35007 numBytesHigh);
35009 #endif
35012 /*****************************************************************************
35013 ** The next group of routines implement the I/O methods specified
35014 ** by the sqlite3_io_methods object.
35015 ******************************************************************************/
35018 ** Some Microsoft compilers lack this definition.
35020 #ifndef INVALID_SET_FILE_POINTER
35021 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
35022 #endif
35025 ** Move the current position of the file handle passed as the first
35026 ** argument to offset iOffset within the file. If successful, return 0.
35027 ** Otherwise, set pFile->lastErrno and return non-zero.
35029 static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
35030 #if !SQLITE_OS_WINRT
35031 LONG upperBits; /* Most sig. 32 bits of new offset */
35032 LONG lowerBits; /* Least sig. 32 bits of new offset */
35033 DWORD dwRet; /* Value returned by SetFilePointer() */
35034 DWORD lastErrno; /* Value returned by GetLastError() */
35036 OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
35038 upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
35039 lowerBits = (LONG)(iOffset & 0xffffffff);
35041 /* API oddity: If successful, SetFilePointer() returns a dword
35042 ** containing the lower 32-bits of the new file-offset. Or, if it fails,
35043 ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
35044 ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
35045 ** whether an error has actually occurred, it is also necessary to call
35046 ** GetLastError().
35048 dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
35050 if( (dwRet==INVALID_SET_FILE_POINTER
35051 && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
35052 pFile->lastErrno = lastErrno;
35053 winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
35054 "winSeekFile", pFile->zPath);
35055 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
35056 return 1;
35059 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
35060 return 0;
35061 #else
35063 ** Same as above, except that this implementation works for WinRT.
35066 LARGE_INTEGER x; /* The new offset */
35067 BOOL bRet; /* Value returned by SetFilePointerEx() */
35069 x.QuadPart = iOffset;
35070 bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
35072 if(!bRet){
35073 pFile->lastErrno = osGetLastError();
35074 winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
35075 "winSeekFile", pFile->zPath);
35076 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
35077 return 1;
35080 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
35081 return 0;
35082 #endif
35085 #if SQLITE_MAX_MMAP_SIZE>0
35086 /* Forward references to VFS helper methods used for memory mapped files */
35087 static int winMapfile(winFile*, sqlite3_int64);
35088 static int winUnmapfile(winFile*);
35089 #endif
35092 ** Close a file.
35094 ** It is reported that an attempt to close a handle might sometimes
35095 ** fail. This is a very unreasonable result, but Windows is notorious
35096 ** for being unreasonable so I do not doubt that it might happen. If
35097 ** the close fails, we pause for 100 milliseconds and try again. As
35098 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
35099 ** giving up and returning an error.
35101 #define MX_CLOSE_ATTEMPT 3
35102 static int winClose(sqlite3_file *id){
35103 int rc, cnt = 0;
35104 winFile *pFile = (winFile*)id;
35106 assert( id!=0 );
35107 #ifndef SQLITE_OMIT_WAL
35108 assert( pFile->pShm==0 );
35109 #endif
35110 assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
35111 OSTRACE(("CLOSE file=%p\n", pFile->h));
35113 #if SQLITE_MAX_MMAP_SIZE>0
35114 winUnmapfile(pFile);
35115 #endif
35118 rc = osCloseHandle(pFile->h);
35119 /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
35120 }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
35121 #if SQLITE_OS_WINCE
35122 #define WINCE_DELETION_ATTEMPTS 3
35123 winceDestroyLock(pFile);
35124 if( pFile->zDeleteOnClose ){
35125 int cnt = 0;
35126 while(
35127 osDeleteFileW(pFile->zDeleteOnClose)==0
35128 && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
35129 && cnt++ < WINCE_DELETION_ATTEMPTS
35131 sqlite3_win32_sleep(100); /* Wait a little before trying again */
35133 sqlite3_free(pFile->zDeleteOnClose);
35135 #endif
35136 if( rc ){
35137 pFile->h = NULL;
35139 OpenCounter(-1);
35140 OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
35141 return rc ? SQLITE_OK
35142 : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
35143 "winClose", pFile->zPath);
35147 ** Read data from a file into a buffer. Return SQLITE_OK if all
35148 ** bytes were read successfully and SQLITE_IOERR if anything goes
35149 ** wrong.
35151 static int winRead(
35152 sqlite3_file *id, /* File to read from */
35153 void *pBuf, /* Write content into this buffer */
35154 int amt, /* Number of bytes to read */
35155 sqlite3_int64 offset /* Begin reading at this offset */
35157 #if !SQLITE_OS_WINCE
35158 OVERLAPPED overlapped; /* The offset for ReadFile. */
35159 #endif
35160 winFile *pFile = (winFile*)id; /* file handle */
35161 DWORD nRead; /* Number of bytes actually read from file */
35162 int nRetry = 0; /* Number of retrys */
35164 assert( id!=0 );
35165 assert( amt>0 );
35166 assert( offset>=0 );
35167 SimulateIOError(return SQLITE_IOERR_READ);
35168 OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
35169 pFile->h, pBuf, amt, offset, pFile->locktype));
35171 #if SQLITE_MAX_MMAP_SIZE>0
35172 /* Deal with as much of this read request as possible by transfering
35173 ** data from the memory mapping using memcpy(). */
35174 if( offset<pFile->mmapSize ){
35175 if( offset+amt <= pFile->mmapSize ){
35176 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
35177 OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
35178 return SQLITE_OK;
35179 }else{
35180 int nCopy = (int)(pFile->mmapSize - offset);
35181 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
35182 pBuf = &((u8 *)pBuf)[nCopy];
35183 amt -= nCopy;
35184 offset += nCopy;
35187 #endif
35189 #if SQLITE_OS_WINCE
35190 if( winSeekFile(pFile, offset) ){
35191 OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
35192 return SQLITE_FULL;
35194 while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
35195 #else
35196 memset(&overlapped, 0, sizeof(OVERLAPPED));
35197 overlapped.Offset = (LONG)(offset & 0xffffffff);
35198 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
35199 while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
35200 osGetLastError()!=ERROR_HANDLE_EOF ){
35201 #endif
35202 DWORD lastErrno;
35203 if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
35204 pFile->lastErrno = lastErrno;
35205 OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
35206 return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
35207 "winRead", pFile->zPath);
35209 winLogIoerr(nRetry);
35210 if( nRead<(DWORD)amt ){
35211 /* Unread parts of the buffer must be zero-filled */
35212 memset(&((char*)pBuf)[nRead], 0, amt-nRead);
35213 OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
35214 return SQLITE_IOERR_SHORT_READ;
35217 OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
35218 return SQLITE_OK;
35222 ** Write data from a buffer into a file. Return SQLITE_OK on success
35223 ** or some other error code on failure.
35225 static int winWrite(
35226 sqlite3_file *id, /* File to write into */
35227 const void *pBuf, /* The bytes to be written */
35228 int amt, /* Number of bytes to write */
35229 sqlite3_int64 offset /* Offset into the file to begin writing at */
35231 int rc = 0; /* True if error has occurred, else false */
35232 winFile *pFile = (winFile*)id; /* File handle */
35233 int nRetry = 0; /* Number of retries */
35235 assert( amt>0 );
35236 assert( pFile );
35237 SimulateIOError(return SQLITE_IOERR_WRITE);
35238 SimulateDiskfullError(return SQLITE_FULL);
35240 OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
35241 pFile->h, pBuf, amt, offset, pFile->locktype));
35243 #if !SQLITE_MMAP_READ_ONLY
35244 #if SQLITE_MAX_MMAP_SIZE>0
35245 /* Deal with as much of this write request as possible by transfering
35246 ** data from the memory mapping using memcpy(). */
35247 if( offset<pFile->mmapSize ){
35248 if( offset+amt <= pFile->mmapSize ){
35249 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
35250 OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
35251 return SQLITE_OK;
35252 }else{
35253 int nCopy = (int)(pFile->mmapSize - offset);
35254 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
35255 pBuf = &((u8 *)pBuf)[nCopy];
35256 amt -= nCopy;
35257 offset += nCopy;
35260 #endif
35261 #endif
35263 #if SQLITE_OS_WINCE
35264 rc = winSeekFile(pFile, offset);
35265 if( rc==0 ){
35266 #else
35268 #endif
35269 #if !SQLITE_OS_WINCE
35270 OVERLAPPED overlapped; /* The offset for WriteFile. */
35271 #endif
35272 u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
35273 int nRem = amt; /* Number of bytes yet to be written */
35274 DWORD nWrite; /* Bytes written by each WriteFile() call */
35275 DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
35277 #if !SQLITE_OS_WINCE
35278 memset(&overlapped, 0, sizeof(OVERLAPPED));
35279 overlapped.Offset = (LONG)(offset & 0xffffffff);
35280 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
35281 #endif
35283 while( nRem>0 ){
35284 #if SQLITE_OS_WINCE
35285 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
35286 #else
35287 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
35288 #endif
35289 if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
35290 break;
35292 assert( nWrite==0 || nWrite<=(DWORD)nRem );
35293 if( nWrite==0 || nWrite>(DWORD)nRem ){
35294 lastErrno = osGetLastError();
35295 break;
35297 #if !SQLITE_OS_WINCE
35298 offset += nWrite;
35299 overlapped.Offset = (LONG)(offset & 0xffffffff);
35300 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
35301 #endif
35302 aRem += nWrite;
35303 nRem -= nWrite;
35305 if( nRem>0 ){
35306 pFile->lastErrno = lastErrno;
35307 rc = 1;
35311 if( rc ){
35312 if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
35313 || ( pFile->lastErrno==ERROR_DISK_FULL )){
35314 OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
35315 return winLogError(SQLITE_FULL, pFile->lastErrno,
35316 "winWrite1", pFile->zPath);
35318 OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
35319 return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
35320 "winWrite2", pFile->zPath);
35321 }else{
35322 winLogIoerr(nRetry);
35324 OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
35325 return SQLITE_OK;
35329 ** Truncate an open file to a specified size
35331 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
35332 winFile *pFile = (winFile*)id; /* File handle object */
35333 int rc = SQLITE_OK; /* Return code for this function */
35334 DWORD lastErrno;
35336 assert( pFile );
35337 SimulateIOError(return SQLITE_IOERR_TRUNCATE);
35338 OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
35339 pFile->h, nByte, pFile->locktype));
35341 /* If the user has configured a chunk-size for this file, truncate the
35342 ** file so that it consists of an integer number of chunks (i.e. the
35343 ** actual file size after the operation may be larger than the requested
35344 ** size).
35346 if( pFile->szChunk>0 ){
35347 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
35350 /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
35351 if( winSeekFile(pFile, nByte) ){
35352 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
35353 "winTruncate1", pFile->zPath);
35354 }else if( 0==osSetEndOfFile(pFile->h) &&
35355 ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
35356 pFile->lastErrno = lastErrno;
35357 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
35358 "winTruncate2", pFile->zPath);
35361 #if SQLITE_MAX_MMAP_SIZE>0
35362 /* If the file was truncated to a size smaller than the currently
35363 ** mapped region, reduce the effective mapping size as well. SQLite will
35364 ** use read() and write() to access data beyond this point from now on.
35366 if( pFile->pMapRegion && nByte<pFile->mmapSize ){
35367 pFile->mmapSize = nByte;
35369 #endif
35371 OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
35372 return rc;
35375 #ifdef SQLITE_TEST
35377 ** Count the number of fullsyncs and normal syncs. This is used to test
35378 ** that syncs and fullsyncs are occuring at the right times.
35380 SQLITE_API int sqlite3_sync_count = 0;
35381 SQLITE_API int sqlite3_fullsync_count = 0;
35382 #endif
35385 ** Make sure all writes to a particular file are committed to disk.
35387 static int winSync(sqlite3_file *id, int flags){
35388 #ifndef SQLITE_NO_SYNC
35390 ** Used only when SQLITE_NO_SYNC is not defined.
35392 BOOL rc;
35393 #endif
35394 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
35395 (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
35397 ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
35398 ** OSTRACE() macros.
35400 winFile *pFile = (winFile*)id;
35401 #else
35402 UNUSED_PARAMETER(id);
35403 #endif
35405 assert( pFile );
35406 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
35407 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
35408 || (flags&0x0F)==SQLITE_SYNC_FULL
35411 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
35412 ** line is to test that doing so does not cause any problems.
35414 SimulateDiskfullError( return SQLITE_FULL );
35416 OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
35417 pFile->h, flags, pFile->locktype));
35419 #ifndef SQLITE_TEST
35420 UNUSED_PARAMETER(flags);
35421 #else
35422 if( (flags&0x0F)==SQLITE_SYNC_FULL ){
35423 sqlite3_fullsync_count++;
35425 sqlite3_sync_count++;
35426 #endif
35428 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
35429 ** no-op
35431 #ifdef SQLITE_NO_SYNC
35432 OSTRACE(("SYNC-NOP file=%p, rc=SQLITE_OK\n", pFile->h));
35433 return SQLITE_OK;
35434 #else
35435 rc = osFlushFileBuffers(pFile->h);
35436 SimulateIOError( rc=FALSE );
35437 if( rc ){
35438 OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
35439 return SQLITE_OK;
35440 }else{
35441 pFile->lastErrno = osGetLastError();
35442 OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
35443 return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
35444 "winSync", pFile->zPath);
35446 #endif
35450 ** Determine the current size of a file in bytes
35452 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
35453 winFile *pFile = (winFile*)id;
35454 int rc = SQLITE_OK;
35456 assert( id!=0 );
35457 assert( pSize!=0 );
35458 SimulateIOError(return SQLITE_IOERR_FSTAT);
35459 OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
35461 #if SQLITE_OS_WINRT
35463 FILE_STANDARD_INFO info;
35464 if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
35465 &info, sizeof(info)) ){
35466 *pSize = info.EndOfFile.QuadPart;
35467 }else{
35468 pFile->lastErrno = osGetLastError();
35469 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
35470 "winFileSize", pFile->zPath);
35473 #else
35475 DWORD upperBits;
35476 DWORD lowerBits;
35477 DWORD lastErrno;
35479 lowerBits = osGetFileSize(pFile->h, &upperBits);
35480 *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
35481 if( (lowerBits == INVALID_FILE_SIZE)
35482 && ((lastErrno = osGetLastError())!=NO_ERROR) ){
35483 pFile->lastErrno = lastErrno;
35484 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
35485 "winFileSize", pFile->zPath);
35488 #endif
35489 OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
35490 pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
35491 return rc;
35495 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
35497 #ifndef LOCKFILE_FAIL_IMMEDIATELY
35498 # define LOCKFILE_FAIL_IMMEDIATELY 1
35499 #endif
35501 #ifndef LOCKFILE_EXCLUSIVE_LOCK
35502 # define LOCKFILE_EXCLUSIVE_LOCK 2
35503 #endif
35506 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
35507 ** When the LockFile function was used, it was always expected to fail
35508 ** immediately if the lock could not be obtained. Also, it always expected to
35509 ** obtain an exclusive lock. These flags are used with the LockFileEx function
35510 ** and reflect those expectations; therefore, they should not be changed.
35512 #ifndef SQLITE_LOCKFILE_FLAGS
35513 # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
35514 LOCKFILE_EXCLUSIVE_LOCK)
35515 #endif
35518 ** Currently, SQLite never calls the LockFileEx function without wanting the
35519 ** call to fail immediately if the lock cannot be obtained.
35521 #ifndef SQLITE_LOCKFILEEX_FLAGS
35522 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
35523 #endif
35526 ** Acquire a reader lock.
35527 ** Different API routines are called depending on whether or not this
35528 ** is Win9x or WinNT.
35530 static int winGetReadLock(winFile *pFile){
35531 int res;
35532 OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
35533 if( osIsNT() ){
35534 #if SQLITE_OS_WINCE
35536 ** NOTE: Windows CE is handled differently here due its lack of the Win32
35537 ** API LockFileEx.
35539 res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
35540 #else
35541 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
35542 SHARED_SIZE, 0);
35543 #endif
35545 #ifdef SQLITE_WIN32_HAS_ANSI
35546 else{
35547 int lk;
35548 sqlite3_randomness(sizeof(lk), &lk);
35549 pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
35550 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
35551 SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
35553 #endif
35554 if( res == 0 ){
35555 pFile->lastErrno = osGetLastError();
35556 /* No need to log a failure to lock */
35558 OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
35559 return res;
35563 ** Undo a readlock
35565 static int winUnlockReadLock(winFile *pFile){
35566 int res;
35567 DWORD lastErrno;
35568 OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
35569 if( osIsNT() ){
35570 res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
35572 #ifdef SQLITE_WIN32_HAS_ANSI
35573 else{
35574 res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
35576 #endif
35577 if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
35578 pFile->lastErrno = lastErrno;
35579 winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
35580 "winUnlockReadLock", pFile->zPath);
35582 OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
35583 return res;
35587 ** Lock the file with the lock specified by parameter locktype - one
35588 ** of the following:
35590 ** (1) SHARED_LOCK
35591 ** (2) RESERVED_LOCK
35592 ** (3) PENDING_LOCK
35593 ** (4) EXCLUSIVE_LOCK
35595 ** Sometimes when requesting one lock state, additional lock states
35596 ** are inserted in between. The locking might fail on one of the later
35597 ** transitions leaving the lock state different from what it started but
35598 ** still short of its goal. The following chart shows the allowed
35599 ** transitions and the inserted intermediate states:
35601 ** UNLOCKED -> SHARED
35602 ** SHARED -> RESERVED
35603 ** SHARED -> (PENDING) -> EXCLUSIVE
35604 ** RESERVED -> (PENDING) -> EXCLUSIVE
35605 ** PENDING -> EXCLUSIVE
35607 ** This routine will only increase a lock. The winUnlock() routine
35608 ** erases all locks at once and returns us immediately to locking level 0.
35609 ** It is not possible to lower the locking level one step at a time. You
35610 ** must go straight to locking level 0.
35612 static int winLock(sqlite3_file *id, int locktype){
35613 int rc = SQLITE_OK; /* Return code from subroutines */
35614 int res = 1; /* Result of a Windows lock call */
35615 int newLocktype; /* Set pFile->locktype to this value before exiting */
35616 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
35617 winFile *pFile = (winFile*)id;
35618 DWORD lastErrno = NO_ERROR;
35620 assert( id!=0 );
35621 OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
35622 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
35624 /* If there is already a lock of this type or more restrictive on the
35625 ** OsFile, do nothing. Don't use the end_lock: exit path, as
35626 ** sqlite3OsEnterMutex() hasn't been called yet.
35628 if( pFile->locktype>=locktype ){
35629 OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
35630 return SQLITE_OK;
35633 /* Make sure the locking sequence is correct
35635 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
35636 assert( locktype!=PENDING_LOCK );
35637 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
35639 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
35640 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
35641 ** the PENDING_LOCK byte is temporary.
35643 newLocktype = pFile->locktype;
35644 if( (pFile->locktype==NO_LOCK)
35645 || ( (locktype==EXCLUSIVE_LOCK)
35646 && (pFile->locktype==RESERVED_LOCK))
35648 int cnt = 3;
35649 while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
35650 PENDING_BYTE, 0, 1, 0))==0 ){
35651 /* Try 3 times to get the pending lock. This is needed to work
35652 ** around problems caused by indexing and/or anti-virus software on
35653 ** Windows systems.
35654 ** If you are using this code as a model for alternative VFSes, do not
35655 ** copy this retry logic. It is a hack intended for Windows only.
35657 lastErrno = osGetLastError();
35658 OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
35659 pFile->h, cnt, res));
35660 if( lastErrno==ERROR_INVALID_HANDLE ){
35661 pFile->lastErrno = lastErrno;
35662 rc = SQLITE_IOERR_LOCK;
35663 OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
35664 pFile->h, cnt, sqlite3ErrName(rc)));
35665 return rc;
35667 if( cnt ) sqlite3_win32_sleep(1);
35669 gotPendingLock = res;
35670 if( !res ){
35671 lastErrno = osGetLastError();
35675 /* Acquire a shared lock
35677 if( locktype==SHARED_LOCK && res ){
35678 assert( pFile->locktype==NO_LOCK );
35679 res = winGetReadLock(pFile);
35680 if( res ){
35681 newLocktype = SHARED_LOCK;
35682 }else{
35683 lastErrno = osGetLastError();
35687 /* Acquire a RESERVED lock
35689 if( locktype==RESERVED_LOCK && res ){
35690 assert( pFile->locktype==SHARED_LOCK );
35691 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
35692 if( res ){
35693 newLocktype = RESERVED_LOCK;
35694 }else{
35695 lastErrno = osGetLastError();
35699 /* Acquire a PENDING lock
35701 if( locktype==EXCLUSIVE_LOCK && res ){
35702 newLocktype = PENDING_LOCK;
35703 gotPendingLock = 0;
35706 /* Acquire an EXCLUSIVE lock
35708 if( locktype==EXCLUSIVE_LOCK && res ){
35709 assert( pFile->locktype>=SHARED_LOCK );
35710 res = winUnlockReadLock(pFile);
35711 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
35712 SHARED_SIZE, 0);
35713 if( res ){
35714 newLocktype = EXCLUSIVE_LOCK;
35715 }else{
35716 lastErrno = osGetLastError();
35717 winGetReadLock(pFile);
35721 /* If we are holding a PENDING lock that ought to be released, then
35722 ** release it now.
35724 if( gotPendingLock && locktype==SHARED_LOCK ){
35725 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
35728 /* Update the state of the lock has held in the file descriptor then
35729 ** return the appropriate result code.
35731 if( res ){
35732 rc = SQLITE_OK;
35733 }else{
35734 pFile->lastErrno = lastErrno;
35735 rc = SQLITE_BUSY;
35736 OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
35737 pFile->h, locktype, newLocktype));
35739 pFile->locktype = (u8)newLocktype;
35740 OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
35741 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
35742 return rc;
35746 ** This routine checks if there is a RESERVED lock held on the specified
35747 ** file by this or any other process. If such a lock is held, return
35748 ** non-zero, otherwise zero.
35750 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
35751 int res;
35752 winFile *pFile = (winFile*)id;
35754 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
35755 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
35757 assert( id!=0 );
35758 if( pFile->locktype>=RESERVED_LOCK ){
35759 res = 1;
35760 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
35761 }else{
35762 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
35763 if( res ){
35764 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
35766 res = !res;
35767 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
35769 *pResOut = res;
35770 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
35771 pFile->h, pResOut, *pResOut));
35772 return SQLITE_OK;
35776 ** Lower the locking level on file descriptor id to locktype. locktype
35777 ** must be either NO_LOCK or SHARED_LOCK.
35779 ** If the locking level of the file descriptor is already at or below
35780 ** the requested locking level, this routine is a no-op.
35782 ** It is not possible for this routine to fail if the second argument
35783 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
35784 ** might return SQLITE_IOERR;
35786 static int winUnlock(sqlite3_file *id, int locktype){
35787 int type;
35788 winFile *pFile = (winFile*)id;
35789 int rc = SQLITE_OK;
35790 assert( pFile!=0 );
35791 assert( locktype<=SHARED_LOCK );
35792 OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
35793 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
35794 type = pFile->locktype;
35795 if( type>=EXCLUSIVE_LOCK ){
35796 winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
35797 if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
35798 /* This should never happen. We should always be able to
35799 ** reacquire the read lock */
35800 rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
35801 "winUnlock", pFile->zPath);
35804 if( type>=RESERVED_LOCK ){
35805 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
35807 if( locktype==NO_LOCK && type>=SHARED_LOCK ){
35808 winUnlockReadLock(pFile);
35810 if( type>=PENDING_LOCK ){
35811 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
35813 pFile->locktype = (u8)locktype;
35814 OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
35815 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
35816 return rc;
35820 ** If *pArg is initially negative then this is a query. Set *pArg to
35821 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
35823 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
35825 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
35826 if( *pArg<0 ){
35827 *pArg = (pFile->ctrlFlags & mask)!=0;
35828 }else if( (*pArg)==0 ){
35829 pFile->ctrlFlags &= ~mask;
35830 }else{
35831 pFile->ctrlFlags |= mask;
35835 /* Forward references to VFS helper methods used for temporary files */
35836 static int winGetTempname(sqlite3_vfs *, char **);
35837 static int winIsDir(const void *);
35838 static BOOL winIsDriveLetterAndColon(const char *);
35841 ** Control and query of the open file handle.
35843 static int winFileControl(sqlite3_file *id, int op, void *pArg){
35844 winFile *pFile = (winFile*)id;
35845 OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
35846 switch( op ){
35847 case SQLITE_FCNTL_LOCKSTATE: {
35848 *(int*)pArg = pFile->locktype;
35849 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35850 return SQLITE_OK;
35852 case SQLITE_LAST_ERRNO: {
35853 *(int*)pArg = (int)pFile->lastErrno;
35854 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35855 return SQLITE_OK;
35857 case SQLITE_FCNTL_CHUNK_SIZE: {
35858 pFile->szChunk = *(int *)pArg;
35859 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35860 return SQLITE_OK;
35862 case SQLITE_FCNTL_SIZE_HINT: {
35863 if( pFile->szChunk>0 ){
35864 sqlite3_int64 oldSz;
35865 int rc = winFileSize(id, &oldSz);
35866 if( rc==SQLITE_OK ){
35867 sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
35868 if( newSz>oldSz ){
35869 SimulateIOErrorBenign(1);
35870 rc = winTruncate(id, newSz);
35871 SimulateIOErrorBenign(0);
35874 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
35875 return rc;
35877 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35878 return SQLITE_OK;
35880 case SQLITE_FCNTL_PERSIST_WAL: {
35881 winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
35882 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35883 return SQLITE_OK;
35885 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
35886 winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
35887 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35888 return SQLITE_OK;
35890 case SQLITE_FCNTL_VFSNAME: {
35891 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
35892 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35893 return SQLITE_OK;
35895 case SQLITE_FCNTL_WIN32_AV_RETRY: {
35896 int *a = (int*)pArg;
35897 if( a[0]>0 ){
35898 winIoerrRetry = a[0];
35899 }else{
35900 a[0] = winIoerrRetry;
35902 if( a[1]>0 ){
35903 winIoerrRetryDelay = a[1];
35904 }else{
35905 a[1] = winIoerrRetryDelay;
35907 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35908 return SQLITE_OK;
35910 #ifdef SQLITE_TEST
35911 case SQLITE_FCNTL_WIN32_SET_HANDLE: {
35912 LPHANDLE phFile = (LPHANDLE)pArg;
35913 HANDLE hOldFile = pFile->h;
35914 pFile->h = *phFile;
35915 *phFile = hOldFile;
35916 OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
35917 hOldFile, pFile->h));
35918 return SQLITE_OK;
35920 #endif
35921 case SQLITE_FCNTL_TEMPFILENAME: {
35922 char *zTFile = 0;
35923 int rc = winGetTempname(pFile->pVfs, &zTFile);
35924 if( rc==SQLITE_OK ){
35925 *(char**)pArg = zTFile;
35927 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
35928 return rc;
35930 #if SQLITE_MAX_MMAP_SIZE>0
35931 case SQLITE_FCNTL_MMAP_SIZE: {
35932 i64 newLimit = *(i64*)pArg;
35933 int rc = SQLITE_OK;
35934 if( newLimit>sqlite3GlobalConfig.mxMmap ){
35935 newLimit = sqlite3GlobalConfig.mxMmap;
35937 *(i64*)pArg = pFile->mmapSizeMax;
35938 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
35939 pFile->mmapSizeMax = newLimit;
35940 if( pFile->mmapSize>0 ){
35941 winUnmapfile(pFile);
35942 rc = winMapfile(pFile, -1);
35945 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
35946 return rc;
35948 #endif
35950 OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
35951 return SQLITE_NOTFOUND;
35955 ** Return the sector size in bytes of the underlying block device for
35956 ** the specified file. This is almost always 512 bytes, but may be
35957 ** larger for some devices.
35959 ** SQLite code assumes this function cannot fail. It also assumes that
35960 ** if two files are created in the same file-system directory (i.e.
35961 ** a database and its journal file) that the sector size will be the
35962 ** same for both.
35964 static int winSectorSize(sqlite3_file *id){
35965 (void)id;
35966 return SQLITE_DEFAULT_SECTOR_SIZE;
35970 ** Return a vector of device characteristics.
35972 static int winDeviceCharacteristics(sqlite3_file *id){
35973 winFile *p = (winFile*)id;
35974 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
35975 ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
35979 ** Windows will only let you create file view mappings
35980 ** on allocation size granularity boundaries.
35981 ** During sqlite3_os_init() we do a GetSystemInfo()
35982 ** to get the granularity size.
35984 static SYSTEM_INFO winSysInfo;
35986 #ifndef SQLITE_OMIT_WAL
35989 ** Helper functions to obtain and relinquish the global mutex. The
35990 ** global mutex is used to protect the winLockInfo objects used by
35991 ** this file, all of which may be shared by multiple threads.
35993 ** Function winShmMutexHeld() is used to assert() that the global mutex
35994 ** is held when required. This function is only used as part of assert()
35995 ** statements. e.g.
35997 ** winShmEnterMutex()
35998 ** assert( winShmMutexHeld() );
35999 ** winShmLeaveMutex()
36001 static void winShmEnterMutex(void){
36002 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
36004 static void winShmLeaveMutex(void){
36005 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
36007 #ifndef NDEBUG
36008 static int winShmMutexHeld(void) {
36009 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
36011 #endif
36014 ** Object used to represent a single file opened and mmapped to provide
36015 ** shared memory. When multiple threads all reference the same
36016 ** log-summary, each thread has its own winFile object, but they all
36017 ** point to a single instance of this object. In other words, each
36018 ** log-summary is opened only once per process.
36020 ** winShmMutexHeld() must be true when creating or destroying
36021 ** this object or while reading or writing the following fields:
36023 ** nRef
36024 ** pNext
36026 ** The following fields are read-only after the object is created:
36028 ** fid
36029 ** zFilename
36031 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
36032 ** winShmMutexHeld() is true when reading or writing any other field
36033 ** in this structure.
36036 struct winShmNode {
36037 sqlite3_mutex *mutex; /* Mutex to access this object */
36038 char *zFilename; /* Name of the file */
36039 winFile hFile; /* File handle from winOpen */
36041 int szRegion; /* Size of shared-memory regions */
36042 int nRegion; /* Size of array apRegion */
36043 struct ShmRegion {
36044 HANDLE hMap; /* File handle from CreateFileMapping */
36045 void *pMap;
36046 } *aRegion;
36047 DWORD lastErrno; /* The Windows errno from the last I/O error */
36049 int nRef; /* Number of winShm objects pointing to this */
36050 winShm *pFirst; /* All winShm objects pointing to this */
36051 winShmNode *pNext; /* Next in list of all winShmNode objects */
36052 #ifdef SQLITE_DEBUG
36053 u8 nextShmId; /* Next available winShm.id value */
36054 #endif
36058 ** A global array of all winShmNode objects.
36060 ** The winShmMutexHeld() must be true while reading or writing this list.
36062 static winShmNode *winShmNodeList = 0;
36065 ** Structure used internally by this VFS to record the state of an
36066 ** open shared memory connection.
36068 ** The following fields are initialized when this object is created and
36069 ** are read-only thereafter:
36071 ** winShm.pShmNode
36072 ** winShm.id
36074 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
36075 ** while accessing any read/write fields.
36077 struct winShm {
36078 winShmNode *pShmNode; /* The underlying winShmNode object */
36079 winShm *pNext; /* Next winShm with the same winShmNode */
36080 u8 hasMutex; /* True if holding the winShmNode mutex */
36081 u16 sharedMask; /* Mask of shared locks held */
36082 u16 exclMask; /* Mask of exclusive locks held */
36083 #ifdef SQLITE_DEBUG
36084 u8 id; /* Id of this connection with its winShmNode */
36085 #endif
36089 ** Constants used for locking
36091 #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
36092 #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
36095 ** Apply advisory locks for all n bytes beginning at ofst.
36097 #define _SHM_UNLCK 1
36098 #define _SHM_RDLCK 2
36099 #define _SHM_WRLCK 3
36100 static int winShmSystemLock(
36101 winShmNode *pFile, /* Apply locks to this open shared-memory segment */
36102 int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
36103 int ofst, /* Offset to first byte to be locked/unlocked */
36104 int nByte /* Number of bytes to lock or unlock */
36106 int rc = 0; /* Result code form Lock/UnlockFileEx() */
36108 /* Access to the winShmNode object is serialized by the caller */
36109 assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
36111 OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
36112 pFile->hFile.h, lockType, ofst, nByte));
36114 /* Release/Acquire the system-level lock */
36115 if( lockType==_SHM_UNLCK ){
36116 rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
36117 }else{
36118 /* Initialize the locking parameters */
36119 DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
36120 if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
36121 rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
36124 if( rc!= 0 ){
36125 rc = SQLITE_OK;
36126 }else{
36127 pFile->lastErrno = osGetLastError();
36128 rc = SQLITE_BUSY;
36131 OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
36132 pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
36133 "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
36135 return rc;
36138 /* Forward references to VFS methods */
36139 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
36140 static int winDelete(sqlite3_vfs *,const char*,int);
36143 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
36145 ** This is not a VFS shared-memory method; it is a utility function called
36146 ** by VFS shared-memory methods.
36148 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
36149 winShmNode **pp;
36150 winShmNode *p;
36151 assert( winShmMutexHeld() );
36152 OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
36153 osGetCurrentProcessId(), deleteFlag));
36154 pp = &winShmNodeList;
36155 while( (p = *pp)!=0 ){
36156 if( p->nRef==0 ){
36157 int i;
36158 if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
36159 for(i=0; i<p->nRegion; i++){
36160 BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
36161 OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
36162 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
36163 UNUSED_VARIABLE_VALUE(bRc);
36164 bRc = osCloseHandle(p->aRegion[i].hMap);
36165 OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
36166 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
36167 UNUSED_VARIABLE_VALUE(bRc);
36169 if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
36170 SimulateIOErrorBenign(1);
36171 winClose((sqlite3_file *)&p->hFile);
36172 SimulateIOErrorBenign(0);
36174 if( deleteFlag ){
36175 SimulateIOErrorBenign(1);
36176 sqlite3BeginBenignMalloc();
36177 winDelete(pVfs, p->zFilename, 0);
36178 sqlite3EndBenignMalloc();
36179 SimulateIOErrorBenign(0);
36181 *pp = p->pNext;
36182 sqlite3_free(p->aRegion);
36183 sqlite3_free(p);
36184 }else{
36185 pp = &p->pNext;
36191 ** Open the shared-memory area associated with database file pDbFd.
36193 ** When opening a new shared-memory file, if no other instances of that
36194 ** file are currently open, in this process or in other processes, then
36195 ** the file must be truncated to zero length or have its header cleared.
36197 static int winOpenSharedMemory(winFile *pDbFd){
36198 struct winShm *p; /* The connection to be opened */
36199 struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
36200 int rc; /* Result code */
36201 struct winShmNode *pNew; /* Newly allocated winShmNode */
36202 int nName; /* Size of zName in bytes */
36204 assert( pDbFd->pShm==0 ); /* Not previously opened */
36206 /* Allocate space for the new sqlite3_shm object. Also speculatively
36207 ** allocate space for a new winShmNode and filename.
36209 p = sqlite3MallocZero( sizeof(*p) );
36210 if( p==0 ) return SQLITE_IOERR_NOMEM;
36211 nName = sqlite3Strlen30(pDbFd->zPath);
36212 pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
36213 if( pNew==0 ){
36214 sqlite3_free(p);
36215 return SQLITE_IOERR_NOMEM;
36217 pNew->zFilename = (char*)&pNew[1];
36218 sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
36219 sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
36221 /* Look to see if there is an existing winShmNode that can be used.
36222 ** If no matching winShmNode currently exists, create a new one.
36224 winShmEnterMutex();
36225 for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
36226 /* TBD need to come up with better match here. Perhaps
36227 ** use FILE_ID_BOTH_DIR_INFO Structure.
36229 if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
36231 if( pShmNode ){
36232 sqlite3_free(pNew);
36233 }else{
36234 pShmNode = pNew;
36235 pNew = 0;
36236 ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
36237 pShmNode->pNext = winShmNodeList;
36238 winShmNodeList = pShmNode;
36240 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
36241 if( pShmNode->mutex==0 ){
36242 rc = SQLITE_IOERR_NOMEM;
36243 goto shm_open_err;
36246 rc = winOpen(pDbFd->pVfs,
36247 pShmNode->zFilename, /* Name of the file (UTF-8) */
36248 (sqlite3_file*)&pShmNode->hFile, /* File handle here */
36249 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
36251 if( SQLITE_OK!=rc ){
36252 goto shm_open_err;
36255 /* Check to see if another process is holding the dead-man switch.
36256 ** If not, truncate the file to zero length.
36258 if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
36259 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
36260 if( rc!=SQLITE_OK ){
36261 rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
36262 "winOpenShm", pDbFd->zPath);
36265 if( rc==SQLITE_OK ){
36266 winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
36267 rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
36269 if( rc ) goto shm_open_err;
36272 /* Make the new connection a child of the winShmNode */
36273 p->pShmNode = pShmNode;
36274 #ifdef SQLITE_DEBUG
36275 p->id = pShmNode->nextShmId++;
36276 #endif
36277 pShmNode->nRef++;
36278 pDbFd->pShm = p;
36279 winShmLeaveMutex();
36281 /* The reference count on pShmNode has already been incremented under
36282 ** the cover of the winShmEnterMutex() mutex and the pointer from the
36283 ** new (struct winShm) object to the pShmNode has been set. All that is
36284 ** left to do is to link the new object into the linked list starting
36285 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
36286 ** mutex.
36288 sqlite3_mutex_enter(pShmNode->mutex);
36289 p->pNext = pShmNode->pFirst;
36290 pShmNode->pFirst = p;
36291 sqlite3_mutex_leave(pShmNode->mutex);
36292 return SQLITE_OK;
36294 /* Jump here on any error */
36295 shm_open_err:
36296 winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
36297 winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
36298 sqlite3_free(p);
36299 sqlite3_free(pNew);
36300 winShmLeaveMutex();
36301 return rc;
36305 ** Close a connection to shared-memory. Delete the underlying
36306 ** storage if deleteFlag is true.
36308 static int winShmUnmap(
36309 sqlite3_file *fd, /* Database holding shared memory */
36310 int deleteFlag /* Delete after closing if true */
36312 winFile *pDbFd; /* Database holding shared-memory */
36313 winShm *p; /* The connection to be closed */
36314 winShmNode *pShmNode; /* The underlying shared-memory file */
36315 winShm **pp; /* For looping over sibling connections */
36317 pDbFd = (winFile*)fd;
36318 p = pDbFd->pShm;
36319 if( p==0 ) return SQLITE_OK;
36320 pShmNode = p->pShmNode;
36322 /* Remove connection p from the set of connections associated
36323 ** with pShmNode */
36324 sqlite3_mutex_enter(pShmNode->mutex);
36325 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
36326 *pp = p->pNext;
36328 /* Free the connection p */
36329 sqlite3_free(p);
36330 pDbFd->pShm = 0;
36331 sqlite3_mutex_leave(pShmNode->mutex);
36333 /* If pShmNode->nRef has reached 0, then close the underlying
36334 ** shared-memory file, too */
36335 winShmEnterMutex();
36336 assert( pShmNode->nRef>0 );
36337 pShmNode->nRef--;
36338 if( pShmNode->nRef==0 ){
36339 winShmPurge(pDbFd->pVfs, deleteFlag);
36341 winShmLeaveMutex();
36343 return SQLITE_OK;
36347 ** Change the lock state for a shared-memory segment.
36349 static int winShmLock(
36350 sqlite3_file *fd, /* Database file holding the shared memory */
36351 int ofst, /* First lock to acquire or release */
36352 int n, /* Number of locks to acquire or release */
36353 int flags /* What to do with the lock */
36355 winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
36356 winShm *p = pDbFd->pShm; /* The shared memory being locked */
36357 winShm *pX; /* For looping over all siblings */
36358 winShmNode *pShmNode = p->pShmNode;
36359 int rc = SQLITE_OK; /* Result code */
36360 u16 mask; /* Mask of locks to take or release */
36362 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
36363 assert( n>=1 );
36364 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
36365 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
36366 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
36367 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
36368 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
36370 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
36371 assert( n>1 || mask==(1<<ofst) );
36372 sqlite3_mutex_enter(pShmNode->mutex);
36373 if( flags & SQLITE_SHM_UNLOCK ){
36374 u16 allMask = 0; /* Mask of locks held by siblings */
36376 /* See if any siblings hold this same lock */
36377 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
36378 if( pX==p ) continue;
36379 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
36380 allMask |= pX->sharedMask;
36383 /* Unlock the system-level locks */
36384 if( (mask & allMask)==0 ){
36385 rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
36386 }else{
36387 rc = SQLITE_OK;
36390 /* Undo the local locks */
36391 if( rc==SQLITE_OK ){
36392 p->exclMask &= ~mask;
36393 p->sharedMask &= ~mask;
36395 }else if( flags & SQLITE_SHM_SHARED ){
36396 u16 allShared = 0; /* Union of locks held by connections other than "p" */
36398 /* Find out which shared locks are already held by sibling connections.
36399 ** If any sibling already holds an exclusive lock, go ahead and return
36400 ** SQLITE_BUSY.
36402 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
36403 if( (pX->exclMask & mask)!=0 ){
36404 rc = SQLITE_BUSY;
36405 break;
36407 allShared |= pX->sharedMask;
36410 /* Get shared locks at the system level, if necessary */
36411 if( rc==SQLITE_OK ){
36412 if( (allShared & mask)==0 ){
36413 rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
36414 }else{
36415 rc = SQLITE_OK;
36419 /* Get the local shared locks */
36420 if( rc==SQLITE_OK ){
36421 p->sharedMask |= mask;
36423 }else{
36424 /* Make sure no sibling connections hold locks that will block this
36425 ** lock. If any do, return SQLITE_BUSY right away.
36427 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
36428 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
36429 rc = SQLITE_BUSY;
36430 break;
36434 /* Get the exclusive locks at the system level. Then if successful
36435 ** also mark the local connection as being locked.
36437 if( rc==SQLITE_OK ){
36438 rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
36439 if( rc==SQLITE_OK ){
36440 assert( (p->sharedMask & mask)==0 );
36441 p->exclMask |= mask;
36445 sqlite3_mutex_leave(pShmNode->mutex);
36446 OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
36447 osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
36448 sqlite3ErrName(rc)));
36449 return rc;
36453 ** Implement a memory barrier or memory fence on shared memory.
36455 ** All loads and stores begun before the barrier must complete before
36456 ** any load or store begun after the barrier.
36458 static void winShmBarrier(
36459 sqlite3_file *fd /* Database holding the shared memory */
36461 UNUSED_PARAMETER(fd);
36462 /* MemoryBarrier(); // does not work -- do not know why not */
36463 winShmEnterMutex();
36464 winShmLeaveMutex();
36468 ** This function is called to obtain a pointer to region iRegion of the
36469 ** shared-memory associated with the database file fd. Shared-memory regions
36470 ** are numbered starting from zero. Each shared-memory region is szRegion
36471 ** bytes in size.
36473 ** If an error occurs, an error code is returned and *pp is set to NULL.
36475 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
36476 ** region has not been allocated (by any client, including one running in a
36477 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
36478 ** isWrite is non-zero and the requested shared-memory region has not yet
36479 ** been allocated, it is allocated by this function.
36481 ** If the shared-memory region has already been allocated or is allocated by
36482 ** this call as described above, then it is mapped into this processes
36483 ** address space (if it is not already), *pp is set to point to the mapped
36484 ** memory and SQLITE_OK returned.
36486 static int winShmMap(
36487 sqlite3_file *fd, /* Handle open on database file */
36488 int iRegion, /* Region to retrieve */
36489 int szRegion, /* Size of regions */
36490 int isWrite, /* True to extend file if necessary */
36491 void volatile **pp /* OUT: Mapped memory */
36493 winFile *pDbFd = (winFile*)fd;
36494 winShm *p = pDbFd->pShm;
36495 winShmNode *pShmNode;
36496 int rc = SQLITE_OK;
36498 if( !p ){
36499 rc = winOpenSharedMemory(pDbFd);
36500 if( rc!=SQLITE_OK ) return rc;
36501 p = pDbFd->pShm;
36503 pShmNode = p->pShmNode;
36505 sqlite3_mutex_enter(pShmNode->mutex);
36506 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
36508 if( pShmNode->nRegion<=iRegion ){
36509 struct ShmRegion *apNew; /* New aRegion[] array */
36510 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
36511 sqlite3_int64 sz; /* Current size of wal-index file */
36513 pShmNode->szRegion = szRegion;
36515 /* The requested region is not mapped into this processes address space.
36516 ** Check to see if it has been allocated (i.e. if the wal-index file is
36517 ** large enough to contain the requested region).
36519 rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
36520 if( rc!=SQLITE_OK ){
36521 rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
36522 "winShmMap1", pDbFd->zPath);
36523 goto shmpage_out;
36526 if( sz<nByte ){
36527 /* The requested memory region does not exist. If isWrite is set to
36528 ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
36530 ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
36531 ** the requested memory region.
36533 if( !isWrite ) goto shmpage_out;
36534 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
36535 if( rc!=SQLITE_OK ){
36536 rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
36537 "winShmMap2", pDbFd->zPath);
36538 goto shmpage_out;
36542 /* Map the requested memory region into this processes address space. */
36543 apNew = (struct ShmRegion *)sqlite3_realloc(
36544 pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
36546 if( !apNew ){
36547 rc = SQLITE_IOERR_NOMEM;
36548 goto shmpage_out;
36550 pShmNode->aRegion = apNew;
36552 while( pShmNode->nRegion<=iRegion ){
36553 HANDLE hMap = NULL; /* file-mapping handle */
36554 void *pMap = 0; /* Mapped memory region */
36556 #if SQLITE_OS_WINRT
36557 hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
36558 NULL, PAGE_READWRITE, nByte, NULL
36560 #elif defined(SQLITE_WIN32_HAS_WIDE)
36561 hMap = osCreateFileMappingW(pShmNode->hFile.h,
36562 NULL, PAGE_READWRITE, 0, nByte, NULL
36564 #elif defined(SQLITE_WIN32_HAS_ANSI)
36565 hMap = osCreateFileMappingA(pShmNode->hFile.h,
36566 NULL, PAGE_READWRITE, 0, nByte, NULL
36568 #endif
36569 OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
36570 osGetCurrentProcessId(), pShmNode->nRegion, nByte,
36571 hMap ? "ok" : "failed"));
36572 if( hMap ){
36573 int iOffset = pShmNode->nRegion*szRegion;
36574 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
36575 #if SQLITE_OS_WINRT
36576 pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
36577 iOffset - iOffsetShift, szRegion + iOffsetShift
36579 #else
36580 pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
36581 0, iOffset - iOffsetShift, szRegion + iOffsetShift
36583 #endif
36584 OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
36585 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
36586 szRegion, pMap ? "ok" : "failed"));
36588 if( !pMap ){
36589 pShmNode->lastErrno = osGetLastError();
36590 rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
36591 "winShmMap3", pDbFd->zPath);
36592 if( hMap ) osCloseHandle(hMap);
36593 goto shmpage_out;
36596 pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
36597 pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
36598 pShmNode->nRegion++;
36602 shmpage_out:
36603 if( pShmNode->nRegion>iRegion ){
36604 int iOffset = iRegion*szRegion;
36605 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
36606 char *p = (char *)pShmNode->aRegion[iRegion].pMap;
36607 *pp = (void *)&p[iOffsetShift];
36608 }else{
36609 *pp = 0;
36611 sqlite3_mutex_leave(pShmNode->mutex);
36612 return rc;
36615 #else
36616 # define winShmMap 0
36617 # define winShmLock 0
36618 # define winShmBarrier 0
36619 # define winShmUnmap 0
36620 #endif /* #ifndef SQLITE_OMIT_WAL */
36623 ** Cleans up the mapped region of the specified file, if any.
36625 #if SQLITE_MAX_MMAP_SIZE>0
36626 static int winUnmapfile(winFile *pFile){
36627 assert( pFile!=0 );
36628 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
36629 "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
36630 osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
36631 pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
36632 if( pFile->pMapRegion ){
36633 if( !osUnmapViewOfFile(pFile->pMapRegion) ){
36634 pFile->lastErrno = osGetLastError();
36635 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
36636 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
36637 pFile->pMapRegion));
36638 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
36639 "winUnmapfile1", pFile->zPath);
36641 pFile->pMapRegion = 0;
36642 pFile->mmapSize = 0;
36643 pFile->mmapSizeActual = 0;
36645 if( pFile->hMap!=NULL ){
36646 if( !osCloseHandle(pFile->hMap) ){
36647 pFile->lastErrno = osGetLastError();
36648 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
36649 osGetCurrentProcessId(), pFile, pFile->hMap));
36650 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
36651 "winUnmapfile2", pFile->zPath);
36653 pFile->hMap = NULL;
36655 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
36656 osGetCurrentProcessId(), pFile));
36657 return SQLITE_OK;
36661 ** Memory map or remap the file opened by file-descriptor pFd (if the file
36662 ** is already mapped, the existing mapping is replaced by the new). Or, if
36663 ** there already exists a mapping for this file, and there are still
36664 ** outstanding xFetch() references to it, this function is a no-op.
36666 ** If parameter nByte is non-negative, then it is the requested size of
36667 ** the mapping to create. Otherwise, if nByte is less than zero, then the
36668 ** requested size is the size of the file on disk. The actual size of the
36669 ** created mapping is either the requested size or the value configured
36670 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
36672 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
36673 ** recreated as a result of outstanding references) or an SQLite error
36674 ** code otherwise.
36676 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
36677 sqlite3_int64 nMap = nByte;
36678 int rc;
36680 assert( nMap>=0 || pFd->nFetchOut==0 );
36681 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
36682 osGetCurrentProcessId(), pFd, nByte));
36684 if( pFd->nFetchOut>0 ) return SQLITE_OK;
36686 if( nMap<0 ){
36687 rc = winFileSize((sqlite3_file*)pFd, &nMap);
36688 if( rc ){
36689 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
36690 osGetCurrentProcessId(), pFd));
36691 return SQLITE_IOERR_FSTAT;
36694 if( nMap>pFd->mmapSizeMax ){
36695 nMap = pFd->mmapSizeMax;
36697 nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
36699 if( nMap==0 && pFd->mmapSize>0 ){
36700 winUnmapfile(pFd);
36702 if( nMap!=pFd->mmapSize ){
36703 void *pNew = 0;
36704 DWORD protect = PAGE_READONLY;
36705 DWORD flags = FILE_MAP_READ;
36707 winUnmapfile(pFd);
36708 #if !SQLITE_MMAP_READ_ONLY
36709 if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
36710 protect = PAGE_READWRITE;
36711 flags |= FILE_MAP_WRITE;
36713 #endif
36714 #if SQLITE_OS_WINRT
36715 pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
36716 #elif defined(SQLITE_WIN32_HAS_WIDE)
36717 pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
36718 (DWORD)((nMap>>32) & 0xffffffff),
36719 (DWORD)(nMap & 0xffffffff), NULL);
36720 #elif defined(SQLITE_WIN32_HAS_ANSI)
36721 pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
36722 (DWORD)((nMap>>32) & 0xffffffff),
36723 (DWORD)(nMap & 0xffffffff), NULL);
36724 #endif
36725 if( pFd->hMap==NULL ){
36726 pFd->lastErrno = osGetLastError();
36727 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
36728 "winMapfile1", pFd->zPath);
36729 /* Log the error, but continue normal operation using xRead/xWrite */
36730 OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
36731 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
36732 return SQLITE_OK;
36734 assert( (nMap % winSysInfo.dwPageSize)==0 );
36735 assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
36736 #if SQLITE_OS_WINRT
36737 pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
36738 #else
36739 pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
36740 #endif
36741 if( pNew==NULL ){
36742 osCloseHandle(pFd->hMap);
36743 pFd->hMap = NULL;
36744 pFd->lastErrno = osGetLastError();
36745 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
36746 "winMapfile2", pFd->zPath);
36747 /* Log the error, but continue normal operation using xRead/xWrite */
36748 OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
36749 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
36750 return SQLITE_OK;
36752 pFd->pMapRegion = pNew;
36753 pFd->mmapSize = nMap;
36754 pFd->mmapSizeActual = nMap;
36757 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
36758 osGetCurrentProcessId(), pFd));
36759 return SQLITE_OK;
36761 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
36764 ** If possible, return a pointer to a mapping of file fd starting at offset
36765 ** iOff. The mapping must be valid for at least nAmt bytes.
36767 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
36768 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
36769 ** Finally, if an error does occur, return an SQLite error code. The final
36770 ** value of *pp is undefined in this case.
36772 ** If this function does return a pointer, the caller must eventually
36773 ** release the reference by calling winUnfetch().
36775 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
36776 #if SQLITE_MAX_MMAP_SIZE>0
36777 winFile *pFd = (winFile*)fd; /* The underlying database file */
36778 #endif
36779 *pp = 0;
36781 OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
36782 osGetCurrentProcessId(), fd, iOff, nAmt, pp));
36784 #if SQLITE_MAX_MMAP_SIZE>0
36785 if( pFd->mmapSizeMax>0 ){
36786 if( pFd->pMapRegion==0 ){
36787 int rc = winMapfile(pFd, -1);
36788 if( rc!=SQLITE_OK ){
36789 OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
36790 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
36791 return rc;
36794 if( pFd->mmapSize >= iOff+nAmt ){
36795 *pp = &((u8 *)pFd->pMapRegion)[iOff];
36796 pFd->nFetchOut++;
36799 #endif
36801 OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
36802 osGetCurrentProcessId(), fd, pp, *pp));
36803 return SQLITE_OK;
36807 ** If the third argument is non-NULL, then this function releases a
36808 ** reference obtained by an earlier call to winFetch(). The second
36809 ** argument passed to this function must be the same as the corresponding
36810 ** argument that was passed to the winFetch() invocation.
36812 ** Or, if the third argument is NULL, then this function is being called
36813 ** to inform the VFS layer that, according to POSIX, any existing mapping
36814 ** may now be invalid and should be unmapped.
36816 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
36817 #if SQLITE_MAX_MMAP_SIZE>0
36818 winFile *pFd = (winFile*)fd; /* The underlying database file */
36820 /* If p==0 (unmap the entire file) then there must be no outstanding
36821 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
36822 ** then there must be at least one outstanding. */
36823 assert( (p==0)==(pFd->nFetchOut==0) );
36825 /* If p!=0, it must match the iOff value. */
36826 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
36828 OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
36829 osGetCurrentProcessId(), pFd, iOff, p));
36831 if( p ){
36832 pFd->nFetchOut--;
36833 }else{
36834 /* FIXME: If Windows truly always prevents truncating or deleting a
36835 ** file while a mapping is held, then the following winUnmapfile() call
36836 ** is unnecessary can be omitted - potentially improving
36837 ** performance. */
36838 winUnmapfile(pFd);
36841 assert( pFd->nFetchOut>=0 );
36842 #endif
36844 OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
36845 osGetCurrentProcessId(), fd));
36846 return SQLITE_OK;
36850 ** Here ends the implementation of all sqlite3_file methods.
36852 ********************** End sqlite3_file Methods *******************************
36853 ******************************************************************************/
36856 ** This vector defines all the methods that can operate on an
36857 ** sqlite3_file for win32.
36859 static const sqlite3_io_methods winIoMethod = {
36860 3, /* iVersion */
36861 winClose, /* xClose */
36862 winRead, /* xRead */
36863 winWrite, /* xWrite */
36864 winTruncate, /* xTruncate */
36865 winSync, /* xSync */
36866 winFileSize, /* xFileSize */
36867 winLock, /* xLock */
36868 winUnlock, /* xUnlock */
36869 winCheckReservedLock, /* xCheckReservedLock */
36870 winFileControl, /* xFileControl */
36871 winSectorSize, /* xSectorSize */
36872 winDeviceCharacteristics, /* xDeviceCharacteristics */
36873 winShmMap, /* xShmMap */
36874 winShmLock, /* xShmLock */
36875 winShmBarrier, /* xShmBarrier */
36876 winShmUnmap, /* xShmUnmap */
36877 winFetch, /* xFetch */
36878 winUnfetch /* xUnfetch */
36881 /****************************************************************************
36882 **************************** sqlite3_vfs methods ****************************
36884 ** This division contains the implementation of methods on the
36885 ** sqlite3_vfs object.
36888 #if defined(__CYGWIN__)
36890 ** Convert a filename from whatever the underlying operating system
36891 ** supports for filenames into UTF-8. Space to hold the result is
36892 ** obtained from malloc and must be freed by the calling function.
36894 static char *winConvertToUtf8Filename(const void *zFilename){
36895 char *zConverted = 0;
36896 if( osIsNT() ){
36897 zConverted = winUnicodeToUtf8(zFilename);
36899 #ifdef SQLITE_WIN32_HAS_ANSI
36900 else{
36901 zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
36903 #endif
36904 /* caller will handle out of memory */
36905 return zConverted;
36907 #endif
36910 ** Convert a UTF-8 filename into whatever form the underlying
36911 ** operating system wants filenames in. Space to hold the result
36912 ** is obtained from malloc and must be freed by the calling
36913 ** function.
36915 static void *winConvertFromUtf8Filename(const char *zFilename){
36916 void *zConverted = 0;
36917 if( osIsNT() ){
36918 zConverted = winUtf8ToUnicode(zFilename);
36920 #ifdef SQLITE_WIN32_HAS_ANSI
36921 else{
36922 zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
36924 #endif
36925 /* caller will handle out of memory */
36926 return zConverted;
36930 ** This function returns non-zero if the specified UTF-8 string buffer
36931 ** ends with a directory separator character or one was successfully
36932 ** added to it.
36934 static int winMakeEndInDirSep(int nBuf, char *zBuf){
36935 if( zBuf ){
36936 int nLen = sqlite3Strlen30(zBuf);
36937 if( nLen>0 ){
36938 if( winIsDirSep(zBuf[nLen-1]) ){
36939 return 1;
36940 }else if( nLen+1<nBuf ){
36941 zBuf[nLen] = winGetDirSep();
36942 zBuf[nLen+1] = '\0';
36943 return 1;
36947 return 0;
36951 ** Create a temporary file name and store the resulting pointer into pzBuf.
36952 ** The pointer returned in pzBuf must be freed via sqlite3_free().
36954 static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
36955 static char zChars[] =
36956 "abcdefghijklmnopqrstuvwxyz"
36957 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
36958 "0123456789";
36959 size_t i, j;
36960 int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
36961 int nMax, nBuf, nDir, nLen;
36962 char *zBuf;
36964 /* It's odd to simulate an io-error here, but really this is just
36965 ** using the io-error infrastructure to test that SQLite handles this
36966 ** function failing.
36968 SimulateIOError( return SQLITE_IOERR );
36970 /* Allocate a temporary buffer to store the fully qualified file
36971 ** name for the temporary file. If this fails, we cannot continue.
36973 nMax = pVfs->mxPathname; nBuf = nMax + 2;
36974 zBuf = sqlite3MallocZero( nBuf );
36975 if( !zBuf ){
36976 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
36977 return SQLITE_IOERR_NOMEM;
36980 /* Figure out the effective temporary directory. First, check if one
36981 ** has been explicitly set by the application; otherwise, use the one
36982 ** configured by the operating system.
36984 nDir = nMax - (nPre + 15);
36985 assert( nDir>0 );
36986 if( sqlite3_temp_directory ){
36987 int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
36988 if( nDirLen>0 ){
36989 if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
36990 nDirLen++;
36992 if( nDirLen>nDir ){
36993 sqlite3_free(zBuf);
36994 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
36995 return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
36997 sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
37000 #if defined(__CYGWIN__)
37001 else{
37002 static const char *azDirs[] = {
37003 0, /* getenv("SQLITE_TMPDIR") */
37004 0, /* getenv("TMPDIR") */
37005 0, /* getenv("TMP") */
37006 0, /* getenv("TEMP") */
37007 0, /* getenv("USERPROFILE") */
37008 "/var/tmp",
37009 "/usr/tmp",
37010 "/tmp",
37011 ".",
37012 0 /* List terminator */
37014 unsigned int i;
37015 const char *zDir = 0;
37017 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
37018 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
37019 if( !azDirs[2] ) azDirs[2] = getenv("TMP");
37020 if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
37021 if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
37022 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
37023 void *zConverted;
37024 if( zDir==0 ) continue;
37025 /* If the path starts with a drive letter followed by the colon
37026 ** character, assume it is already a native Win32 path; otherwise,
37027 ** it must be converted to a native Win32 path via the Cygwin API
37028 ** prior to using it.
37030 if( winIsDriveLetterAndColon(zDir) ){
37031 zConverted = winConvertFromUtf8Filename(zDir);
37032 if( !zConverted ){
37033 sqlite3_free(zBuf);
37034 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37035 return SQLITE_IOERR_NOMEM;
37037 if( winIsDir(zConverted) ){
37038 sqlite3_snprintf(nMax, zBuf, "%s", zDir);
37039 sqlite3_free(zConverted);
37040 break;
37042 sqlite3_free(zConverted);
37043 }else{
37044 zConverted = sqlite3MallocZero( nMax+1 );
37045 if( !zConverted ){
37046 sqlite3_free(zBuf);
37047 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37048 return SQLITE_IOERR_NOMEM;
37050 if( cygwin_conv_path(
37051 osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
37052 zConverted, nMax+1)<0 ){
37053 sqlite3_free(zConverted);
37054 sqlite3_free(zBuf);
37055 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
37056 return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
37057 "winGetTempname2", zDir);
37059 if( winIsDir(zConverted) ){
37060 /* At this point, we know the candidate directory exists and should
37061 ** be used. However, we may need to convert the string containing
37062 ** its name into UTF-8 (i.e. if it is UTF-16 right now).
37064 char *zUtf8 = winConvertToUtf8Filename(zConverted);
37065 if( !zUtf8 ){
37066 sqlite3_free(zConverted);
37067 sqlite3_free(zBuf);
37068 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37069 return SQLITE_IOERR_NOMEM;
37071 sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
37072 sqlite3_free(zUtf8);
37073 sqlite3_free(zConverted);
37074 break;
37076 sqlite3_free(zConverted);
37080 #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
37081 else if( osIsNT() ){
37082 char *zMulti;
37083 LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
37084 if( !zWidePath ){
37085 sqlite3_free(zBuf);
37086 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37087 return SQLITE_IOERR_NOMEM;
37089 if( osGetTempPathW(nMax, zWidePath)==0 ){
37090 sqlite3_free(zWidePath);
37091 sqlite3_free(zBuf);
37092 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
37093 return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
37094 "winGetTempname2", 0);
37096 zMulti = winUnicodeToUtf8(zWidePath);
37097 if( zMulti ){
37098 sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
37099 sqlite3_free(zMulti);
37100 sqlite3_free(zWidePath);
37101 }else{
37102 sqlite3_free(zWidePath);
37103 sqlite3_free(zBuf);
37104 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37105 return SQLITE_IOERR_NOMEM;
37108 #ifdef SQLITE_WIN32_HAS_ANSI
37109 else{
37110 char *zUtf8;
37111 char *zMbcsPath = sqlite3MallocZero( nMax );
37112 if( !zMbcsPath ){
37113 sqlite3_free(zBuf);
37114 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37115 return SQLITE_IOERR_NOMEM;
37117 if( osGetTempPathA(nMax, zMbcsPath)==0 ){
37118 sqlite3_free(zBuf);
37119 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
37120 return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
37121 "winGetTempname3", 0);
37123 zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
37124 if( zUtf8 ){
37125 sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
37126 sqlite3_free(zUtf8);
37127 }else{
37128 sqlite3_free(zBuf);
37129 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37130 return SQLITE_IOERR_NOMEM;
37133 #endif /* SQLITE_WIN32_HAS_ANSI */
37134 #endif /* !SQLITE_OS_WINRT */
37137 ** Check to make sure the temporary directory ends with an appropriate
37138 ** separator. If it does not and there is not enough space left to add
37139 ** one, fail.
37141 if( !winMakeEndInDirSep(nDir+1, zBuf) ){
37142 sqlite3_free(zBuf);
37143 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
37144 return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
37148 ** Check that the output buffer is large enough for the temporary file
37149 ** name in the following format:
37151 ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
37153 ** If not, return SQLITE_ERROR. The number 17 is used here in order to
37154 ** account for the space used by the 15 character random suffix and the
37155 ** two trailing NUL characters. The final directory separator character
37156 ** has already added if it was not already present.
37158 nLen = sqlite3Strlen30(zBuf);
37159 if( (nLen + nPre + 17) > nBuf ){
37160 sqlite3_free(zBuf);
37161 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
37162 return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
37165 sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
37167 j = sqlite3Strlen30(zBuf);
37168 sqlite3_randomness(15, &zBuf[j]);
37169 for(i=0; i<15; i++, j++){
37170 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
37172 zBuf[j] = 0;
37173 zBuf[j+1] = 0;
37174 *pzBuf = zBuf;
37176 OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
37177 return SQLITE_OK;
37181 ** Return TRUE if the named file is really a directory. Return false if
37182 ** it is something other than a directory, or if there is any kind of memory
37183 ** allocation failure.
37185 static int winIsDir(const void *zConverted){
37186 DWORD attr;
37187 int rc = 0;
37188 DWORD lastErrno;
37190 if( osIsNT() ){
37191 int cnt = 0;
37192 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
37193 memset(&sAttrData, 0, sizeof(sAttrData));
37194 while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
37195 GetFileExInfoStandard,
37196 &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
37197 if( !rc ){
37198 return 0; /* Invalid name? */
37200 attr = sAttrData.dwFileAttributes;
37201 #if SQLITE_OS_WINCE==0
37202 }else{
37203 attr = osGetFileAttributesA((char*)zConverted);
37204 #endif
37206 return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
37210 ** Open a file.
37212 static int winOpen(
37213 sqlite3_vfs *pVfs, /* Used to get maximum path name length */
37214 const char *zName, /* Name of the file (UTF-8) */
37215 sqlite3_file *id, /* Write the SQLite file handle here */
37216 int flags, /* Open mode flags */
37217 int *pOutFlags /* Status return flags */
37219 HANDLE h;
37220 DWORD lastErrno = 0;
37221 DWORD dwDesiredAccess;
37222 DWORD dwShareMode;
37223 DWORD dwCreationDisposition;
37224 DWORD dwFlagsAndAttributes = 0;
37225 #if SQLITE_OS_WINCE
37226 int isTemp = 0;
37227 #endif
37228 winFile *pFile = (winFile*)id;
37229 void *zConverted; /* Filename in OS encoding */
37230 const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
37231 int cnt = 0;
37233 /* If argument zPath is a NULL pointer, this function is required to open
37234 ** a temporary file. Use this buffer to store the file name in.
37236 char *zTmpname = 0; /* For temporary filename, if necessary. */
37238 int rc = SQLITE_OK; /* Function Return Code */
37239 #if !defined(NDEBUG) || SQLITE_OS_WINCE
37240 int eType = flags&0xFFFFFF00; /* Type of file to open */
37241 #endif
37243 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
37244 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
37245 int isCreate = (flags & SQLITE_OPEN_CREATE);
37246 int isReadonly = (flags & SQLITE_OPEN_READONLY);
37247 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
37249 #ifndef NDEBUG
37250 int isOpenJournal = (isCreate && (
37251 eType==SQLITE_OPEN_MASTER_JOURNAL
37252 || eType==SQLITE_OPEN_MAIN_JOURNAL
37253 || eType==SQLITE_OPEN_WAL
37255 #endif
37257 OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
37258 zUtf8Name, id, flags, pOutFlags));
37260 /* Check the following statements are true:
37262 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
37263 ** (b) if CREATE is set, then READWRITE must also be set, and
37264 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
37265 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
37267 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
37268 assert(isCreate==0 || isReadWrite);
37269 assert(isExclusive==0 || isCreate);
37270 assert(isDelete==0 || isCreate);
37272 /* The main DB, main journal, WAL file and master journal are never
37273 ** automatically deleted. Nor are they ever temporary files. */
37274 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
37275 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
37276 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
37277 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
37279 /* Assert that the upper layer has set one of the "file-type" flags. */
37280 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
37281 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
37282 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
37283 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
37286 assert( pFile!=0 );
37287 memset(pFile, 0, sizeof(winFile));
37288 pFile->h = INVALID_HANDLE_VALUE;
37290 #if SQLITE_OS_WINRT
37291 if( !zUtf8Name && !sqlite3_temp_directory ){
37292 sqlite3_log(SQLITE_ERROR,
37293 "sqlite3_temp_directory variable should be set for WinRT");
37295 #endif
37297 /* If the second argument to this function is NULL, generate a
37298 ** temporary file name to use
37300 if( !zUtf8Name ){
37301 assert( isDelete && !isOpenJournal );
37302 rc = winGetTempname(pVfs, &zTmpname);
37303 if( rc!=SQLITE_OK ){
37304 OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
37305 return rc;
37307 zUtf8Name = zTmpname;
37310 /* Database filenames are double-zero terminated if they are not
37311 ** URIs with parameters. Hence, they can always be passed into
37312 ** sqlite3_uri_parameter().
37314 assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
37315 zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
37317 /* Convert the filename to the system encoding. */
37318 zConverted = winConvertFromUtf8Filename(zUtf8Name);
37319 if( zConverted==0 ){
37320 sqlite3_free(zTmpname);
37321 OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
37322 return SQLITE_IOERR_NOMEM;
37325 if( winIsDir(zConverted) ){
37326 sqlite3_free(zConverted);
37327 sqlite3_free(zTmpname);
37328 OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
37329 return SQLITE_CANTOPEN_ISDIR;
37332 if( isReadWrite ){
37333 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
37334 }else{
37335 dwDesiredAccess = GENERIC_READ;
37338 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
37339 ** created. SQLite doesn't use it to indicate "exclusive access"
37340 ** as it is usually understood.
37342 if( isExclusive ){
37343 /* Creates a new file, only if it does not already exist. */
37344 /* If the file exists, it fails. */
37345 dwCreationDisposition = CREATE_NEW;
37346 }else if( isCreate ){
37347 /* Open existing file, or create if it doesn't exist */
37348 dwCreationDisposition = OPEN_ALWAYS;
37349 }else{
37350 /* Opens a file, only if it exists. */
37351 dwCreationDisposition = OPEN_EXISTING;
37354 dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
37356 if( isDelete ){
37357 #if SQLITE_OS_WINCE
37358 dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
37359 isTemp = 1;
37360 #else
37361 dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
37362 | FILE_ATTRIBUTE_HIDDEN
37363 | FILE_FLAG_DELETE_ON_CLOSE;
37364 #endif
37365 }else{
37366 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
37368 /* Reports from the internet are that performance is always
37369 ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
37370 #if SQLITE_OS_WINCE
37371 dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
37372 #endif
37374 if( osIsNT() ){
37375 #if SQLITE_OS_WINRT
37376 CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
37377 extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
37378 extendedParameters.dwFileAttributes =
37379 dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
37380 extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
37381 extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
37382 extendedParameters.lpSecurityAttributes = NULL;
37383 extendedParameters.hTemplateFile = NULL;
37384 while( (h = osCreateFile2((LPCWSTR)zConverted,
37385 dwDesiredAccess,
37386 dwShareMode,
37387 dwCreationDisposition,
37388 &extendedParameters))==INVALID_HANDLE_VALUE &&
37389 winRetryIoerr(&cnt, &lastErrno) ){
37390 /* Noop */
37392 #else
37393 while( (h = osCreateFileW((LPCWSTR)zConverted,
37394 dwDesiredAccess,
37395 dwShareMode, NULL,
37396 dwCreationDisposition,
37397 dwFlagsAndAttributes,
37398 NULL))==INVALID_HANDLE_VALUE &&
37399 winRetryIoerr(&cnt, &lastErrno) ){
37400 /* Noop */
37402 #endif
37404 #ifdef SQLITE_WIN32_HAS_ANSI
37405 else{
37406 while( (h = osCreateFileA((LPCSTR)zConverted,
37407 dwDesiredAccess,
37408 dwShareMode, NULL,
37409 dwCreationDisposition,
37410 dwFlagsAndAttributes,
37411 NULL))==INVALID_HANDLE_VALUE &&
37412 winRetryIoerr(&cnt, &lastErrno) ){
37413 /* Noop */
37416 #endif
37417 winLogIoerr(cnt);
37419 OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
37420 dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
37422 if( h==INVALID_HANDLE_VALUE ){
37423 pFile->lastErrno = lastErrno;
37424 winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
37425 sqlite3_free(zConverted);
37426 sqlite3_free(zTmpname);
37427 if( isReadWrite && !isExclusive ){
37428 return winOpen(pVfs, zName, id,
37429 ((flags|SQLITE_OPEN_READONLY) &
37430 ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
37431 pOutFlags);
37432 }else{
37433 return SQLITE_CANTOPEN_BKPT;
37437 if( pOutFlags ){
37438 if( isReadWrite ){
37439 *pOutFlags = SQLITE_OPEN_READWRITE;
37440 }else{
37441 *pOutFlags = SQLITE_OPEN_READONLY;
37445 OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
37446 "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
37447 *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
37449 #if SQLITE_OS_WINCE
37450 if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
37451 && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
37453 osCloseHandle(h);
37454 sqlite3_free(zConverted);
37455 sqlite3_free(zTmpname);
37456 OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
37457 return rc;
37459 if( isTemp ){
37460 pFile->zDeleteOnClose = zConverted;
37461 }else
37462 #endif
37464 sqlite3_free(zConverted);
37467 sqlite3_free(zTmpname);
37468 pFile->pMethod = &winIoMethod;
37469 pFile->pVfs = pVfs;
37470 pFile->h = h;
37471 if( isReadonly ){
37472 pFile->ctrlFlags |= WINFILE_RDONLY;
37474 if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
37475 pFile->ctrlFlags |= WINFILE_PSOW;
37477 pFile->lastErrno = NO_ERROR;
37478 pFile->zPath = zName;
37479 #if SQLITE_MAX_MMAP_SIZE>0
37480 pFile->hMap = NULL;
37481 pFile->pMapRegion = 0;
37482 pFile->mmapSize = 0;
37483 pFile->mmapSizeActual = 0;
37484 pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
37485 #endif
37487 OpenCounter(+1);
37488 return rc;
37492 ** Delete the named file.
37494 ** Note that Windows does not allow a file to be deleted if some other
37495 ** process has it open. Sometimes a virus scanner or indexing program
37496 ** will open a journal file shortly after it is created in order to do
37497 ** whatever it does. While this other process is holding the
37498 ** file open, we will be unable to delete it. To work around this
37499 ** problem, we delay 100 milliseconds and try to delete again. Up
37500 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
37501 ** up and returning an error.
37503 static int winDelete(
37504 sqlite3_vfs *pVfs, /* Not used on win32 */
37505 const char *zFilename, /* Name of file to delete */
37506 int syncDir /* Not used on win32 */
37508 int cnt = 0;
37509 int rc;
37510 DWORD attr;
37511 DWORD lastErrno = 0;
37512 void *zConverted;
37513 UNUSED_PARAMETER(pVfs);
37514 UNUSED_PARAMETER(syncDir);
37516 SimulateIOError(return SQLITE_IOERR_DELETE);
37517 OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
37519 zConverted = winConvertFromUtf8Filename(zFilename);
37520 if( zConverted==0 ){
37521 OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
37522 return SQLITE_IOERR_NOMEM;
37524 if( osIsNT() ){
37525 do {
37526 #if SQLITE_OS_WINRT
37527 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
37528 memset(&sAttrData, 0, sizeof(sAttrData));
37529 if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
37530 &sAttrData) ){
37531 attr = sAttrData.dwFileAttributes;
37532 }else{
37533 lastErrno = osGetLastError();
37534 if( lastErrno==ERROR_FILE_NOT_FOUND
37535 || lastErrno==ERROR_PATH_NOT_FOUND ){
37536 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
37537 }else{
37538 rc = SQLITE_ERROR;
37540 break;
37542 #else
37543 attr = osGetFileAttributesW(zConverted);
37544 #endif
37545 if ( attr==INVALID_FILE_ATTRIBUTES ){
37546 lastErrno = osGetLastError();
37547 if( lastErrno==ERROR_FILE_NOT_FOUND
37548 || lastErrno==ERROR_PATH_NOT_FOUND ){
37549 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
37550 }else{
37551 rc = SQLITE_ERROR;
37553 break;
37555 if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
37556 rc = SQLITE_ERROR; /* Files only. */
37557 break;
37559 if ( osDeleteFileW(zConverted) ){
37560 rc = SQLITE_OK; /* Deleted OK. */
37561 break;
37563 if ( !winRetryIoerr(&cnt, &lastErrno) ){
37564 rc = SQLITE_ERROR; /* No more retries. */
37565 break;
37567 } while(1);
37569 #ifdef SQLITE_WIN32_HAS_ANSI
37570 else{
37571 do {
37572 attr = osGetFileAttributesA(zConverted);
37573 if ( attr==INVALID_FILE_ATTRIBUTES ){
37574 lastErrno = osGetLastError();
37575 if( lastErrno==ERROR_FILE_NOT_FOUND
37576 || lastErrno==ERROR_PATH_NOT_FOUND ){
37577 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
37578 }else{
37579 rc = SQLITE_ERROR;
37581 break;
37583 if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
37584 rc = SQLITE_ERROR; /* Files only. */
37585 break;
37587 if ( osDeleteFileA(zConverted) ){
37588 rc = SQLITE_OK; /* Deleted OK. */
37589 break;
37591 if ( !winRetryIoerr(&cnt, &lastErrno) ){
37592 rc = SQLITE_ERROR; /* No more retries. */
37593 break;
37595 } while(1);
37597 #endif
37598 if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
37599 rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
37600 }else{
37601 winLogIoerr(cnt);
37603 sqlite3_free(zConverted);
37604 OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
37605 return rc;
37609 ** Check the existence and status of a file.
37611 static int winAccess(
37612 sqlite3_vfs *pVfs, /* Not used on win32 */
37613 const char *zFilename, /* Name of file to check */
37614 int flags, /* Type of test to make on this file */
37615 int *pResOut /* OUT: Result */
37617 DWORD attr;
37618 int rc = 0;
37619 DWORD lastErrno = 0;
37620 void *zConverted;
37621 UNUSED_PARAMETER(pVfs);
37623 SimulateIOError( return SQLITE_IOERR_ACCESS; );
37624 OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
37625 zFilename, flags, pResOut));
37627 zConverted = winConvertFromUtf8Filename(zFilename);
37628 if( zConverted==0 ){
37629 OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
37630 return SQLITE_IOERR_NOMEM;
37632 if( osIsNT() ){
37633 int cnt = 0;
37634 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
37635 memset(&sAttrData, 0, sizeof(sAttrData));
37636 while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
37637 GetFileExInfoStandard,
37638 &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
37639 if( rc ){
37640 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
37641 ** as if it does not exist.
37643 if( flags==SQLITE_ACCESS_EXISTS
37644 && sAttrData.nFileSizeHigh==0
37645 && sAttrData.nFileSizeLow==0 ){
37646 attr = INVALID_FILE_ATTRIBUTES;
37647 }else{
37648 attr = sAttrData.dwFileAttributes;
37650 }else{
37651 winLogIoerr(cnt);
37652 if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
37653 sqlite3_free(zConverted);
37654 return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
37655 zFilename);
37656 }else{
37657 attr = INVALID_FILE_ATTRIBUTES;
37661 #ifdef SQLITE_WIN32_HAS_ANSI
37662 else{
37663 attr = osGetFileAttributesA((char*)zConverted);
37665 #endif
37666 sqlite3_free(zConverted);
37667 switch( flags ){
37668 case SQLITE_ACCESS_READ:
37669 case SQLITE_ACCESS_EXISTS:
37670 rc = attr!=INVALID_FILE_ATTRIBUTES;
37671 break;
37672 case SQLITE_ACCESS_READWRITE:
37673 rc = attr!=INVALID_FILE_ATTRIBUTES &&
37674 (attr & FILE_ATTRIBUTE_READONLY)==0;
37675 break;
37676 default:
37677 assert(!"Invalid flags argument");
37679 *pResOut = rc;
37680 OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
37681 zFilename, pResOut, *pResOut));
37682 return SQLITE_OK;
37686 ** Returns non-zero if the specified path name starts with a drive letter
37687 ** followed by a colon character.
37689 static BOOL winIsDriveLetterAndColon(
37690 const char *zPathname
37692 return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
37696 ** Returns non-zero if the specified path name should be used verbatim. If
37697 ** non-zero is returned from this function, the calling function must simply
37698 ** use the provided path name verbatim -OR- resolve it into a full path name
37699 ** using the GetFullPathName Win32 API function (if available).
37701 static BOOL winIsVerbatimPathname(
37702 const char *zPathname
37705 ** If the path name starts with a forward slash or a backslash, it is either
37706 ** a legal UNC name, a volume relative path, or an absolute path name in the
37707 ** "Unix" format on Windows. There is no easy way to differentiate between
37708 ** the final two cases; therefore, we return the safer return value of TRUE
37709 ** so that callers of this function will simply use it verbatim.
37711 if ( winIsDirSep(zPathname[0]) ){
37712 return TRUE;
37716 ** If the path name starts with a letter and a colon it is either a volume
37717 ** relative path or an absolute path. Callers of this function must not
37718 ** attempt to treat it as a relative path name (i.e. they should simply use
37719 ** it verbatim).
37721 if ( winIsDriveLetterAndColon(zPathname) ){
37722 return TRUE;
37726 ** If we get to this point, the path name should almost certainly be a purely
37727 ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
37729 return FALSE;
37733 ** Turn a relative pathname into a full pathname. Write the full
37734 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
37735 ** bytes in size.
37737 static int winFullPathname(
37738 sqlite3_vfs *pVfs, /* Pointer to vfs object */
37739 const char *zRelative, /* Possibly relative input path */
37740 int nFull, /* Size of output buffer in bytes */
37741 char *zFull /* Output buffer */
37744 #if defined(__CYGWIN__)
37745 SimulateIOError( return SQLITE_ERROR );
37746 UNUSED_PARAMETER(nFull);
37747 assert( nFull>=pVfs->mxPathname );
37748 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
37750 ** NOTE: We are dealing with a relative path name and the data
37751 ** directory has been set. Therefore, use it as the basis
37752 ** for converting the relative path name to an absolute
37753 ** one by prepending the data directory and a slash.
37755 char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
37756 if( !zOut ){
37757 return SQLITE_IOERR_NOMEM;
37759 if( cygwin_conv_path(
37760 (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
37761 CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
37762 sqlite3_free(zOut);
37763 return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
37764 "winFullPathname1", zRelative);
37765 }else{
37766 char *zUtf8 = winConvertToUtf8Filename(zOut);
37767 if( !zUtf8 ){
37768 sqlite3_free(zOut);
37769 return SQLITE_IOERR_NOMEM;
37771 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
37772 sqlite3_data_directory, winGetDirSep(), zUtf8);
37773 sqlite3_free(zUtf8);
37774 sqlite3_free(zOut);
37776 }else{
37777 char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
37778 if( !zOut ){
37779 return SQLITE_IOERR_NOMEM;
37781 if( cygwin_conv_path(
37782 (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
37783 zRelative, zOut, pVfs->mxPathname+1)<0 ){
37784 sqlite3_free(zOut);
37785 return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
37786 "winFullPathname2", zRelative);
37787 }else{
37788 char *zUtf8 = winConvertToUtf8Filename(zOut);
37789 if( !zUtf8 ){
37790 sqlite3_free(zOut);
37791 return SQLITE_IOERR_NOMEM;
37793 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
37794 sqlite3_free(zUtf8);
37795 sqlite3_free(zOut);
37798 return SQLITE_OK;
37799 #endif
37801 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
37802 SimulateIOError( return SQLITE_ERROR );
37803 /* WinCE has no concept of a relative pathname, or so I am told. */
37804 /* WinRT has no way to convert a relative path to an absolute one. */
37805 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
37807 ** NOTE: We are dealing with a relative path name and the data
37808 ** directory has been set. Therefore, use it as the basis
37809 ** for converting the relative path name to an absolute
37810 ** one by prepending the data directory and a backslash.
37812 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
37813 sqlite3_data_directory, winGetDirSep(), zRelative);
37814 }else{
37815 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
37817 return SQLITE_OK;
37818 #endif
37820 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
37821 DWORD nByte;
37822 void *zConverted;
37823 char *zOut;
37825 /* If this path name begins with "/X:", where "X" is any alphabetic
37826 ** character, discard the initial "/" from the pathname.
37828 if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
37829 zRelative++;
37832 /* It's odd to simulate an io-error here, but really this is just
37833 ** using the io-error infrastructure to test that SQLite handles this
37834 ** function failing. This function could fail if, for example, the
37835 ** current working directory has been unlinked.
37837 SimulateIOError( return SQLITE_ERROR );
37838 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
37840 ** NOTE: We are dealing with a relative path name and the data
37841 ** directory has been set. Therefore, use it as the basis
37842 ** for converting the relative path name to an absolute
37843 ** one by prepending the data directory and a backslash.
37845 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
37846 sqlite3_data_directory, winGetDirSep(), zRelative);
37847 return SQLITE_OK;
37849 zConverted = winConvertFromUtf8Filename(zRelative);
37850 if( zConverted==0 ){
37851 return SQLITE_IOERR_NOMEM;
37853 if( osIsNT() ){
37854 LPWSTR zTemp;
37855 nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
37856 if( nByte==0 ){
37857 sqlite3_free(zConverted);
37858 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
37859 "winFullPathname1", zRelative);
37861 nByte += 3;
37862 zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
37863 if( zTemp==0 ){
37864 sqlite3_free(zConverted);
37865 return SQLITE_IOERR_NOMEM;
37867 nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
37868 if( nByte==0 ){
37869 sqlite3_free(zConverted);
37870 sqlite3_free(zTemp);
37871 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
37872 "winFullPathname2", zRelative);
37874 sqlite3_free(zConverted);
37875 zOut = winUnicodeToUtf8(zTemp);
37876 sqlite3_free(zTemp);
37878 #ifdef SQLITE_WIN32_HAS_ANSI
37879 else{
37880 char *zTemp;
37881 nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
37882 if( nByte==0 ){
37883 sqlite3_free(zConverted);
37884 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
37885 "winFullPathname3", zRelative);
37887 nByte += 3;
37888 zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
37889 if( zTemp==0 ){
37890 sqlite3_free(zConverted);
37891 return SQLITE_IOERR_NOMEM;
37893 nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
37894 if( nByte==0 ){
37895 sqlite3_free(zConverted);
37896 sqlite3_free(zTemp);
37897 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
37898 "winFullPathname4", zRelative);
37900 sqlite3_free(zConverted);
37901 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
37902 sqlite3_free(zTemp);
37904 #endif
37905 if( zOut ){
37906 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
37907 sqlite3_free(zOut);
37908 return SQLITE_OK;
37909 }else{
37910 return SQLITE_IOERR_NOMEM;
37912 #endif
37915 #ifndef SQLITE_OMIT_LOAD_EXTENSION
37917 ** Interfaces for opening a shared library, finding entry points
37918 ** within the shared library, and closing the shared library.
37920 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
37921 HANDLE h;
37922 #if defined(__CYGWIN__)
37923 int nFull = pVfs->mxPathname+1;
37924 char *zFull = sqlite3MallocZero( nFull );
37925 void *zConverted = 0;
37926 if( zFull==0 ){
37927 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
37928 return 0;
37930 if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
37931 sqlite3_free(zFull);
37932 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
37933 return 0;
37935 zConverted = winConvertFromUtf8Filename(zFull);
37936 sqlite3_free(zFull);
37937 #else
37938 void *zConverted = winConvertFromUtf8Filename(zFilename);
37939 UNUSED_PARAMETER(pVfs);
37940 #endif
37941 if( zConverted==0 ){
37942 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
37943 return 0;
37945 if( osIsNT() ){
37946 #if SQLITE_OS_WINRT
37947 h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
37948 #else
37949 h = osLoadLibraryW((LPCWSTR)zConverted);
37950 #endif
37952 #ifdef SQLITE_WIN32_HAS_ANSI
37953 else{
37954 h = osLoadLibraryA((char*)zConverted);
37956 #endif
37957 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
37958 sqlite3_free(zConverted);
37959 return (void*)h;
37961 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
37962 UNUSED_PARAMETER(pVfs);
37963 winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
37965 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
37966 FARPROC proc;
37967 UNUSED_PARAMETER(pVfs);
37968 proc = osGetProcAddressA((HANDLE)pH, zSym);
37969 OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
37970 (void*)pH, zSym, (void*)proc));
37971 return (void(*)(void))proc;
37973 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
37974 UNUSED_PARAMETER(pVfs);
37975 osFreeLibrary((HANDLE)pHandle);
37976 OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
37978 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
37979 #define winDlOpen 0
37980 #define winDlError 0
37981 #define winDlSym 0
37982 #define winDlClose 0
37983 #endif
37987 ** Write up to nBuf bytes of randomness into zBuf.
37989 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
37990 int n = 0;
37991 UNUSED_PARAMETER(pVfs);
37992 #if defined(SQLITE_TEST)
37993 n = nBuf;
37994 memset(zBuf, 0, nBuf);
37995 #else
37996 if( sizeof(SYSTEMTIME)<=nBuf-n ){
37997 SYSTEMTIME x;
37998 osGetSystemTime(&x);
37999 memcpy(&zBuf[n], &x, sizeof(x));
38000 n += sizeof(x);
38002 if( sizeof(DWORD)<=nBuf-n ){
38003 DWORD pid = osGetCurrentProcessId();
38004 memcpy(&zBuf[n], &pid, sizeof(pid));
38005 n += sizeof(pid);
38007 #if SQLITE_OS_WINRT
38008 if( sizeof(ULONGLONG)<=nBuf-n ){
38009 ULONGLONG cnt = osGetTickCount64();
38010 memcpy(&zBuf[n], &cnt, sizeof(cnt));
38011 n += sizeof(cnt);
38013 #else
38014 if( sizeof(DWORD)<=nBuf-n ){
38015 DWORD cnt = osGetTickCount();
38016 memcpy(&zBuf[n], &cnt, sizeof(cnt));
38017 n += sizeof(cnt);
38019 #endif
38020 if( sizeof(LARGE_INTEGER)<=nBuf-n ){
38021 LARGE_INTEGER i;
38022 osQueryPerformanceCounter(&i);
38023 memcpy(&zBuf[n], &i, sizeof(i));
38024 n += sizeof(i);
38026 #endif
38027 return n;
38032 ** Sleep for a little while. Return the amount of time slept.
38034 static int winSleep(sqlite3_vfs *pVfs, int microsec){
38035 sqlite3_win32_sleep((microsec+999)/1000);
38036 UNUSED_PARAMETER(pVfs);
38037 return ((microsec+999)/1000)*1000;
38041 ** The following variable, if set to a non-zero value, is interpreted as
38042 ** the number of seconds since 1970 and is used to set the result of
38043 ** sqlite3OsCurrentTime() during testing.
38045 #ifdef SQLITE_TEST
38046 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
38047 #endif
38050 ** Find the current time (in Universal Coordinated Time). Write into *piNow
38051 ** the current time and date as a Julian Day number times 86_400_000. In
38052 ** other words, write into *piNow the number of milliseconds since the Julian
38053 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
38054 ** proleptic Gregorian calendar.
38056 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
38057 ** cannot be found.
38059 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
38060 /* FILETIME structure is a 64-bit value representing the number of
38061 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
38063 FILETIME ft;
38064 static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
38065 #ifdef SQLITE_TEST
38066 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
38067 #endif
38068 /* 2^32 - to avoid use of LL and warnings in gcc */
38069 static const sqlite3_int64 max32BitValue =
38070 (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
38071 (sqlite3_int64)294967296;
38073 #if SQLITE_OS_WINCE
38074 SYSTEMTIME time;
38075 osGetSystemTime(&time);
38076 /* if SystemTimeToFileTime() fails, it returns zero. */
38077 if (!osSystemTimeToFileTime(&time,&ft)){
38078 return SQLITE_ERROR;
38080 #else
38081 osGetSystemTimeAsFileTime( &ft );
38082 #endif
38084 *piNow = winFiletimeEpoch +
38085 ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
38086 (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
38088 #ifdef SQLITE_TEST
38089 if( sqlite3_current_time ){
38090 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
38092 #endif
38093 UNUSED_PARAMETER(pVfs);
38094 return SQLITE_OK;
38098 ** Find the current time (in Universal Coordinated Time). Write the
38099 ** current time and date as a Julian Day number into *prNow and
38100 ** return 0. Return 1 if the time and date cannot be found.
38102 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
38103 int rc;
38104 sqlite3_int64 i;
38105 rc = winCurrentTimeInt64(pVfs, &i);
38106 if( !rc ){
38107 *prNow = i/86400000.0;
38109 return rc;
38113 ** The idea is that this function works like a combination of
38114 ** GetLastError() and FormatMessage() on Windows (or errno and
38115 ** strerror_r() on Unix). After an error is returned by an OS
38116 ** function, SQLite calls this function with zBuf pointing to
38117 ** a buffer of nBuf bytes. The OS layer should populate the
38118 ** buffer with a nul-terminated UTF-8 encoded error message
38119 ** describing the last IO error to have occurred within the calling
38120 ** thread.
38122 ** If the error message is too large for the supplied buffer,
38123 ** it should be truncated. The return value of xGetLastError
38124 ** is zero if the error message fits in the buffer, or non-zero
38125 ** otherwise (if the message was truncated). If non-zero is returned,
38126 ** then it is not necessary to include the nul-terminator character
38127 ** in the output buffer.
38129 ** Not supplying an error message will have no adverse effect
38130 ** on SQLite. It is fine to have an implementation that never
38131 ** returns an error message:
38133 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
38134 ** assert(zBuf[0]=='\0');
38135 ** return 0;
38136 ** }
38138 ** However if an error message is supplied, it will be incorporated
38139 ** by sqlite into the error message available to the user using
38140 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
38142 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
38143 UNUSED_PARAMETER(pVfs);
38144 return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
38148 ** Initialize and deinitialize the operating system interface.
38150 SQLITE_API int sqlite3_os_init(void){
38151 static sqlite3_vfs winVfs = {
38152 3, /* iVersion */
38153 sizeof(winFile), /* szOsFile */
38154 SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
38155 0, /* pNext */
38156 "win32", /* zName */
38157 0, /* pAppData */
38158 winOpen, /* xOpen */
38159 winDelete, /* xDelete */
38160 winAccess, /* xAccess */
38161 winFullPathname, /* xFullPathname */
38162 winDlOpen, /* xDlOpen */
38163 winDlError, /* xDlError */
38164 winDlSym, /* xDlSym */
38165 winDlClose, /* xDlClose */
38166 winRandomness, /* xRandomness */
38167 winSleep, /* xSleep */
38168 winCurrentTime, /* xCurrentTime */
38169 winGetLastError, /* xGetLastError */
38170 winCurrentTimeInt64, /* xCurrentTimeInt64 */
38171 winSetSystemCall, /* xSetSystemCall */
38172 winGetSystemCall, /* xGetSystemCall */
38173 winNextSystemCall, /* xNextSystemCall */
38175 #if defined(SQLITE_WIN32_HAS_WIDE)
38176 static sqlite3_vfs winLongPathVfs = {
38177 3, /* iVersion */
38178 sizeof(winFile), /* szOsFile */
38179 SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
38180 0, /* pNext */
38181 "win32-longpath", /* zName */
38182 0, /* pAppData */
38183 winOpen, /* xOpen */
38184 winDelete, /* xDelete */
38185 winAccess, /* xAccess */
38186 winFullPathname, /* xFullPathname */
38187 winDlOpen, /* xDlOpen */
38188 winDlError, /* xDlError */
38189 winDlSym, /* xDlSym */
38190 winDlClose, /* xDlClose */
38191 winRandomness, /* xRandomness */
38192 winSleep, /* xSleep */
38193 winCurrentTime, /* xCurrentTime */
38194 winGetLastError, /* xGetLastError */
38195 winCurrentTimeInt64, /* xCurrentTimeInt64 */
38196 winSetSystemCall, /* xSetSystemCall */
38197 winGetSystemCall, /* xGetSystemCall */
38198 winNextSystemCall, /* xNextSystemCall */
38200 #endif
38202 /* Double-check that the aSyscall[] array has been constructed
38203 ** correctly. See ticket [bb3a86e890c8e96ab] */
38204 assert( ArraySize(aSyscall)==77 );
38206 /* get memory map allocation granularity */
38207 memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
38208 #if SQLITE_OS_WINRT
38209 osGetNativeSystemInfo(&winSysInfo);
38210 #else
38211 osGetSystemInfo(&winSysInfo);
38212 #endif
38213 assert( winSysInfo.dwAllocationGranularity>0 );
38214 assert( winSysInfo.dwPageSize>0 );
38216 sqlite3_vfs_register(&winVfs, 1);
38218 #if defined(SQLITE_WIN32_HAS_WIDE)
38219 sqlite3_vfs_register(&winLongPathVfs, 0);
38220 #endif
38222 return SQLITE_OK;
38225 SQLITE_API int sqlite3_os_end(void){
38226 #if SQLITE_OS_WINRT
38227 if( sleepObj!=NULL ){
38228 osCloseHandle(sleepObj);
38229 sleepObj = NULL;
38231 #endif
38232 return SQLITE_OK;
38235 CHROMIUM_SQLITE_API
38236 void chromium_sqlite3_initialize_win_sqlite3_file(sqlite3_file* file, HANDLE handle) {
38237 winFile* winSQLite3File = (winFile*)file;
38238 memset(file, 0, sizeof(*file));
38239 winSQLite3File->pMethod = &winIoMethod;
38240 winSQLite3File->h = handle;
38243 #endif /* SQLITE_OS_WIN */
38245 /************** End of os_win.c **********************************************/
38246 /************** Begin file bitvec.c ******************************************/
38248 ** 2008 February 16
38250 ** The author disclaims copyright to this source code. In place of
38251 ** a legal notice, here is a blessing:
38253 ** May you do good and not evil.
38254 ** May you find forgiveness for yourself and forgive others.
38255 ** May you share freely, never taking more than you give.
38257 *************************************************************************
38258 ** This file implements an object that represents a fixed-length
38259 ** bitmap. Bits are numbered starting with 1.
38261 ** A bitmap is used to record which pages of a database file have been
38262 ** journalled during a transaction, or which pages have the "dont-write"
38263 ** property. Usually only a few pages are meet either condition.
38264 ** So the bitmap is usually sparse and has low cardinality.
38265 ** But sometimes (for example when during a DROP of a large table) most
38266 ** or all of the pages in a database can get journalled. In those cases,
38267 ** the bitmap becomes dense with high cardinality. The algorithm needs
38268 ** to handle both cases well.
38270 ** The size of the bitmap is fixed when the object is created.
38272 ** All bits are clear when the bitmap is created. Individual bits
38273 ** may be set or cleared one at a time.
38275 ** Test operations are about 100 times more common that set operations.
38276 ** Clear operations are exceedingly rare. There are usually between
38277 ** 5 and 500 set operations per Bitvec object, though the number of sets can
38278 ** sometimes grow into tens of thousands or larger. The size of the
38279 ** Bitvec object is the number of pages in the database file at the
38280 ** start of a transaction, and is thus usually less than a few thousand,
38281 ** but can be as large as 2 billion for a really big database.
38284 /* Size of the Bitvec structure in bytes. */
38285 #define BITVEC_SZ 512
38287 /* Round the union size down to the nearest pointer boundary, since that's how
38288 ** it will be aligned within the Bitvec struct. */
38289 #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
38291 /* Type of the array "element" for the bitmap representation.
38292 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
38293 ** Setting this to the "natural word" size of your CPU may improve
38294 ** performance. */
38295 #define BITVEC_TELEM u8
38296 /* Size, in bits, of the bitmap element. */
38297 #define BITVEC_SZELEM 8
38298 /* Number of elements in a bitmap array. */
38299 #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
38300 /* Number of bits in the bitmap array. */
38301 #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
38303 /* Number of u32 values in hash table. */
38304 #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
38305 /* Maximum number of entries in hash table before
38306 ** sub-dividing and re-hashing. */
38307 #define BITVEC_MXHASH (BITVEC_NINT/2)
38308 /* Hashing function for the aHash representation.
38309 ** Empirical testing showed that the *37 multiplier
38310 ** (an arbitrary prime)in the hash function provided
38311 ** no fewer collisions than the no-op *1. */
38312 #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
38314 #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
38318 ** A bitmap is an instance of the following structure.
38320 ** This bitmap records the existence of zero or more bits
38321 ** with values between 1 and iSize, inclusive.
38323 ** There are three possible representations of the bitmap.
38324 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
38325 ** bitmap. The least significant bit is bit 1.
38327 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
38328 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
38330 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
38331 ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
38332 ** handles up to iDivisor separate values of i. apSub[0] holds
38333 ** values between 1 and iDivisor. apSub[1] holds values between
38334 ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
38335 ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
38336 ** to hold deal with values between 1 and iDivisor.
38338 struct Bitvec {
38339 u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
38340 u32 nSet; /* Number of bits that are set - only valid for aHash
38341 ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
38342 ** this would be 125. */
38343 u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
38344 /* Should >=0 for apSub element. */
38345 /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
38346 /* For a BITVEC_SZ of 512, this would be 34,359,739. */
38347 union {
38348 BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
38349 u32 aHash[BITVEC_NINT]; /* Hash table representation */
38350 Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
38351 } u;
38355 ** Create a new bitmap object able to handle bits between 0 and iSize,
38356 ** inclusive. Return a pointer to the new object. Return NULL if
38357 ** malloc fails.
38359 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
38360 Bitvec *p;
38361 assert( sizeof(*p)==BITVEC_SZ );
38362 p = sqlite3MallocZero( sizeof(*p) );
38363 if( p ){
38364 p->iSize = iSize;
38366 return p;
38370 ** Check to see if the i-th bit is set. Return true or false.
38371 ** If p is NULL (if the bitmap has not been created) or if
38372 ** i is out of range, then return false.
38374 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
38375 if( p==0 ) return 0;
38376 if( i>p->iSize || i==0 ) return 0;
38377 i--;
38378 while( p->iDivisor ){
38379 u32 bin = i/p->iDivisor;
38380 i = i%p->iDivisor;
38381 p = p->u.apSub[bin];
38382 if (!p) {
38383 return 0;
38386 if( p->iSize<=BITVEC_NBIT ){
38387 return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
38388 } else{
38389 u32 h = BITVEC_HASH(i++);
38390 while( p->u.aHash[h] ){
38391 if( p->u.aHash[h]==i ) return 1;
38392 h = (h+1) % BITVEC_NINT;
38394 return 0;
38399 ** Set the i-th bit. Return 0 on success and an error code if
38400 ** anything goes wrong.
38402 ** This routine might cause sub-bitmaps to be allocated. Failing
38403 ** to get the memory needed to hold the sub-bitmap is the only
38404 ** that can go wrong with an insert, assuming p and i are valid.
38406 ** The calling function must ensure that p is a valid Bitvec object
38407 ** and that the value for "i" is within range of the Bitvec object.
38408 ** Otherwise the behavior is undefined.
38410 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
38411 u32 h;
38412 if( p==0 ) return SQLITE_OK;
38413 assert( i>0 );
38414 assert( i<=p->iSize );
38415 i--;
38416 while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
38417 u32 bin = i/p->iDivisor;
38418 i = i%p->iDivisor;
38419 if( p->u.apSub[bin]==0 ){
38420 p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
38421 if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
38423 p = p->u.apSub[bin];
38425 if( p->iSize<=BITVEC_NBIT ){
38426 p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
38427 return SQLITE_OK;
38429 h = BITVEC_HASH(i++);
38430 /* if there wasn't a hash collision, and this doesn't */
38431 /* completely fill the hash, then just add it without */
38432 /* worring about sub-dividing and re-hashing. */
38433 if( !p->u.aHash[h] ){
38434 if (p->nSet<(BITVEC_NINT-1)) {
38435 goto bitvec_set_end;
38436 } else {
38437 goto bitvec_set_rehash;
38440 /* there was a collision, check to see if it's already */
38441 /* in hash, if not, try to find a spot for it */
38442 do {
38443 if( p->u.aHash[h]==i ) return SQLITE_OK;
38444 h++;
38445 if( h>=BITVEC_NINT ) h = 0;
38446 } while( p->u.aHash[h] );
38447 /* we didn't find it in the hash. h points to the first */
38448 /* available free spot. check to see if this is going to */
38449 /* make our hash too "full". */
38450 bitvec_set_rehash:
38451 if( p->nSet>=BITVEC_MXHASH ){
38452 unsigned int j;
38453 int rc;
38454 u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
38455 if( aiValues==0 ){
38456 return SQLITE_NOMEM;
38457 }else{
38458 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
38459 memset(p->u.apSub, 0, sizeof(p->u.apSub));
38460 p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
38461 rc = sqlite3BitvecSet(p, i);
38462 for(j=0; j<BITVEC_NINT; j++){
38463 if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
38465 sqlite3StackFree(0, aiValues);
38466 return rc;
38469 bitvec_set_end:
38470 p->nSet++;
38471 p->u.aHash[h] = i;
38472 return SQLITE_OK;
38476 ** Clear the i-th bit.
38478 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
38479 ** that BitvecClear can use to rebuilt its hash table.
38481 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
38482 if( p==0 ) return;
38483 assert( i>0 );
38484 i--;
38485 while( p->iDivisor ){
38486 u32 bin = i/p->iDivisor;
38487 i = i%p->iDivisor;
38488 p = p->u.apSub[bin];
38489 if (!p) {
38490 return;
38493 if( p->iSize<=BITVEC_NBIT ){
38494 p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
38495 }else{
38496 unsigned int j;
38497 u32 *aiValues = pBuf;
38498 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
38499 memset(p->u.aHash, 0, sizeof(p->u.aHash));
38500 p->nSet = 0;
38501 for(j=0; j<BITVEC_NINT; j++){
38502 if( aiValues[j] && aiValues[j]!=(i+1) ){
38503 u32 h = BITVEC_HASH(aiValues[j]-1);
38504 p->nSet++;
38505 while( p->u.aHash[h] ){
38506 h++;
38507 if( h>=BITVEC_NINT ) h = 0;
38509 p->u.aHash[h] = aiValues[j];
38516 ** Destroy a bitmap object. Reclaim all memory used.
38518 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
38519 if( p==0 ) return;
38520 if( p->iDivisor ){
38521 unsigned int i;
38522 for(i=0; i<BITVEC_NPTR; i++){
38523 sqlite3BitvecDestroy(p->u.apSub[i]);
38526 sqlite3_free(p);
38530 ** Return the value of the iSize parameter specified when Bitvec *p
38531 ** was created.
38533 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
38534 return p->iSize;
38537 #ifndef SQLITE_OMIT_BUILTIN_TEST
38539 ** Let V[] be an array of unsigned characters sufficient to hold
38540 ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
38541 ** Then the following macros can be used to set, clear, or test
38542 ** individual bits within V.
38544 #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
38545 #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
38546 #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
38549 ** This routine runs an extensive test of the Bitvec code.
38551 ** The input is an array of integers that acts as a program
38552 ** to test the Bitvec. The integers are opcodes followed
38553 ** by 0, 1, or 3 operands, depending on the opcode. Another
38554 ** opcode follows immediately after the last operand.
38556 ** There are 6 opcodes numbered from 0 through 5. 0 is the
38557 ** "halt" opcode and causes the test to end.
38559 ** 0 Halt and return the number of errors
38560 ** 1 N S X Set N bits beginning with S and incrementing by X
38561 ** 2 N S X Clear N bits beginning with S and incrementing by X
38562 ** 3 N Set N randomly chosen bits
38563 ** 4 N Clear N randomly chosen bits
38564 ** 5 N S X Set N bits from S increment X in array only, not in bitvec
38566 ** The opcodes 1 through 4 perform set and clear operations are performed
38567 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
38568 ** Opcode 5 works on the linear array only, not on the Bitvec.
38569 ** Opcode 5 is used to deliberately induce a fault in order to
38570 ** confirm that error detection works.
38572 ** At the conclusion of the test the linear array is compared
38573 ** against the Bitvec object. If there are any differences,
38574 ** an error is returned. If they are the same, zero is returned.
38576 ** If a memory allocation error occurs, return -1.
38578 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
38579 Bitvec *pBitvec = 0;
38580 unsigned char *pV = 0;
38581 int rc = -1;
38582 int i, nx, pc, op;
38583 void *pTmpSpace;
38585 /* Allocate the Bitvec to be tested and a linear array of
38586 ** bits to act as the reference */
38587 pBitvec = sqlite3BitvecCreate( sz );
38588 pV = sqlite3MallocZero( (sz+7)/8 + 1 );
38589 pTmpSpace = sqlite3_malloc(BITVEC_SZ);
38590 if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
38592 /* NULL pBitvec tests */
38593 sqlite3BitvecSet(0, 1);
38594 sqlite3BitvecClear(0, 1, pTmpSpace);
38596 /* Run the program */
38597 pc = 0;
38598 while( (op = aOp[pc])!=0 ){
38599 switch( op ){
38600 case 1:
38601 case 2:
38602 case 5: {
38603 nx = 4;
38604 i = aOp[pc+2] - 1;
38605 aOp[pc+2] += aOp[pc+3];
38606 break;
38608 case 3:
38609 case 4:
38610 default: {
38611 nx = 2;
38612 sqlite3_randomness(sizeof(i), &i);
38613 break;
38616 if( (--aOp[pc+1]) > 0 ) nx = 0;
38617 pc += nx;
38618 i = (i & 0x7fffffff)%sz;
38619 if( (op & 1)!=0 ){
38620 SETBIT(pV, (i+1));
38621 if( op!=5 ){
38622 if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
38624 }else{
38625 CLEARBIT(pV, (i+1));
38626 sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
38630 /* Test to make sure the linear array exactly matches the
38631 ** Bitvec object. Start with the assumption that they do
38632 ** match (rc==0). Change rc to non-zero if a discrepancy
38633 ** is found.
38635 rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
38636 + sqlite3BitvecTest(pBitvec, 0)
38637 + (sqlite3BitvecSize(pBitvec) - sz);
38638 for(i=1; i<=sz; i++){
38639 if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
38640 rc = i;
38641 break;
38645 /* Free allocated structure */
38646 bitvec_end:
38647 sqlite3_free(pTmpSpace);
38648 sqlite3_free(pV);
38649 sqlite3BitvecDestroy(pBitvec);
38650 return rc;
38652 #endif /* SQLITE_OMIT_BUILTIN_TEST */
38654 /************** End of bitvec.c **********************************************/
38655 /************** Begin file pcache.c ******************************************/
38657 ** 2008 August 05
38659 ** The author disclaims copyright to this source code. In place of
38660 ** a legal notice, here is a blessing:
38662 ** May you do good and not evil.
38663 ** May you find forgiveness for yourself and forgive others.
38664 ** May you share freely, never taking more than you give.
38666 *************************************************************************
38667 ** This file implements that page cache.
38671 ** A complete page cache is an instance of this structure.
38673 struct PCache {
38674 PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
38675 PgHdr *pSynced; /* Last synced page in dirty page list */
38676 int nRef; /* Number of referenced pages */
38677 int szCache; /* Configured cache size */
38678 int szPage; /* Size of every page in this cache */
38679 int szExtra; /* Size of extra space for each page */
38680 u8 bPurgeable; /* True if pages are on backing store */
38681 u8 eCreate; /* eCreate value for for xFetch() */
38682 int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
38683 void *pStress; /* Argument to xStress */
38684 sqlite3_pcache *pCache; /* Pluggable cache module */
38685 PgHdr *pPage1; /* Reference to page 1 */
38689 ** Some of the assert() macros in this code are too expensive to run
38690 ** even during normal debugging. Use them only rarely on long-running
38691 ** tests. Enable the expensive asserts using the
38692 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
38694 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
38695 # define expensive_assert(X) assert(X)
38696 #else
38697 # define expensive_assert(X)
38698 #endif
38700 /********************************** Linked List Management ********************/
38702 /* Allowed values for second argument to pcacheManageDirtyList() */
38703 #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
38704 #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
38705 #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
38708 ** Manage pPage's participation on the dirty list. Bits of the addRemove
38709 ** argument determines what operation to do. The 0x01 bit means first
38710 ** remove pPage from the dirty list. The 0x02 means add pPage back to
38711 ** the dirty list. Doing both moves pPage to the front of the dirty list.
38713 static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
38714 PCache *p = pPage->pCache;
38716 if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
38717 assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
38718 assert( pPage->pDirtyPrev || pPage==p->pDirty );
38720 /* Update the PCache1.pSynced variable if necessary. */
38721 if( p->pSynced==pPage ){
38722 PgHdr *pSynced = pPage->pDirtyPrev;
38723 while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
38724 pSynced = pSynced->pDirtyPrev;
38726 p->pSynced = pSynced;
38729 if( pPage->pDirtyNext ){
38730 pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
38731 }else{
38732 assert( pPage==p->pDirtyTail );
38733 p->pDirtyTail = pPage->pDirtyPrev;
38735 if( pPage->pDirtyPrev ){
38736 pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
38737 }else{
38738 assert( pPage==p->pDirty );
38739 p->pDirty = pPage->pDirtyNext;
38740 if( p->pDirty==0 && p->bPurgeable ){
38741 assert( p->eCreate==1 );
38742 p->eCreate = 2;
38745 pPage->pDirtyNext = 0;
38746 pPage->pDirtyPrev = 0;
38748 if( addRemove & PCACHE_DIRTYLIST_ADD ){
38749 assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
38751 pPage->pDirtyNext = p->pDirty;
38752 if( pPage->pDirtyNext ){
38753 assert( pPage->pDirtyNext->pDirtyPrev==0 );
38754 pPage->pDirtyNext->pDirtyPrev = pPage;
38755 }else{
38756 p->pDirtyTail = pPage;
38757 if( p->bPurgeable ){
38758 assert( p->eCreate==2 );
38759 p->eCreate = 1;
38762 p->pDirty = pPage;
38763 if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
38764 p->pSynced = pPage;
38770 ** Wrapper around the pluggable caches xUnpin method. If the cache is
38771 ** being used for an in-memory database, this function is a no-op.
38773 static void pcacheUnpin(PgHdr *p){
38774 if( p->pCache->bPurgeable ){
38775 if( p->pgno==1 ){
38776 p->pCache->pPage1 = 0;
38778 sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
38783 ** Compute the number of pages of cache requested.
38785 static int numberOfCachePages(PCache *p){
38786 if( p->szCache>=0 ){
38787 return p->szCache;
38788 }else{
38789 return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
38793 /*************************************************** General Interfaces ******
38795 ** Initialize and shutdown the page cache subsystem. Neither of these
38796 ** functions are threadsafe.
38798 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
38799 if( sqlite3GlobalConfig.pcache2.xInit==0 ){
38800 /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
38801 ** built-in default page cache is used instead of the application defined
38802 ** page cache. */
38803 sqlite3PCacheSetDefault();
38805 return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
38807 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
38808 if( sqlite3GlobalConfig.pcache2.xShutdown ){
38809 /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
38810 sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
38815 ** Return the size in bytes of a PCache object.
38817 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
38820 ** Create a new PCache object. Storage space to hold the object
38821 ** has already been allocated and is passed in as the p pointer.
38822 ** The caller discovers how much space needs to be allocated by
38823 ** calling sqlite3PcacheSize().
38825 SQLITE_PRIVATE int sqlite3PcacheOpen(
38826 int szPage, /* Size of every page */
38827 int szExtra, /* Extra space associated with each page */
38828 int bPurgeable, /* True if pages are on backing store */
38829 int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
38830 void *pStress, /* Argument to xStress */
38831 PCache *p /* Preallocated space for the PCache */
38833 memset(p, 0, sizeof(PCache));
38834 p->szPage = 1;
38835 p->szExtra = szExtra;
38836 p->bPurgeable = bPurgeable;
38837 p->eCreate = 2;
38838 p->xStress = xStress;
38839 p->pStress = pStress;
38840 p->szCache = 100;
38841 return sqlite3PcacheSetPageSize(p, szPage);
38845 ** Change the page size for PCache object. The caller must ensure that there
38846 ** are no outstanding page references when this function is called.
38848 SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
38849 assert( pCache->nRef==0 && pCache->pDirty==0 );
38850 if( pCache->szPage ){
38851 sqlite3_pcache *pNew;
38852 pNew = sqlite3GlobalConfig.pcache2.xCreate(
38853 szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
38855 if( pNew==0 ) return SQLITE_NOMEM;
38856 sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
38857 if( pCache->pCache ){
38858 sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
38860 pCache->pCache = pNew;
38861 pCache->pPage1 = 0;
38862 pCache->szPage = szPage;
38864 return SQLITE_OK;
38868 ** Try to obtain a page from the cache.
38870 ** This routine returns a pointer to an sqlite3_pcache_page object if
38871 ** such an object is already in cache, or if a new one is created.
38872 ** This routine returns a NULL pointer if the object was not in cache
38873 ** and could not be created.
38875 ** The createFlags should be 0 to check for existing pages and should
38876 ** be 3 (not 1, but 3) to try to create a new page.
38878 ** If the createFlag is 0, then NULL is always returned if the page
38879 ** is not already in the cache. If createFlag is 1, then a new page
38880 ** is created only if that can be done without spilling dirty pages
38881 ** and without exceeding the cache size limit.
38883 ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
38884 ** initialize the sqlite3_pcache_page object and convert it into a
38885 ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
38886 ** routines are split this way for performance reasons. When separated
38887 ** they can both (usually) operate without having to push values to
38888 ** the stack on entry and pop them back off on exit, which saves a
38889 ** lot of pushing and popping.
38891 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
38892 PCache *pCache, /* Obtain the page from this cache */
38893 Pgno pgno, /* Page number to obtain */
38894 int createFlag /* If true, create page if it does not exist already */
38896 int eCreate;
38898 assert( pCache!=0 );
38899 assert( pCache->pCache!=0 );
38900 assert( createFlag==3 || createFlag==0 );
38901 assert( pgno>0 );
38903 /* eCreate defines what to do if the page does not exist.
38904 ** 0 Do not allocate a new page. (createFlag==0)
38905 ** 1 Allocate a new page if doing so is inexpensive.
38906 ** (createFlag==1 AND bPurgeable AND pDirty)
38907 ** 2 Allocate a new page even it doing so is difficult.
38908 ** (createFlag==1 AND !(bPurgeable AND pDirty)
38910 eCreate = createFlag & pCache->eCreate;
38911 assert( eCreate==0 || eCreate==1 || eCreate==2 );
38912 assert( createFlag==0 || pCache->eCreate==eCreate );
38913 assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
38914 return sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
38918 ** If the sqlite3PcacheFetch() routine is unable to allocate a new
38919 ** page because new clean pages are available for reuse and the cache
38920 ** size limit has been reached, then this routine can be invoked to
38921 ** try harder to allocate a page. This routine might invoke the stress
38922 ** callback to spill dirty pages to the journal. It will then try to
38923 ** allocate the new page and will only fail to allocate a new page on
38924 ** an OOM error.
38926 ** This routine should be invoked only after sqlite3PcacheFetch() fails.
38928 SQLITE_PRIVATE int sqlite3PcacheFetchStress(
38929 PCache *pCache, /* Obtain the page from this cache */
38930 Pgno pgno, /* Page number to obtain */
38931 sqlite3_pcache_page **ppPage /* Write result here */
38933 PgHdr *pPg;
38934 if( pCache->eCreate==2 ) return 0;
38937 /* Find a dirty page to write-out and recycle. First try to find a
38938 ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
38939 ** cleared), but if that is not possible settle for any other
38940 ** unreferenced dirty page.
38942 for(pPg=pCache->pSynced;
38943 pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
38944 pPg=pPg->pDirtyPrev
38946 pCache->pSynced = pPg;
38947 if( !pPg ){
38948 for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
38950 if( pPg ){
38951 int rc;
38952 #ifdef SQLITE_LOG_CACHE_SPILL
38953 sqlite3_log(SQLITE_FULL,
38954 "spill page %d making room for %d - cache used: %d/%d",
38955 pPg->pgno, pgno,
38956 sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
38957 numberOfCachePages(pCache));
38958 #endif
38959 rc = pCache->xStress(pCache->pStress, pPg);
38960 if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
38961 return rc;
38964 *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
38965 return *ppPage==0 ? SQLITE_NOMEM : SQLITE_OK;
38969 ** This is a helper routine for sqlite3PcacheFetchFinish()
38971 ** In the uncommon case where the page being fetched has not been
38972 ** initialized, this routine is invoked to do the initialization.
38973 ** This routine is broken out into a separate function since it
38974 ** requires extra stack manipulation that can be avoided in the common
38975 ** case.
38977 static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
38978 PCache *pCache, /* Obtain the page from this cache */
38979 Pgno pgno, /* Page number obtained */
38980 sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
38982 PgHdr *pPgHdr;
38983 assert( pPage!=0 );
38984 pPgHdr = (PgHdr*)pPage->pExtra;
38985 assert( pPgHdr->pPage==0 );
38986 memset(pPgHdr, 0, sizeof(PgHdr));
38987 pPgHdr->pPage = pPage;
38988 pPgHdr->pData = pPage->pBuf;
38989 pPgHdr->pExtra = (void *)&pPgHdr[1];
38990 memset(pPgHdr->pExtra, 0, pCache->szExtra);
38991 pPgHdr->pCache = pCache;
38992 pPgHdr->pgno = pgno;
38993 return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
38997 ** This routine converts the sqlite3_pcache_page object returned by
38998 ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
38999 ** must be called after sqlite3PcacheFetch() in order to get a usable
39000 ** result.
39002 SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
39003 PCache *pCache, /* Obtain the page from this cache */
39004 Pgno pgno, /* Page number obtained */
39005 sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
39007 PgHdr *pPgHdr;
39009 if( pPage==0 ) return 0;
39010 pPgHdr = (PgHdr *)pPage->pExtra;
39012 if( !pPgHdr->pPage ){
39013 return pcacheFetchFinishWithInit(pCache, pgno, pPage);
39015 if( 0==pPgHdr->nRef ){
39016 pCache->nRef++;
39018 pPgHdr->nRef++;
39019 if( pgno==1 ){
39020 pCache->pPage1 = pPgHdr;
39022 return pPgHdr;
39026 ** Decrement the reference count on a page. If the page is clean and the
39027 ** reference count drops to 0, then it is made eligible for recycling.
39029 SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
39030 assert( p->nRef>0 );
39031 p->nRef--;
39032 if( p->nRef==0 ){
39033 p->pCache->nRef--;
39034 if( (p->flags&PGHDR_DIRTY)==0 ){
39035 pcacheUnpin(p);
39036 }else if( p->pDirtyPrev!=0 ){
39037 /* Move the page to the head of the dirty list. */
39038 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
39044 ** Increase the reference count of a supplied page by 1.
39046 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
39047 assert(p->nRef>0);
39048 p->nRef++;
39052 ** Drop a page from the cache. There must be exactly one reference to the
39053 ** page. This function deletes that reference, so after it returns the
39054 ** page pointed to by p is invalid.
39056 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
39057 assert( p->nRef==1 );
39058 if( p->flags&PGHDR_DIRTY ){
39059 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
39061 p->pCache->nRef--;
39062 if( p->pgno==1 ){
39063 p->pCache->pPage1 = 0;
39065 sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
39069 ** Make sure the page is marked as dirty. If it isn't dirty already,
39070 ** make it so.
39072 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
39073 p->flags &= ~PGHDR_DONT_WRITE;
39074 assert( p->nRef>0 );
39075 if( 0==(p->flags & PGHDR_DIRTY) ){
39076 p->flags |= PGHDR_DIRTY;
39077 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
39082 ** Make sure the page is marked as clean. If it isn't clean already,
39083 ** make it so.
39085 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
39086 if( (p->flags & PGHDR_DIRTY) ){
39087 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
39088 p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
39089 if( p->nRef==0 ){
39090 pcacheUnpin(p);
39096 ** Make every page in the cache clean.
39098 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
39099 PgHdr *p;
39100 while( (p = pCache->pDirty)!=0 ){
39101 sqlite3PcacheMakeClean(p);
39106 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
39108 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
39109 PgHdr *p;
39110 for(p=pCache->pDirty; p; p=p->pDirtyNext){
39111 p->flags &= ~PGHDR_NEED_SYNC;
39113 pCache->pSynced = pCache->pDirtyTail;
39117 ** Change the page number of page p to newPgno.
39119 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
39120 PCache *pCache = p->pCache;
39121 assert( p->nRef>0 );
39122 assert( newPgno>0 );
39123 sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
39124 p->pgno = newPgno;
39125 if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
39126 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
39131 ** Drop every cache entry whose page number is greater than "pgno". The
39132 ** caller must ensure that there are no outstanding references to any pages
39133 ** other than page 1 with a page number greater than pgno.
39135 ** If there is a reference to page 1 and the pgno parameter passed to this
39136 ** function is 0, then the data area associated with page 1 is zeroed, but
39137 ** the page object is not dropped.
39139 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
39140 if( pCache->pCache ){
39141 PgHdr *p;
39142 PgHdr *pNext;
39143 for(p=pCache->pDirty; p; p=pNext){
39144 pNext = p->pDirtyNext;
39145 /* This routine never gets call with a positive pgno except right
39146 ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
39147 ** it must be that pgno==0.
39149 assert( p->pgno>0 );
39150 if( ALWAYS(p->pgno>pgno) ){
39151 assert( p->flags&PGHDR_DIRTY );
39152 sqlite3PcacheMakeClean(p);
39155 if( pgno==0 && pCache->pPage1 ){
39156 memset(pCache->pPage1->pData, 0, pCache->szPage);
39157 pgno = 1;
39159 sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
39164 ** Close a cache.
39166 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
39167 assert( pCache->pCache!=0 );
39168 sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
39172 ** Discard the contents of the cache.
39174 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
39175 sqlite3PcacheTruncate(pCache, 0);
39179 ** Merge two lists of pages connected by pDirty and in pgno order.
39180 ** Do not both fixing the pDirtyPrev pointers.
39182 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
39183 PgHdr result, *pTail;
39184 pTail = &result;
39185 while( pA && pB ){
39186 if( pA->pgno<pB->pgno ){
39187 pTail->pDirty = pA;
39188 pTail = pA;
39189 pA = pA->pDirty;
39190 }else{
39191 pTail->pDirty = pB;
39192 pTail = pB;
39193 pB = pB->pDirty;
39196 if( pA ){
39197 pTail->pDirty = pA;
39198 }else if( pB ){
39199 pTail->pDirty = pB;
39200 }else{
39201 pTail->pDirty = 0;
39203 return result.pDirty;
39207 ** Sort the list of pages in accending order by pgno. Pages are
39208 ** connected by pDirty pointers. The pDirtyPrev pointers are
39209 ** corrupted by this sort.
39211 ** Since there cannot be more than 2^31 distinct pages in a database,
39212 ** there cannot be more than 31 buckets required by the merge sorter.
39213 ** One extra bucket is added to catch overflow in case something
39214 ** ever changes to make the previous sentence incorrect.
39216 #define N_SORT_BUCKET 32
39217 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
39218 PgHdr *a[N_SORT_BUCKET], *p;
39219 int i;
39220 memset(a, 0, sizeof(a));
39221 while( pIn ){
39222 p = pIn;
39223 pIn = p->pDirty;
39224 p->pDirty = 0;
39225 for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
39226 if( a[i]==0 ){
39227 a[i] = p;
39228 break;
39229 }else{
39230 p = pcacheMergeDirtyList(a[i], p);
39231 a[i] = 0;
39234 if( NEVER(i==N_SORT_BUCKET-1) ){
39235 /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
39236 ** the input list. But that is impossible.
39238 a[i] = pcacheMergeDirtyList(a[i], p);
39241 p = a[0];
39242 for(i=1; i<N_SORT_BUCKET; i++){
39243 p = pcacheMergeDirtyList(p, a[i]);
39245 return p;
39249 ** Return a list of all dirty pages in the cache, sorted by page number.
39251 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
39252 PgHdr *p;
39253 for(p=pCache->pDirty; p; p=p->pDirtyNext){
39254 p->pDirty = p->pDirtyNext;
39256 return pcacheSortDirtyList(pCache->pDirty);
39260 ** Return the total number of referenced pages held by the cache.
39262 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
39263 return pCache->nRef;
39267 ** Return the number of references to the page supplied as an argument.
39269 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
39270 return p->nRef;
39274 ** Return the total number of pages in the cache.
39276 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
39277 assert( pCache->pCache!=0 );
39278 return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
39281 #ifdef SQLITE_TEST
39283 ** Get the suggested cache-size value.
39285 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
39286 return numberOfCachePages(pCache);
39288 #endif
39291 ** Set the suggested cache-size value.
39293 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
39294 assert( pCache->pCache!=0 );
39295 pCache->szCache = mxPage;
39296 sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
39297 numberOfCachePages(pCache));
39301 ** Free up as much memory as possible from the page cache.
39303 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
39304 assert( pCache->pCache!=0 );
39305 sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
39308 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
39310 ** For all dirty pages currently in the cache, invoke the specified
39311 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
39312 ** defined.
39314 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
39315 PgHdr *pDirty;
39316 for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
39317 xIter(pDirty);
39320 #endif
39322 /************** End of pcache.c **********************************************/
39323 /************** Begin file pcache1.c *****************************************/
39325 ** 2008 November 05
39327 ** The author disclaims copyright to this source code. In place of
39328 ** a legal notice, here is a blessing:
39330 ** May you do good and not evil.
39331 ** May you find forgiveness for yourself and forgive others.
39332 ** May you share freely, never taking more than you give.
39334 *************************************************************************
39336 ** This file implements the default page cache implementation (the
39337 ** sqlite3_pcache interface). It also contains part of the implementation
39338 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
39339 ** If the default page cache implementation is overridden, then neither of
39340 ** these two features are available.
39344 typedef struct PCache1 PCache1;
39345 typedef struct PgHdr1 PgHdr1;
39346 typedef struct PgFreeslot PgFreeslot;
39347 typedef struct PGroup PGroup;
39349 /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
39350 ** of one or more PCaches that are able to recycle each other's unpinned
39351 ** pages when they are under memory pressure. A PGroup is an instance of
39352 ** the following object.
39354 ** This page cache implementation works in one of two modes:
39356 ** (1) Every PCache is the sole member of its own PGroup. There is
39357 ** one PGroup per PCache.
39359 ** (2) There is a single global PGroup that all PCaches are a member
39360 ** of.
39362 ** Mode 1 uses more memory (since PCache instances are not able to rob
39363 ** unused pages from other PCaches) but it also operates without a mutex,
39364 ** and is therefore often faster. Mode 2 requires a mutex in order to be
39365 ** threadsafe, but recycles pages more efficiently.
39367 ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
39368 ** PGroup which is the pcache1.grp global variable and its mutex is
39369 ** SQLITE_MUTEX_STATIC_LRU.
39371 struct PGroup {
39372 sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
39373 unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
39374 unsigned int nMinPage; /* Sum of nMin for purgeable caches */
39375 unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
39376 unsigned int nCurrentPage; /* Number of purgeable pages allocated */
39377 PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
39380 /* Each page cache is an instance of the following object. Every
39381 ** open database file (including each in-memory database and each
39382 ** temporary or transient database) has a single page cache which
39383 ** is an instance of this object.
39385 ** Pointers to structures of this type are cast and returned as
39386 ** opaque sqlite3_pcache* handles.
39388 struct PCache1 {
39389 /* Cache configuration parameters. Page size (szPage) and the purgeable
39390 ** flag (bPurgeable) are set when the cache is created. nMax may be
39391 ** modified at any time by a call to the pcache1Cachesize() method.
39392 ** The PGroup mutex must be held when accessing nMax.
39394 PGroup *pGroup; /* PGroup this cache belongs to */
39395 int szPage; /* Size of allocated pages in bytes */
39396 int szExtra; /* Size of extra space in bytes */
39397 int bPurgeable; /* True if cache is purgeable */
39398 unsigned int nMin; /* Minimum number of pages reserved */
39399 unsigned int nMax; /* Configured "cache_size" value */
39400 unsigned int n90pct; /* nMax*9/10 */
39401 unsigned int iMaxKey; /* Largest key seen since xTruncate() */
39403 /* Hash table of all pages. The following variables may only be accessed
39404 ** when the accessor is holding the PGroup mutex.
39406 unsigned int nRecyclable; /* Number of pages in the LRU list */
39407 unsigned int nPage; /* Total number of pages in apHash */
39408 unsigned int nHash; /* Number of slots in apHash[] */
39409 PgHdr1 **apHash; /* Hash table for fast lookup by key */
39413 ** Each cache entry is represented by an instance of the following
39414 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
39415 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
39416 ** in memory.
39418 struct PgHdr1 {
39419 sqlite3_pcache_page page;
39420 unsigned int iKey; /* Key value (page number) */
39421 u8 isPinned; /* Page in use, not on the LRU list */
39422 PgHdr1 *pNext; /* Next in hash table chain */
39423 PCache1 *pCache; /* Cache that currently owns this page */
39424 PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
39425 PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
39429 ** Free slots in the allocator used to divide up the buffer provided using
39430 ** the SQLITE_CONFIG_PAGECACHE mechanism.
39432 struct PgFreeslot {
39433 PgFreeslot *pNext; /* Next free slot */
39437 ** Global data used by this cache.
39439 static SQLITE_WSD struct PCacheGlobal {
39440 PGroup grp; /* The global PGroup for mode (2) */
39442 /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
39443 ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
39444 ** fixed at sqlite3_initialize() time and do not require mutex protection.
39445 ** The nFreeSlot and pFree values do require mutex protection.
39447 int isInit; /* True if initialized */
39448 int szSlot; /* Size of each free slot */
39449 int nSlot; /* The number of pcache slots */
39450 int nReserve; /* Try to keep nFreeSlot above this */
39451 void *pStart, *pEnd; /* Bounds of pagecache malloc range */
39452 /* Above requires no mutex. Use mutex below for variable that follow. */
39453 sqlite3_mutex *mutex; /* Mutex for accessing the following: */
39454 PgFreeslot *pFree; /* Free page blocks */
39455 int nFreeSlot; /* Number of unused pcache slots */
39456 /* The following value requires a mutex to change. We skip the mutex on
39457 ** reading because (1) most platforms read a 32-bit integer atomically and
39458 ** (2) even if an incorrect value is read, no great harm is done since this
39459 ** is really just an optimization. */
39460 int bUnderPressure; /* True if low on PAGECACHE memory */
39461 } pcache1_g;
39464 ** All code in this file should access the global structure above via the
39465 ** alias "pcache1". This ensures that the WSD emulation is used when
39466 ** compiling for systems that do not support real WSD.
39468 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
39471 ** Macros to enter and leave the PCache LRU mutex.
39473 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
39474 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
39476 /******************************************************************************/
39477 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
39480 ** This function is called during initialization if a static buffer is
39481 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
39482 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
39483 ** enough to contain 'n' buffers of 'sz' bytes each.
39485 ** This routine is called from sqlite3_initialize() and so it is guaranteed
39486 ** to be serialized already. There is no need for further mutexing.
39488 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
39489 if( pcache1.isInit ){
39490 PgFreeslot *p;
39491 sz = ROUNDDOWN8(sz);
39492 pcache1.szSlot = sz;
39493 pcache1.nSlot = pcache1.nFreeSlot = n;
39494 pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
39495 pcache1.pStart = pBuf;
39496 pcache1.pFree = 0;
39497 pcache1.bUnderPressure = 0;
39498 while( n-- ){
39499 p = (PgFreeslot*)pBuf;
39500 p->pNext = pcache1.pFree;
39501 pcache1.pFree = p;
39502 pBuf = (void*)&((char*)pBuf)[sz];
39504 pcache1.pEnd = pBuf;
39509 ** Malloc function used within this file to allocate space from the buffer
39510 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
39511 ** such buffer exists or there is no space left in it, this function falls
39512 ** back to sqlite3Malloc().
39514 ** Multiple threads can run this routine at the same time. Global variables
39515 ** in pcache1 need to be protected via mutex.
39517 static void *pcache1Alloc(int nByte){
39518 void *p = 0;
39519 assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
39520 sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
39521 if( nByte<=pcache1.szSlot ){
39522 sqlite3_mutex_enter(pcache1.mutex);
39523 p = (PgHdr1 *)pcache1.pFree;
39524 if( p ){
39525 pcache1.pFree = pcache1.pFree->pNext;
39526 pcache1.nFreeSlot--;
39527 pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
39528 assert( pcache1.nFreeSlot>=0 );
39529 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
39531 sqlite3_mutex_leave(pcache1.mutex);
39533 if( p==0 ){
39534 /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
39535 ** it from sqlite3Malloc instead.
39537 p = sqlite3Malloc(nByte);
39538 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
39539 if( p ){
39540 int sz = sqlite3MallocSize(p);
39541 sqlite3_mutex_enter(pcache1.mutex);
39542 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
39543 sqlite3_mutex_leave(pcache1.mutex);
39545 #endif
39546 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
39548 return p;
39552 ** Free an allocated buffer obtained from pcache1Alloc().
39554 static int pcache1Free(void *p){
39555 int nFreed = 0;
39556 if( p==0 ) return 0;
39557 if( p>=pcache1.pStart && p<pcache1.pEnd ){
39558 PgFreeslot *pSlot;
39559 sqlite3_mutex_enter(pcache1.mutex);
39560 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
39561 pSlot = (PgFreeslot*)p;
39562 pSlot->pNext = pcache1.pFree;
39563 pcache1.pFree = pSlot;
39564 pcache1.nFreeSlot++;
39565 pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
39566 assert( pcache1.nFreeSlot<=pcache1.nSlot );
39567 sqlite3_mutex_leave(pcache1.mutex);
39568 }else{
39569 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
39570 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
39571 nFreed = sqlite3MallocSize(p);
39572 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
39573 sqlite3_mutex_enter(pcache1.mutex);
39574 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
39575 sqlite3_mutex_leave(pcache1.mutex);
39576 #endif
39577 sqlite3_free(p);
39579 return nFreed;
39582 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
39584 ** Return the size of a pcache allocation
39586 static int pcache1MemSize(void *p){
39587 if( p>=pcache1.pStart && p<pcache1.pEnd ){
39588 return pcache1.szSlot;
39589 }else{
39590 int iSize;
39591 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
39592 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
39593 iSize = sqlite3MallocSize(p);
39594 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
39595 return iSize;
39598 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
39601 ** Allocate a new page object initially associated with cache pCache.
39603 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
39604 PgHdr1 *p = 0;
39605 void *pPg;
39607 /* The group mutex must be released before pcache1Alloc() is called. This
39608 ** is because it may call sqlite3_release_memory(), which assumes that
39609 ** this mutex is not held. */
39610 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
39611 pcache1LeaveMutex(pCache->pGroup);
39612 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
39613 pPg = pcache1Alloc(pCache->szPage);
39614 p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
39615 if( !pPg || !p ){
39616 pcache1Free(pPg);
39617 sqlite3_free(p);
39618 pPg = 0;
39620 #else
39621 pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
39622 p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
39623 #endif
39624 pcache1EnterMutex(pCache->pGroup);
39626 if( pPg ){
39627 p->page.pBuf = pPg;
39628 p->page.pExtra = &p[1];
39629 if( pCache->bPurgeable ){
39630 pCache->pGroup->nCurrentPage++;
39632 return p;
39634 return 0;
39638 ** Free a page object allocated by pcache1AllocPage().
39640 ** The pointer is allowed to be NULL, which is prudent. But it turns out
39641 ** that the current implementation happens to never call this routine
39642 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
39644 static void pcache1FreePage(PgHdr1 *p){
39645 if( ALWAYS(p) ){
39646 PCache1 *pCache = p->pCache;
39647 assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
39648 pcache1Free(p->page.pBuf);
39649 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
39650 sqlite3_free(p);
39651 #endif
39652 if( pCache->bPurgeable ){
39653 pCache->pGroup->nCurrentPage--;
39659 ** Malloc function used by SQLite to obtain space from the buffer configured
39660 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
39661 ** exists, this function falls back to sqlite3Malloc().
39663 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
39664 return pcache1Alloc(sz);
39668 ** Free an allocated buffer obtained from sqlite3PageMalloc().
39670 SQLITE_PRIVATE void sqlite3PageFree(void *p){
39671 pcache1Free(p);
39676 ** Return true if it desirable to avoid allocating a new page cache
39677 ** entry.
39679 ** If memory was allocated specifically to the page cache using
39680 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
39681 ** it is desirable to avoid allocating a new page cache entry because
39682 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
39683 ** for all page cache needs and we should not need to spill the
39684 ** allocation onto the heap.
39686 ** Or, the heap is used for all page cache memory but the heap is
39687 ** under memory pressure, then again it is desirable to avoid
39688 ** allocating a new page cache entry in order to avoid stressing
39689 ** the heap even further.
39691 static int pcache1UnderMemoryPressure(PCache1 *pCache){
39692 if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
39693 return pcache1.bUnderPressure;
39694 }else{
39695 return sqlite3HeapNearlyFull();
39699 /******************************************************************************/
39700 /******** General Implementation Functions ************************************/
39703 ** This function is used to resize the hash table used by the cache passed
39704 ** as the first argument.
39706 ** The PCache mutex must be held when this function is called.
39708 static void pcache1ResizeHash(PCache1 *p){
39709 PgHdr1 **apNew;
39710 unsigned int nNew;
39711 unsigned int i;
39713 assert( sqlite3_mutex_held(p->pGroup->mutex) );
39715 nNew = p->nHash*2;
39716 if( nNew<256 ){
39717 nNew = 256;
39720 pcache1LeaveMutex(p->pGroup);
39721 if( p->nHash ){ sqlite3BeginBenignMalloc(); }
39722 apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
39723 if( p->nHash ){ sqlite3EndBenignMalloc(); }
39724 pcache1EnterMutex(p->pGroup);
39725 if( apNew ){
39726 for(i=0; i<p->nHash; i++){
39727 PgHdr1 *pPage;
39728 PgHdr1 *pNext = p->apHash[i];
39729 while( (pPage = pNext)!=0 ){
39730 unsigned int h = pPage->iKey % nNew;
39731 pNext = pPage->pNext;
39732 pPage->pNext = apNew[h];
39733 apNew[h] = pPage;
39736 sqlite3_free(p->apHash);
39737 p->apHash = apNew;
39738 p->nHash = nNew;
39743 ** This function is used internally to remove the page pPage from the
39744 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
39745 ** LRU list, then this function is a no-op.
39747 ** The PGroup mutex must be held when this function is called.
39749 static void pcache1PinPage(PgHdr1 *pPage){
39750 PCache1 *pCache;
39751 PGroup *pGroup;
39753 assert( pPage!=0 );
39754 assert( pPage->isPinned==0 );
39755 pCache = pPage->pCache;
39756 pGroup = pCache->pGroup;
39757 assert( pPage->pLruNext || pPage==pGroup->pLruTail );
39758 assert( pPage->pLruPrev || pPage==pGroup->pLruHead );
39759 assert( sqlite3_mutex_held(pGroup->mutex) );
39760 if( pPage->pLruPrev ){
39761 pPage->pLruPrev->pLruNext = pPage->pLruNext;
39762 }else{
39763 pGroup->pLruHead = pPage->pLruNext;
39765 if( pPage->pLruNext ){
39766 pPage->pLruNext->pLruPrev = pPage->pLruPrev;
39767 }else{
39768 pGroup->pLruTail = pPage->pLruPrev;
39770 pPage->pLruNext = 0;
39771 pPage->pLruPrev = 0;
39772 pPage->isPinned = 1;
39773 pCache->nRecyclable--;
39778 ** Remove the page supplied as an argument from the hash table
39779 ** (PCache1.apHash structure) that it is currently stored in.
39781 ** The PGroup mutex must be held when this function is called.
39783 static void pcache1RemoveFromHash(PgHdr1 *pPage){
39784 unsigned int h;
39785 PCache1 *pCache = pPage->pCache;
39786 PgHdr1 **pp;
39788 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
39789 h = pPage->iKey % pCache->nHash;
39790 for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
39791 *pp = (*pp)->pNext;
39793 pCache->nPage--;
39797 ** If there are currently more than nMaxPage pages allocated, try
39798 ** to recycle pages to reduce the number allocated to nMaxPage.
39800 static void pcache1EnforceMaxPage(PGroup *pGroup){
39801 assert( sqlite3_mutex_held(pGroup->mutex) );
39802 while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
39803 PgHdr1 *p = pGroup->pLruTail;
39804 assert( p->pCache->pGroup==pGroup );
39805 assert( p->isPinned==0 );
39806 pcache1PinPage(p);
39807 pcache1RemoveFromHash(p);
39808 pcache1FreePage(p);
39813 ** Discard all pages from cache pCache with a page number (key value)
39814 ** greater than or equal to iLimit. Any pinned pages that meet this
39815 ** criteria are unpinned before they are discarded.
39817 ** The PCache mutex must be held when this function is called.
39819 static void pcache1TruncateUnsafe(
39820 PCache1 *pCache, /* The cache to truncate */
39821 unsigned int iLimit /* Drop pages with this pgno or larger */
39823 TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
39824 unsigned int h;
39825 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
39826 for(h=0; h<pCache->nHash; h++){
39827 PgHdr1 **pp = &pCache->apHash[h];
39828 PgHdr1 *pPage;
39829 while( (pPage = *pp)!=0 ){
39830 if( pPage->iKey>=iLimit ){
39831 pCache->nPage--;
39832 *pp = pPage->pNext;
39833 if( !pPage->isPinned ) pcache1PinPage(pPage);
39834 pcache1FreePage(pPage);
39835 }else{
39836 pp = &pPage->pNext;
39837 TESTONLY( nPage++; )
39841 assert( pCache->nPage==nPage );
39844 /******************************************************************************/
39845 /******** sqlite3_pcache Methods **********************************************/
39848 ** Implementation of the sqlite3_pcache.xInit method.
39850 static int pcache1Init(void *NotUsed){
39851 UNUSED_PARAMETER(NotUsed);
39852 assert( pcache1.isInit==0 );
39853 memset(&pcache1, 0, sizeof(pcache1));
39854 if( sqlite3GlobalConfig.bCoreMutex ){
39855 pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
39856 pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
39858 pcache1.grp.mxPinned = 10;
39859 pcache1.isInit = 1;
39860 return SQLITE_OK;
39864 ** Implementation of the sqlite3_pcache.xShutdown method.
39865 ** Note that the static mutex allocated in xInit does
39866 ** not need to be freed.
39868 static void pcache1Shutdown(void *NotUsed){
39869 UNUSED_PARAMETER(NotUsed);
39870 assert( pcache1.isInit!=0 );
39871 memset(&pcache1, 0, sizeof(pcache1));
39874 /* forward declaration */
39875 static void pcache1Destroy(sqlite3_pcache *p);
39878 ** Implementation of the sqlite3_pcache.xCreate method.
39880 ** Allocate a new cache.
39882 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
39883 PCache1 *pCache; /* The newly created page cache */
39884 PGroup *pGroup; /* The group the new page cache will belong to */
39885 int sz; /* Bytes of memory required to allocate the new cache */
39888 ** The separateCache variable is true if each PCache has its own private
39889 ** PGroup. In other words, separateCache is true for mode (1) where no
39890 ** mutexing is required.
39892 ** * Always use separate caches (mode-1) if SQLITE_SEPARATE_CACHE_POOLS
39894 ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
39896 ** * Always use a unified cache in single-threaded applications
39898 ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
39899 ** use separate caches (mode-1)
39901 #ifdef SQLITE_SEPARATE_CACHE_POOLS
39902 const int separateCache = 1;
39903 #elif defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
39904 const int separateCache = 0;
39905 #else
39906 int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
39907 #endif
39909 assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
39910 assert( szExtra < 300 );
39912 sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
39913 pCache = (PCache1 *)sqlite3MallocZero(sz);
39914 if( pCache ){
39915 if( separateCache ){
39916 pGroup = (PGroup*)&pCache[1];
39917 pGroup->mxPinned = 10;
39918 }else{
39919 pGroup = &pcache1.grp;
39921 pCache->pGroup = pGroup;
39922 pCache->szPage = szPage;
39923 pCache->szExtra = szExtra;
39924 pCache->bPurgeable = (bPurgeable ? 1 : 0);
39925 pcache1EnterMutex(pGroup);
39926 pcache1ResizeHash(pCache);
39927 if( bPurgeable ){
39928 pCache->nMin = 10;
39929 pGroup->nMinPage += pCache->nMin;
39930 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
39932 pcache1LeaveMutex(pGroup);
39933 if( pCache->nHash==0 ){
39934 pcache1Destroy((sqlite3_pcache*)pCache);
39935 pCache = 0;
39938 return (sqlite3_pcache *)pCache;
39942 ** Implementation of the sqlite3_pcache.xCachesize method.
39944 ** Configure the cache_size limit for a cache.
39946 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
39947 PCache1 *pCache = (PCache1 *)p;
39948 if( pCache->bPurgeable ){
39949 PGroup *pGroup = pCache->pGroup;
39950 pcache1EnterMutex(pGroup);
39951 pGroup->nMaxPage += (nMax - pCache->nMax);
39952 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
39953 pCache->nMax = nMax;
39954 pCache->n90pct = pCache->nMax*9/10;
39955 pcache1EnforceMaxPage(pGroup);
39956 pcache1LeaveMutex(pGroup);
39961 ** Implementation of the sqlite3_pcache.xShrink method.
39963 ** Free up as much memory as possible.
39965 static void pcache1Shrink(sqlite3_pcache *p){
39966 PCache1 *pCache = (PCache1*)p;
39967 if( pCache->bPurgeable ){
39968 PGroup *pGroup = pCache->pGroup;
39969 int savedMaxPage;
39970 pcache1EnterMutex(pGroup);
39971 savedMaxPage = pGroup->nMaxPage;
39972 pGroup->nMaxPage = 0;
39973 pcache1EnforceMaxPage(pGroup);
39974 pGroup->nMaxPage = savedMaxPage;
39975 pcache1LeaveMutex(pGroup);
39980 ** Implementation of the sqlite3_pcache.xPagecount method.
39982 static int pcache1Pagecount(sqlite3_pcache *p){
39983 int n;
39984 PCache1 *pCache = (PCache1*)p;
39985 pcache1EnterMutex(pCache->pGroup);
39986 n = pCache->nPage;
39987 pcache1LeaveMutex(pCache->pGroup);
39988 return n;
39993 ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
39994 ** in the header of the pcache1Fetch() procedure.
39996 ** This steps are broken out into a separate procedure because they are
39997 ** usually not needed, and by avoiding the stack initialization required
39998 ** for these steps, the main pcache1Fetch() procedure can run faster.
40000 static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
40001 PCache1 *pCache,
40002 unsigned int iKey,
40003 int createFlag
40005 unsigned int nPinned;
40006 PGroup *pGroup = pCache->pGroup;
40007 PgHdr1 *pPage = 0;
40009 /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
40010 assert( pCache->nPage >= pCache->nRecyclable );
40011 nPinned = pCache->nPage - pCache->nRecyclable;
40012 assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
40013 assert( pCache->n90pct == pCache->nMax*9/10 );
40014 if( createFlag==1 && (
40015 nPinned>=pGroup->mxPinned
40016 || nPinned>=pCache->n90pct
40017 || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
40019 return 0;
40022 if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
40023 assert( pCache->nHash>0 && pCache->apHash );
40025 /* Step 4. Try to recycle a page. */
40026 if( pCache->bPurgeable && pGroup->pLruTail && (
40027 (pCache->nPage+1>=pCache->nMax)
40028 || pGroup->nCurrentPage>=pGroup->nMaxPage
40029 || pcache1UnderMemoryPressure(pCache)
40031 PCache1 *pOther;
40032 pPage = pGroup->pLruTail;
40033 assert( pPage->isPinned==0 );
40034 pcache1RemoveFromHash(pPage);
40035 pcache1PinPage(pPage);
40036 pOther = pPage->pCache;
40038 /* We want to verify that szPage and szExtra are the same for pOther
40039 ** and pCache. Assert that we can verify this by comparing sums. */
40040 assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
40041 assert( pCache->szExtra<512 );
40042 assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
40043 assert( pOther->szExtra<512 );
40045 if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
40046 pcache1FreePage(pPage);
40047 pPage = 0;
40048 }else{
40049 pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
40053 /* Step 5. If a usable page buffer has still not been found,
40054 ** attempt to allocate a new one.
40056 if( !pPage ){
40057 if( createFlag==1 ) sqlite3BeginBenignMalloc();
40058 pPage = pcache1AllocPage(pCache);
40059 if( createFlag==1 ) sqlite3EndBenignMalloc();
40062 if( pPage ){
40063 unsigned int h = iKey % pCache->nHash;
40064 pCache->nPage++;
40065 pPage->iKey = iKey;
40066 pPage->pNext = pCache->apHash[h];
40067 pPage->pCache = pCache;
40068 pPage->pLruPrev = 0;
40069 pPage->pLruNext = 0;
40070 pPage->isPinned = 1;
40071 *(void **)pPage->page.pExtra = 0;
40072 pCache->apHash[h] = pPage;
40073 if( iKey>pCache->iMaxKey ){
40074 pCache->iMaxKey = iKey;
40077 return pPage;
40081 ** Implementation of the sqlite3_pcache.xFetch method.
40083 ** Fetch a page by key value.
40085 ** Whether or not a new page may be allocated by this function depends on
40086 ** the value of the createFlag argument. 0 means do not allocate a new
40087 ** page. 1 means allocate a new page if space is easily available. 2
40088 ** means to try really hard to allocate a new page.
40090 ** For a non-purgeable cache (a cache used as the storage for an in-memory
40091 ** database) there is really no difference between createFlag 1 and 2. So
40092 ** the calling function (pcache.c) will never have a createFlag of 1 on
40093 ** a non-purgeable cache.
40095 ** There are three different approaches to obtaining space for a page,
40096 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
40098 ** 1. Regardless of the value of createFlag, the cache is searched for a
40099 ** copy of the requested page. If one is found, it is returned.
40101 ** 2. If createFlag==0 and the page is not already in the cache, NULL is
40102 ** returned.
40104 ** 3. If createFlag is 1, and the page is not already in the cache, then
40105 ** return NULL (do not allocate a new page) if any of the following
40106 ** conditions are true:
40108 ** (a) the number of pages pinned by the cache is greater than
40109 ** PCache1.nMax, or
40111 ** (b) the number of pages pinned by the cache is greater than
40112 ** the sum of nMax for all purgeable caches, less the sum of
40113 ** nMin for all other purgeable caches, or
40115 ** 4. If none of the first three conditions apply and the cache is marked
40116 ** as purgeable, and if one of the following is true:
40118 ** (a) The number of pages allocated for the cache is already
40119 ** PCache1.nMax, or
40121 ** (b) The number of pages allocated for all purgeable caches is
40122 ** already equal to or greater than the sum of nMax for all
40123 ** purgeable caches,
40125 ** (c) The system is under memory pressure and wants to avoid
40126 ** unnecessary pages cache entry allocations
40128 ** then attempt to recycle a page from the LRU list. If it is the right
40129 ** size, return the recycled buffer. Otherwise, free the buffer and
40130 ** proceed to step 5.
40132 ** 5. Otherwise, allocate and return a new page buffer.
40134 static sqlite3_pcache_page *pcache1Fetch(
40135 sqlite3_pcache *p,
40136 unsigned int iKey,
40137 int createFlag
40139 PCache1 *pCache = (PCache1 *)p;
40140 PgHdr1 *pPage = 0;
40142 assert( offsetof(PgHdr1,page)==0 );
40143 assert( pCache->bPurgeable || createFlag!=1 );
40144 assert( pCache->bPurgeable || pCache->nMin==0 );
40145 assert( pCache->bPurgeable==0 || pCache->nMin==10 );
40146 assert( pCache->nMin==0 || pCache->bPurgeable );
40147 assert( pCache->nHash>0 );
40148 pcache1EnterMutex(pCache->pGroup);
40150 /* Step 1: Search the hash table for an existing entry. */
40151 pPage = pCache->apHash[iKey % pCache->nHash];
40152 while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
40154 /* Step 2: Abort if no existing page is found and createFlag is 0 */
40155 if( pPage ){
40156 if( !pPage->isPinned ) pcache1PinPage(pPage);
40157 }else if( createFlag ){
40158 /* Steps 3, 4, and 5 implemented by this subroutine */
40159 pPage = pcache1FetchStage2(pCache, iKey, createFlag);
40161 assert( pPage==0 || pCache->iMaxKey>=iKey );
40162 pcache1LeaveMutex(pCache->pGroup);
40163 return (sqlite3_pcache_page*)pPage;
40168 ** Implementation of the sqlite3_pcache.xUnpin method.
40170 ** Mark a page as unpinned (eligible for asynchronous recycling).
40172 static void pcache1Unpin(
40173 sqlite3_pcache *p,
40174 sqlite3_pcache_page *pPg,
40175 int reuseUnlikely
40177 PCache1 *pCache = (PCache1 *)p;
40178 PgHdr1 *pPage = (PgHdr1 *)pPg;
40179 PGroup *pGroup = pCache->pGroup;
40181 assert( pPage->pCache==pCache );
40182 pcache1EnterMutex(pGroup);
40184 /* It is an error to call this function if the page is already
40185 ** part of the PGroup LRU list.
40187 assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
40188 assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
40189 assert( pPage->isPinned==1 );
40191 if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
40192 pcache1RemoveFromHash(pPage);
40193 pcache1FreePage(pPage);
40194 }else{
40195 /* Add the page to the PGroup LRU list. */
40196 if( pGroup->pLruHead ){
40197 pGroup->pLruHead->pLruPrev = pPage;
40198 pPage->pLruNext = pGroup->pLruHead;
40199 pGroup->pLruHead = pPage;
40200 }else{
40201 pGroup->pLruTail = pPage;
40202 pGroup->pLruHead = pPage;
40204 pCache->nRecyclable++;
40205 pPage->isPinned = 0;
40208 pcache1LeaveMutex(pCache->pGroup);
40212 ** Implementation of the sqlite3_pcache.xRekey method.
40214 static void pcache1Rekey(
40215 sqlite3_pcache *p,
40216 sqlite3_pcache_page *pPg,
40217 unsigned int iOld,
40218 unsigned int iNew
40220 PCache1 *pCache = (PCache1 *)p;
40221 PgHdr1 *pPage = (PgHdr1 *)pPg;
40222 PgHdr1 **pp;
40223 unsigned int h;
40224 assert( pPage->iKey==iOld );
40225 assert( pPage->pCache==pCache );
40227 pcache1EnterMutex(pCache->pGroup);
40229 h = iOld%pCache->nHash;
40230 pp = &pCache->apHash[h];
40231 while( (*pp)!=pPage ){
40232 pp = &(*pp)->pNext;
40234 *pp = pPage->pNext;
40236 h = iNew%pCache->nHash;
40237 pPage->iKey = iNew;
40238 pPage->pNext = pCache->apHash[h];
40239 pCache->apHash[h] = pPage;
40240 if( iNew>pCache->iMaxKey ){
40241 pCache->iMaxKey = iNew;
40244 pcache1LeaveMutex(pCache->pGroup);
40248 ** Implementation of the sqlite3_pcache.xTruncate method.
40250 ** Discard all unpinned pages in the cache with a page number equal to
40251 ** or greater than parameter iLimit. Any pinned pages with a page number
40252 ** equal to or greater than iLimit are implicitly unpinned.
40254 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
40255 PCache1 *pCache = (PCache1 *)p;
40256 pcache1EnterMutex(pCache->pGroup);
40257 if( iLimit<=pCache->iMaxKey ){
40258 pcache1TruncateUnsafe(pCache, iLimit);
40259 pCache->iMaxKey = iLimit-1;
40261 pcache1LeaveMutex(pCache->pGroup);
40265 ** Implementation of the sqlite3_pcache.xDestroy method.
40267 ** Destroy a cache allocated using pcache1Create().
40269 static void pcache1Destroy(sqlite3_pcache *p){
40270 PCache1 *pCache = (PCache1 *)p;
40271 PGroup *pGroup = pCache->pGroup;
40272 assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
40273 pcache1EnterMutex(pGroup);
40274 pcache1TruncateUnsafe(pCache, 0);
40275 assert( pGroup->nMaxPage >= pCache->nMax );
40276 pGroup->nMaxPage -= pCache->nMax;
40277 assert( pGroup->nMinPage >= pCache->nMin );
40278 pGroup->nMinPage -= pCache->nMin;
40279 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
40280 pcache1EnforceMaxPage(pGroup);
40281 pcache1LeaveMutex(pGroup);
40282 sqlite3_free(pCache->apHash);
40283 sqlite3_free(pCache);
40287 ** This function is called during initialization (sqlite3_initialize()) to
40288 ** install the default pluggable cache module, assuming the user has not
40289 ** already provided an alternative.
40291 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
40292 static const sqlite3_pcache_methods2 defaultMethods = {
40293 1, /* iVersion */
40294 0, /* pArg */
40295 pcache1Init, /* xInit */
40296 pcache1Shutdown, /* xShutdown */
40297 pcache1Create, /* xCreate */
40298 pcache1Cachesize, /* xCachesize */
40299 pcache1Pagecount, /* xPagecount */
40300 pcache1Fetch, /* xFetch */
40301 pcache1Unpin, /* xUnpin */
40302 pcache1Rekey, /* xRekey */
40303 pcache1Truncate, /* xTruncate */
40304 pcache1Destroy, /* xDestroy */
40305 pcache1Shrink /* xShrink */
40307 sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
40310 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
40312 ** This function is called to free superfluous dynamically allocated memory
40313 ** held by the pager system. Memory in use by any SQLite pager allocated
40314 ** by the current thread may be sqlite3_free()ed.
40316 ** nReq is the number of bytes of memory required. Once this much has
40317 ** been released, the function returns. The return value is the total number
40318 ** of bytes of memory released.
40320 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
40321 int nFree = 0;
40322 assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
40323 assert( sqlite3_mutex_notheld(pcache1.mutex) );
40324 if( pcache1.pStart==0 ){
40325 PgHdr1 *p;
40326 pcache1EnterMutex(&pcache1.grp);
40327 while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
40328 nFree += pcache1MemSize(p->page.pBuf);
40329 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
40330 nFree += sqlite3MemSize(p);
40331 #endif
40332 assert( p->isPinned==0 );
40333 pcache1PinPage(p);
40334 pcache1RemoveFromHash(p);
40335 pcache1FreePage(p);
40337 pcache1LeaveMutex(&pcache1.grp);
40339 return nFree;
40341 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
40343 #ifdef SQLITE_TEST
40345 ** This function is used by test procedures to inspect the internal state
40346 ** of the global cache.
40348 SQLITE_PRIVATE void sqlite3PcacheStats(
40349 int *pnCurrent, /* OUT: Total number of pages cached */
40350 int *pnMax, /* OUT: Global maximum cache size */
40351 int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
40352 int *pnRecyclable /* OUT: Total number of pages available for recycling */
40354 PgHdr1 *p;
40355 int nRecyclable = 0;
40356 for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
40357 assert( p->isPinned==0 );
40358 nRecyclable++;
40360 *pnCurrent = pcache1.grp.nCurrentPage;
40361 *pnMax = (int)pcache1.grp.nMaxPage;
40362 *pnMin = (int)pcache1.grp.nMinPage;
40363 *pnRecyclable = nRecyclable;
40365 #endif
40367 /************** End of pcache1.c *********************************************/
40368 /************** Begin file rowset.c ******************************************/
40370 ** 2008 December 3
40372 ** The author disclaims copyright to this source code. In place of
40373 ** a legal notice, here is a blessing:
40375 ** May you do good and not evil.
40376 ** May you find forgiveness for yourself and forgive others.
40377 ** May you share freely, never taking more than you give.
40379 *************************************************************************
40381 ** This module implements an object we call a "RowSet".
40383 ** The RowSet object is a collection of rowids. Rowids
40384 ** are inserted into the RowSet in an arbitrary order. Inserts
40385 ** can be intermixed with tests to see if a given rowid has been
40386 ** previously inserted into the RowSet.
40388 ** After all inserts are finished, it is possible to extract the
40389 ** elements of the RowSet in sorted order. Once this extraction
40390 ** process has started, no new elements may be inserted.
40392 ** Hence, the primitive operations for a RowSet are:
40394 ** CREATE
40395 ** INSERT
40396 ** TEST
40397 ** SMALLEST
40398 ** DESTROY
40400 ** The CREATE and DESTROY primitives are the constructor and destructor,
40401 ** obviously. The INSERT primitive adds a new element to the RowSet.
40402 ** TEST checks to see if an element is already in the RowSet. SMALLEST
40403 ** extracts the least value from the RowSet.
40405 ** The INSERT primitive might allocate additional memory. Memory is
40406 ** allocated in chunks so most INSERTs do no allocation. There is an
40407 ** upper bound on the size of allocated memory. No memory is freed
40408 ** until DESTROY.
40410 ** The TEST primitive includes a "batch" number. The TEST primitive
40411 ** will only see elements that were inserted before the last change
40412 ** in the batch number. In other words, if an INSERT occurs between
40413 ** two TESTs where the TESTs have the same batch nubmer, then the
40414 ** value added by the INSERT will not be visible to the second TEST.
40415 ** The initial batch number is zero, so if the very first TEST contains
40416 ** a non-zero batch number, it will see all prior INSERTs.
40418 ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
40419 ** that is attempted.
40421 ** The cost of an INSERT is roughly constant. (Sometimes new memory
40422 ** has to be allocated on an INSERT.) The cost of a TEST with a new
40423 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
40424 ** The cost of a TEST using the same batch number is O(logN). The cost
40425 ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
40426 ** primitives are constant time. The cost of DESTROY is O(N).
40428 ** There is an added cost of O(N) when switching between TEST and
40429 ** SMALLEST primitives.
40434 ** Target size for allocation chunks.
40436 #define ROWSET_ALLOCATION_SIZE 1024
40439 ** The number of rowset entries per allocation chunk.
40441 #define ROWSET_ENTRY_PER_CHUNK \
40442 ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
40445 ** Each entry in a RowSet is an instance of the following object.
40447 ** This same object is reused to store a linked list of trees of RowSetEntry
40448 ** objects. In that alternative use, pRight points to the next entry
40449 ** in the list, pLeft points to the tree, and v is unused. The
40450 ** RowSet.pForest value points to the head of this forest list.
40452 struct RowSetEntry {
40453 i64 v; /* ROWID value for this entry */
40454 struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
40455 struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
40459 ** RowSetEntry objects are allocated in large chunks (instances of the
40460 ** following structure) to reduce memory allocation overhead. The
40461 ** chunks are kept on a linked list so that they can be deallocated
40462 ** when the RowSet is destroyed.
40464 struct RowSetChunk {
40465 struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
40466 struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
40470 ** A RowSet in an instance of the following structure.
40472 ** A typedef of this structure if found in sqliteInt.h.
40474 struct RowSet {
40475 struct RowSetChunk *pChunk; /* List of all chunk allocations */
40476 sqlite3 *db; /* The database connection */
40477 struct RowSetEntry *pEntry; /* List of entries using pRight */
40478 struct RowSetEntry *pLast; /* Last entry on the pEntry list */
40479 struct RowSetEntry *pFresh; /* Source of new entry objects */
40480 struct RowSetEntry *pForest; /* List of binary trees of entries */
40481 u16 nFresh; /* Number of objects on pFresh */
40482 u16 rsFlags; /* Various flags */
40483 int iBatch; /* Current insert batch */
40487 ** Allowed values for RowSet.rsFlags
40489 #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
40490 #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
40493 ** Turn bulk memory into a RowSet object. N bytes of memory
40494 ** are available at pSpace. The db pointer is used as a memory context
40495 ** for any subsequent allocations that need to occur.
40496 ** Return a pointer to the new RowSet object.
40498 ** It must be the case that N is sufficient to make a Rowset. If not
40499 ** an assertion fault occurs.
40501 ** If N is larger than the minimum, use the surplus as an initial
40502 ** allocation of entries available to be filled.
40504 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
40505 RowSet *p;
40506 assert( N >= ROUND8(sizeof(*p)) );
40507 p = pSpace;
40508 p->pChunk = 0;
40509 p->db = db;
40510 p->pEntry = 0;
40511 p->pLast = 0;
40512 p->pForest = 0;
40513 p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
40514 p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
40515 p->rsFlags = ROWSET_SORTED;
40516 p->iBatch = 0;
40517 return p;
40521 ** Deallocate all chunks from a RowSet. This frees all memory that
40522 ** the RowSet has allocated over its lifetime. This routine is
40523 ** the destructor for the RowSet.
40525 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
40526 struct RowSetChunk *pChunk, *pNextChunk;
40527 for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
40528 pNextChunk = pChunk->pNextChunk;
40529 sqlite3DbFree(p->db, pChunk);
40531 p->pChunk = 0;
40532 p->nFresh = 0;
40533 p->pEntry = 0;
40534 p->pLast = 0;
40535 p->pForest = 0;
40536 p->rsFlags = ROWSET_SORTED;
40540 ** Allocate a new RowSetEntry object that is associated with the
40541 ** given RowSet. Return a pointer to the new and completely uninitialized
40542 ** objected.
40544 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
40545 ** routine returns NULL.
40547 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
40548 assert( p!=0 );
40549 if( p->nFresh==0 ){
40550 struct RowSetChunk *pNew;
40551 pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
40552 if( pNew==0 ){
40553 return 0;
40555 pNew->pNextChunk = p->pChunk;
40556 p->pChunk = pNew;
40557 p->pFresh = pNew->aEntry;
40558 p->nFresh = ROWSET_ENTRY_PER_CHUNK;
40560 p->nFresh--;
40561 return p->pFresh++;
40565 ** Insert a new value into a RowSet.
40567 ** The mallocFailed flag of the database connection is set if a
40568 ** memory allocation fails.
40570 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
40571 struct RowSetEntry *pEntry; /* The new entry */
40572 struct RowSetEntry *pLast; /* The last prior entry */
40574 /* This routine is never called after sqlite3RowSetNext() */
40575 assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
40577 pEntry = rowSetEntryAlloc(p);
40578 if( pEntry==0 ) return;
40579 pEntry->v = rowid;
40580 pEntry->pRight = 0;
40581 pLast = p->pLast;
40582 if( pLast ){
40583 if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
40584 p->rsFlags &= ~ROWSET_SORTED;
40586 pLast->pRight = pEntry;
40587 }else{
40588 p->pEntry = pEntry;
40590 p->pLast = pEntry;
40594 ** Merge two lists of RowSetEntry objects. Remove duplicates.
40596 ** The input lists are connected via pRight pointers and are
40597 ** assumed to each already be in sorted order.
40599 static struct RowSetEntry *rowSetEntryMerge(
40600 struct RowSetEntry *pA, /* First sorted list to be merged */
40601 struct RowSetEntry *pB /* Second sorted list to be merged */
40603 struct RowSetEntry head;
40604 struct RowSetEntry *pTail;
40606 pTail = &head;
40607 while( pA && pB ){
40608 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
40609 assert( pB->pRight==0 || pB->v<=pB->pRight->v );
40610 if( pA->v<pB->v ){
40611 pTail->pRight = pA;
40612 pA = pA->pRight;
40613 pTail = pTail->pRight;
40614 }else if( pB->v<pA->v ){
40615 pTail->pRight = pB;
40616 pB = pB->pRight;
40617 pTail = pTail->pRight;
40618 }else{
40619 pA = pA->pRight;
40622 if( pA ){
40623 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
40624 pTail->pRight = pA;
40625 }else{
40626 assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
40627 pTail->pRight = pB;
40629 return head.pRight;
40633 ** Sort all elements on the list of RowSetEntry objects into order of
40634 ** increasing v.
40636 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
40637 unsigned int i;
40638 struct RowSetEntry *pNext, *aBucket[40];
40640 memset(aBucket, 0, sizeof(aBucket));
40641 while( pIn ){
40642 pNext = pIn->pRight;
40643 pIn->pRight = 0;
40644 for(i=0; aBucket[i]; i++){
40645 pIn = rowSetEntryMerge(aBucket[i], pIn);
40646 aBucket[i] = 0;
40648 aBucket[i] = pIn;
40649 pIn = pNext;
40651 pIn = 0;
40652 for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
40653 pIn = rowSetEntryMerge(pIn, aBucket[i]);
40655 return pIn;
40660 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
40661 ** Convert this tree into a linked list connected by the pRight pointers
40662 ** and return pointers to the first and last elements of the new list.
40664 static void rowSetTreeToList(
40665 struct RowSetEntry *pIn, /* Root of the input tree */
40666 struct RowSetEntry **ppFirst, /* Write head of the output list here */
40667 struct RowSetEntry **ppLast /* Write tail of the output list here */
40669 assert( pIn!=0 );
40670 if( pIn->pLeft ){
40671 struct RowSetEntry *p;
40672 rowSetTreeToList(pIn->pLeft, ppFirst, &p);
40673 p->pRight = pIn;
40674 }else{
40675 *ppFirst = pIn;
40677 if( pIn->pRight ){
40678 rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
40679 }else{
40680 *ppLast = pIn;
40682 assert( (*ppLast)->pRight==0 );
40687 ** Convert a sorted list of elements (connected by pRight) into a binary
40688 ** tree with depth of iDepth. A depth of 1 means the tree contains a single
40689 ** node taken from the head of *ppList. A depth of 2 means a tree with
40690 ** three nodes. And so forth.
40692 ** Use as many entries from the input list as required and update the
40693 ** *ppList to point to the unused elements of the list. If the input
40694 ** list contains too few elements, then construct an incomplete tree
40695 ** and leave *ppList set to NULL.
40697 ** Return a pointer to the root of the constructed binary tree.
40699 static struct RowSetEntry *rowSetNDeepTree(
40700 struct RowSetEntry **ppList,
40701 int iDepth
40703 struct RowSetEntry *p; /* Root of the new tree */
40704 struct RowSetEntry *pLeft; /* Left subtree */
40705 if( *ppList==0 ){
40706 return 0;
40708 if( iDepth==1 ){
40709 p = *ppList;
40710 *ppList = p->pRight;
40711 p->pLeft = p->pRight = 0;
40712 return p;
40714 pLeft = rowSetNDeepTree(ppList, iDepth-1);
40715 p = *ppList;
40716 if( p==0 ){
40717 return pLeft;
40719 p->pLeft = pLeft;
40720 *ppList = p->pRight;
40721 p->pRight = rowSetNDeepTree(ppList, iDepth-1);
40722 return p;
40726 ** Convert a sorted list of elements into a binary tree. Make the tree
40727 ** as deep as it needs to be in order to contain the entire list.
40729 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
40730 int iDepth; /* Depth of the tree so far */
40731 struct RowSetEntry *p; /* Current tree root */
40732 struct RowSetEntry *pLeft; /* Left subtree */
40734 assert( pList!=0 );
40735 p = pList;
40736 pList = p->pRight;
40737 p->pLeft = p->pRight = 0;
40738 for(iDepth=1; pList; iDepth++){
40739 pLeft = p;
40740 p = pList;
40741 pList = p->pRight;
40742 p->pLeft = pLeft;
40743 p->pRight = rowSetNDeepTree(&pList, iDepth);
40745 return p;
40749 ** Take all the entries on p->pEntry and on the trees in p->pForest and
40750 ** sort them all together into one big ordered list on p->pEntry.
40752 ** This routine should only be called once in the life of a RowSet.
40754 static void rowSetToList(RowSet *p){
40756 /* This routine is called only once */
40757 assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
40759 if( (p->rsFlags & ROWSET_SORTED)==0 ){
40760 p->pEntry = rowSetEntrySort(p->pEntry);
40763 /* While this module could theoretically support it, sqlite3RowSetNext()
40764 ** is never called after sqlite3RowSetText() for the same RowSet. So
40765 ** there is never a forest to deal with. Should this change, simply
40766 ** remove the assert() and the #if 0. */
40767 assert( p->pForest==0 );
40768 #if 0
40769 while( p->pForest ){
40770 struct RowSetEntry *pTree = p->pForest->pLeft;
40771 if( pTree ){
40772 struct RowSetEntry *pHead, *pTail;
40773 rowSetTreeToList(pTree, &pHead, &pTail);
40774 p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
40776 p->pForest = p->pForest->pRight;
40778 #endif
40779 p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
40783 ** Extract the smallest element from the RowSet.
40784 ** Write the element into *pRowid. Return 1 on success. Return
40785 ** 0 if the RowSet is already empty.
40787 ** After this routine has been called, the sqlite3RowSetInsert()
40788 ** routine may not be called again.
40790 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
40791 assert( p!=0 );
40793 /* Merge the forest into a single sorted list on first call */
40794 if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
40796 /* Return the next entry on the list */
40797 if( p->pEntry ){
40798 *pRowid = p->pEntry->v;
40799 p->pEntry = p->pEntry->pRight;
40800 if( p->pEntry==0 ){
40801 sqlite3RowSetClear(p);
40803 return 1;
40804 }else{
40805 return 0;
40810 ** Check to see if element iRowid was inserted into the rowset as
40811 ** part of any insert batch prior to iBatch. Return 1 or 0.
40813 ** If this is the first test of a new batch and if there exist entries
40814 ** on pRowSet->pEntry, then sort those entries into the forest at
40815 ** pRowSet->pForest so that they can be tested.
40817 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
40818 struct RowSetEntry *p, *pTree;
40820 /* This routine is never called after sqlite3RowSetNext() */
40821 assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
40823 /* Sort entries into the forest on the first test of a new batch
40825 if( iBatch!=pRowSet->iBatch ){
40826 p = pRowSet->pEntry;
40827 if( p ){
40828 struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
40829 if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
40830 p = rowSetEntrySort(p);
40832 for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
40833 ppPrevTree = &pTree->pRight;
40834 if( pTree->pLeft==0 ){
40835 pTree->pLeft = rowSetListToTree(p);
40836 break;
40837 }else{
40838 struct RowSetEntry *pAux, *pTail;
40839 rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
40840 pTree->pLeft = 0;
40841 p = rowSetEntryMerge(pAux, p);
40844 if( pTree==0 ){
40845 *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
40846 if( pTree ){
40847 pTree->v = 0;
40848 pTree->pRight = 0;
40849 pTree->pLeft = rowSetListToTree(p);
40852 pRowSet->pEntry = 0;
40853 pRowSet->pLast = 0;
40854 pRowSet->rsFlags |= ROWSET_SORTED;
40856 pRowSet->iBatch = iBatch;
40859 /* Test to see if the iRowid value appears anywhere in the forest.
40860 ** Return 1 if it does and 0 if not.
40862 for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
40863 p = pTree->pLeft;
40864 while( p ){
40865 if( p->v<iRowid ){
40866 p = p->pRight;
40867 }else if( p->v>iRowid ){
40868 p = p->pLeft;
40869 }else{
40870 return 1;
40874 return 0;
40877 /************** End of rowset.c **********************************************/
40878 /************** Begin file pager.c *******************************************/
40880 ** 2001 September 15
40882 ** The author disclaims copyright to this source code. In place of
40883 ** a legal notice, here is a blessing:
40885 ** May you do good and not evil.
40886 ** May you find forgiveness for yourself and forgive others.
40887 ** May you share freely, never taking more than you give.
40889 *************************************************************************
40890 ** This is the implementation of the page cache subsystem or "pager".
40892 ** The pager is used to access a database disk file. It implements
40893 ** atomic commit and rollback through the use of a journal file that
40894 ** is separate from the database file. The pager also implements file
40895 ** locking to prevent two processes from writing the same database
40896 ** file simultaneously, or one process from reading the database while
40897 ** another is writing.
40899 #ifndef SQLITE_OMIT_DISKIO
40900 /************** Include wal.h in the middle of pager.c ***********************/
40901 /************** Begin file wal.h *********************************************/
40903 ** 2010 February 1
40905 ** The author disclaims copyright to this source code. In place of
40906 ** a legal notice, here is a blessing:
40908 ** May you do good and not evil.
40909 ** May you find forgiveness for yourself and forgive others.
40910 ** May you share freely, never taking more than you give.
40912 *************************************************************************
40913 ** This header file defines the interface to the write-ahead logging
40914 ** system. Refer to the comments below and the header comment attached to
40915 ** the implementation of each function in log.c for further details.
40918 #ifndef _WAL_H_
40919 #define _WAL_H_
40922 /* Additional values that can be added to the sync_flags argument of
40923 ** sqlite3WalFrames():
40925 #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
40926 #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
40928 #ifdef SQLITE_OMIT_WAL
40929 # define sqlite3WalOpen(x,y,z) 0
40930 # define sqlite3WalLimit(x,y)
40931 # define sqlite3WalClose(w,x,y,z) 0
40932 # define sqlite3WalBeginReadTransaction(y,z) 0
40933 # define sqlite3WalEndReadTransaction(z)
40934 # define sqlite3WalDbsize(y) 0
40935 # define sqlite3WalBeginWriteTransaction(y) 0
40936 # define sqlite3WalEndWriteTransaction(x) 0
40937 # define sqlite3WalUndo(x,y,z) 0
40938 # define sqlite3WalSavepoint(y,z)
40939 # define sqlite3WalSavepointUndo(y,z) 0
40940 # define sqlite3WalFrames(u,v,w,x,y,z) 0
40941 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
40942 # define sqlite3WalCallback(z) 0
40943 # define sqlite3WalExclusiveMode(y,z) 0
40944 # define sqlite3WalHeapMemory(z) 0
40945 # define sqlite3WalFramesize(z) 0
40946 # define sqlite3WalFindFrame(x,y,z) 0
40947 #else
40949 #define WAL_SAVEPOINT_NDATA 4
40951 /* Connection to a write-ahead log (WAL) file.
40952 ** There is one object of this type for each pager.
40954 typedef struct Wal Wal;
40956 /* Open and close a connection to a write-ahead log. */
40957 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
40958 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
40960 /* Set the limiting size of a WAL file. */
40961 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
40963 /* Used by readers to open (lock) and close (unlock) a snapshot. A
40964 ** snapshot is like a read-transaction. It is the state of the database
40965 ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
40966 ** preserves the current state even if the other threads or processes
40967 ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
40968 ** transaction and releases the lock.
40970 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
40971 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
40973 /* Read a page from the write-ahead log, if it is present. */
40974 SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
40975 SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
40977 /* If the WAL is not empty, return the size of the database. */
40978 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
40980 /* Obtain or release the WRITER lock. */
40981 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
40982 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
40984 /* Undo any frames written (but not committed) to the log */
40985 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
40987 /* Return an integer that records the current (uncommitted) write
40988 ** position in the WAL */
40989 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
40991 /* Move the write position of the WAL back to iFrame. Called in
40992 ** response to a ROLLBACK TO command. */
40993 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
40995 /* Write a frame or frames to the log. */
40996 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
40998 /* Copy pages from the log to the database file */
40999 SQLITE_PRIVATE int sqlite3WalCheckpoint(
41000 Wal *pWal, /* Write-ahead log connection */
41001 int eMode, /* One of PASSIVE, FULL and RESTART */
41002 int (*xBusy)(void*), /* Function to call when busy */
41003 void *pBusyArg, /* Context argument for xBusyHandler */
41004 int sync_flags, /* Flags to sync db file with (or 0) */
41005 int nBuf, /* Size of buffer nBuf */
41006 u8 *zBuf, /* Temporary buffer to use */
41007 int *pnLog, /* OUT: Number of frames in WAL */
41008 int *pnCkpt /* OUT: Number of backfilled frames in WAL */
41011 /* Return the value to pass to a sqlite3_wal_hook callback, the
41012 ** number of frames in the WAL at the point of the last commit since
41013 ** sqlite3WalCallback() was called. If no commits have occurred since
41014 ** the last call, then return 0.
41016 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
41018 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
41019 ** by the pager layer on the database file.
41021 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
41023 /* Return true if the argument is non-NULL and the WAL module is using
41024 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
41025 ** WAL module is using shared-memory, return false.
41027 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
41029 #ifdef SQLITE_ENABLE_ZIPVFS
41030 /* If the WAL file is not empty, return the number of bytes of content
41031 ** stored in each frame (i.e. the db page-size when the WAL was created).
41033 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
41034 #endif
41036 #endif /* ifndef SQLITE_OMIT_WAL */
41037 #endif /* _WAL_H_ */
41039 /************** End of wal.h *************************************************/
41040 /************** Continuing where we left off in pager.c **********************/
41043 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
41045 ** This comment block describes invariants that hold when using a rollback
41046 ** journal. These invariants do not apply for journal_mode=WAL,
41047 ** journal_mode=MEMORY, or journal_mode=OFF.
41049 ** Within this comment block, a page is deemed to have been synced
41050 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
41051 ** Otherwise, the page is not synced until the xSync method of the VFS
41052 ** is called successfully on the file containing the page.
41054 ** Definition: A page of the database file is said to be "overwriteable" if
41055 ** one or more of the following are true about the page:
41057 ** (a) The original content of the page as it was at the beginning of
41058 ** the transaction has been written into the rollback journal and
41059 ** synced.
41061 ** (b) The page was a freelist leaf page at the start of the transaction.
41063 ** (c) The page number is greater than the largest page that existed in
41064 ** the database file at the start of the transaction.
41066 ** (1) A page of the database file is never overwritten unless one of the
41067 ** following are true:
41069 ** (a) The page and all other pages on the same sector are overwriteable.
41071 ** (b) The atomic page write optimization is enabled, and the entire
41072 ** transaction other than the update of the transaction sequence
41073 ** number consists of a single page change.
41075 ** (2) The content of a page written into the rollback journal exactly matches
41076 ** both the content in the database when the rollback journal was written
41077 ** and the content in the database at the beginning of the current
41078 ** transaction.
41080 ** (3) Writes to the database file are an integer multiple of the page size
41081 ** in length and are aligned on a page boundary.
41083 ** (4) Reads from the database file are either aligned on a page boundary and
41084 ** an integer multiple of the page size in length or are taken from the
41085 ** first 100 bytes of the database file.
41087 ** (5) All writes to the database file are synced prior to the rollback journal
41088 ** being deleted, truncated, or zeroed.
41090 ** (6) If a master journal file is used, then all writes to the database file
41091 ** are synced prior to the master journal being deleted.
41093 ** Definition: Two databases (or the same database at two points it time)
41094 ** are said to be "logically equivalent" if they give the same answer to
41095 ** all queries. Note in particular the content of freelist leaf
41096 ** pages can be changed arbitrarily without affecting the logical equivalence
41097 ** of the database.
41099 ** (7) At any time, if any subset, including the empty set and the total set,
41100 ** of the unsynced changes to a rollback journal are removed and the
41101 ** journal is rolled back, the resulting database file will be logically
41102 ** equivalent to the database file at the beginning of the transaction.
41104 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
41105 ** is called to restore the database file to the same size it was at
41106 ** the beginning of the transaction. (In some VFSes, the xTruncate
41107 ** method is a no-op, but that does not change the fact the SQLite will
41108 ** invoke it.)
41110 ** (9) Whenever the database file is modified, at least one bit in the range
41111 ** of bytes from 24 through 39 inclusive will be changed prior to releasing
41112 ** the EXCLUSIVE lock, thus signaling other connections on the same
41113 ** database to flush their caches.
41115 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
41116 ** than one billion transactions.
41118 ** (11) A database file is well-formed at the beginning and at the conclusion
41119 ** of every transaction.
41121 ** (12) An EXCLUSIVE lock is held on the database file when writing to
41122 ** the database file.
41124 ** (13) A SHARED lock is held on the database file while reading any
41125 ** content out of the database file.
41127 ******************************************************************************/
41130 ** Macros for troubleshooting. Normally turned off
41132 #if 0
41133 int sqlite3PagerTrace=1; /* True to enable tracing */
41134 #define sqlite3DebugPrintf printf
41135 #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
41136 #else
41137 #define PAGERTRACE(X)
41138 #endif
41141 ** The following two macros are used within the PAGERTRACE() macros above
41142 ** to print out file-descriptors.
41144 ** PAGERID() takes a pointer to a Pager struct as its argument. The
41145 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
41146 ** struct as its argument.
41148 #define PAGERID(p) ((int)(p->fd))
41149 #define FILEHANDLEID(fd) ((int)fd)
41152 ** The Pager.eState variable stores the current 'state' of a pager. A
41153 ** pager may be in any one of the seven states shown in the following
41154 ** state diagram.
41156 ** OPEN <------+------+
41157 ** | | |
41158 ** V | |
41159 ** +---------> READER-------+ |
41160 ** | | |
41161 ** | V |
41162 ** |<-------WRITER_LOCKED------> ERROR
41163 ** | | ^
41164 ** | V |
41165 ** |<------WRITER_CACHEMOD-------->|
41166 ** | | |
41167 ** | V |
41168 ** |<-------WRITER_DBMOD---------->|
41169 ** | | |
41170 ** | V |
41171 ** +<------WRITER_FINISHED-------->+
41174 ** List of state transitions and the C [function] that performs each:
41176 ** OPEN -> READER [sqlite3PagerSharedLock]
41177 ** READER -> OPEN [pager_unlock]
41179 ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
41180 ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
41181 ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
41182 ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
41183 ** WRITER_*** -> READER [pager_end_transaction]
41185 ** WRITER_*** -> ERROR [pager_error]
41186 ** ERROR -> OPEN [pager_unlock]
41189 ** OPEN:
41191 ** The pager starts up in this state. Nothing is guaranteed in this
41192 ** state - the file may or may not be locked and the database size is
41193 ** unknown. The database may not be read or written.
41195 ** * No read or write transaction is active.
41196 ** * Any lock, or no lock at all, may be held on the database file.
41197 ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
41199 ** READER:
41201 ** In this state all the requirements for reading the database in
41202 ** rollback (non-WAL) mode are met. Unless the pager is (or recently
41203 ** was) in exclusive-locking mode, a user-level read transaction is
41204 ** open. The database size is known in this state.
41206 ** A connection running with locking_mode=normal enters this state when
41207 ** it opens a read-transaction on the database and returns to state
41208 ** OPEN after the read-transaction is completed. However a connection
41209 ** running in locking_mode=exclusive (including temp databases) remains in
41210 ** this state even after the read-transaction is closed. The only way
41211 ** a locking_mode=exclusive connection can transition from READER to OPEN
41212 ** is via the ERROR state (see below).
41214 ** * A read transaction may be active (but a write-transaction cannot).
41215 ** * A SHARED or greater lock is held on the database file.
41216 ** * The dbSize variable may be trusted (even if a user-level read
41217 ** transaction is not active). The dbOrigSize and dbFileSize variables
41218 ** may not be trusted at this point.
41219 ** * If the database is a WAL database, then the WAL connection is open.
41220 ** * Even if a read-transaction is not open, it is guaranteed that
41221 ** there is no hot-journal in the file-system.
41223 ** WRITER_LOCKED:
41225 ** The pager moves to this state from READER when a write-transaction
41226 ** is first opened on the database. In WRITER_LOCKED state, all locks
41227 ** required to start a write-transaction are held, but no actual
41228 ** modifications to the cache or database have taken place.
41230 ** In rollback mode, a RESERVED or (if the transaction was opened with
41231 ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
41232 ** moving to this state, but the journal file is not written to or opened
41233 ** to in this state. If the transaction is committed or rolled back while
41234 ** in WRITER_LOCKED state, all that is required is to unlock the database
41235 ** file.
41237 ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
41238 ** If the connection is running with locking_mode=exclusive, an attempt
41239 ** is made to obtain an EXCLUSIVE lock on the database file.
41241 ** * A write transaction is active.
41242 ** * If the connection is open in rollback-mode, a RESERVED or greater
41243 ** lock is held on the database file.
41244 ** * If the connection is open in WAL-mode, a WAL write transaction
41245 ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
41246 ** called).
41247 ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
41248 ** * The contents of the pager cache have not been modified.
41249 ** * The journal file may or may not be open.
41250 ** * Nothing (not even the first header) has been written to the journal.
41252 ** WRITER_CACHEMOD:
41254 ** A pager moves from WRITER_LOCKED state to this state when a page is
41255 ** first modified by the upper layer. In rollback mode the journal file
41256 ** is opened (if it is not already open) and a header written to the
41257 ** start of it. The database file on disk has not been modified.
41259 ** * A write transaction is active.
41260 ** * A RESERVED or greater lock is held on the database file.
41261 ** * The journal file is open and the first header has been written
41262 ** to it, but the header has not been synced to disk.
41263 ** * The contents of the page cache have been modified.
41265 ** WRITER_DBMOD:
41267 ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
41268 ** when it modifies the contents of the database file. WAL connections
41269 ** never enter this state (since they do not modify the database file,
41270 ** just the log file).
41272 ** * A write transaction is active.
41273 ** * An EXCLUSIVE or greater lock is held on the database file.
41274 ** * The journal file is open and the first header has been written
41275 ** and synced to disk.
41276 ** * The contents of the page cache have been modified (and possibly
41277 ** written to disk).
41279 ** WRITER_FINISHED:
41281 ** It is not possible for a WAL connection to enter this state.
41283 ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
41284 ** state after the entire transaction has been successfully written into the
41285 ** database file. In this state the transaction may be committed simply
41286 ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
41287 ** not possible to modify the database further. At this point, the upper
41288 ** layer must either commit or rollback the transaction.
41290 ** * A write transaction is active.
41291 ** * An EXCLUSIVE or greater lock is held on the database file.
41292 ** * All writing and syncing of journal and database data has finished.
41293 ** If no error occurred, all that remains is to finalize the journal to
41294 ** commit the transaction. If an error did occur, the caller will need
41295 ** to rollback the transaction.
41297 ** ERROR:
41299 ** The ERROR state is entered when an IO or disk-full error (including
41300 ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
41301 ** difficult to be sure that the in-memory pager state (cache contents,
41302 ** db size etc.) are consistent with the contents of the file-system.
41304 ** Temporary pager files may enter the ERROR state, but in-memory pagers
41305 ** cannot.
41307 ** For example, if an IO error occurs while performing a rollback,
41308 ** the contents of the page-cache may be left in an inconsistent state.
41309 ** At this point it would be dangerous to change back to READER state
41310 ** (as usually happens after a rollback). Any subsequent readers might
41311 ** report database corruption (due to the inconsistent cache), and if
41312 ** they upgrade to writers, they may inadvertently corrupt the database
41313 ** file. To avoid this hazard, the pager switches into the ERROR state
41314 ** instead of READER following such an error.
41316 ** Once it has entered the ERROR state, any attempt to use the pager
41317 ** to read or write data returns an error. Eventually, once all
41318 ** outstanding transactions have been abandoned, the pager is able to
41319 ** transition back to OPEN state, discarding the contents of the
41320 ** page-cache and any other in-memory state at the same time. Everything
41321 ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
41322 ** when a read-transaction is next opened on the pager (transitioning
41323 ** the pager into READER state). At that point the system has recovered
41324 ** from the error.
41326 ** Specifically, the pager jumps into the ERROR state if:
41328 ** 1. An error occurs while attempting a rollback. This happens in
41329 ** function sqlite3PagerRollback().
41331 ** 2. An error occurs while attempting to finalize a journal file
41332 ** following a commit in function sqlite3PagerCommitPhaseTwo().
41334 ** 3. An error occurs while attempting to write to the journal or
41335 ** database file in function pagerStress() in order to free up
41336 ** memory.
41338 ** In other cases, the error is returned to the b-tree layer. The b-tree
41339 ** layer then attempts a rollback operation. If the error condition
41340 ** persists, the pager enters the ERROR state via condition (1) above.
41342 ** Condition (3) is necessary because it can be triggered by a read-only
41343 ** statement executed within a transaction. In this case, if the error
41344 ** code were simply returned to the user, the b-tree layer would not
41345 ** automatically attempt a rollback, as it assumes that an error in a
41346 ** read-only statement cannot leave the pager in an internally inconsistent
41347 ** state.
41349 ** * The Pager.errCode variable is set to something other than SQLITE_OK.
41350 ** * There are one or more outstanding references to pages (after the
41351 ** last reference is dropped the pager should move back to OPEN state).
41352 ** * The pager is not an in-memory pager.
41355 ** Notes:
41357 ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
41358 ** connection is open in WAL mode. A WAL connection is always in one
41359 ** of the first four states.
41361 ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
41362 ** state. There are two exceptions: immediately after exclusive-mode has
41363 ** been turned on (and before any read or write transactions are
41364 ** executed), and when the pager is leaving the "error state".
41366 ** * See also: assert_pager_state().
41368 #define PAGER_OPEN 0
41369 #define PAGER_READER 1
41370 #define PAGER_WRITER_LOCKED 2
41371 #define PAGER_WRITER_CACHEMOD 3
41372 #define PAGER_WRITER_DBMOD 4
41373 #define PAGER_WRITER_FINISHED 5
41374 #define PAGER_ERROR 6
41377 ** The Pager.eLock variable is almost always set to one of the
41378 ** following locking-states, according to the lock currently held on
41379 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
41380 ** This variable is kept up to date as locks are taken and released by
41381 ** the pagerLockDb() and pagerUnlockDb() wrappers.
41383 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
41384 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
41385 ** the operation was successful. In these circumstances pagerLockDb() and
41386 ** pagerUnlockDb() take a conservative approach - eLock is always updated
41387 ** when unlocking the file, and only updated when locking the file if the
41388 ** VFS call is successful. This way, the Pager.eLock variable may be set
41389 ** to a less exclusive (lower) value than the lock that is actually held
41390 ** at the system level, but it is never set to a more exclusive value.
41392 ** This is usually safe. If an xUnlock fails or appears to fail, there may
41393 ** be a few redundant xLock() calls or a lock may be held for longer than
41394 ** required, but nothing really goes wrong.
41396 ** The exception is when the database file is unlocked as the pager moves
41397 ** from ERROR to OPEN state. At this point there may be a hot-journal file
41398 ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
41399 ** transition, by the same pager or any other). If the call to xUnlock()
41400 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
41401 ** can confuse the call to xCheckReservedLock() call made later as part
41402 ** of hot-journal detection.
41404 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
41405 ** lock held by this process or any others". So xCheckReservedLock may
41406 ** return true because the caller itself is holding an EXCLUSIVE lock (but
41407 ** doesn't know it because of a previous error in xUnlock). If this happens
41408 ** a hot-journal may be mistaken for a journal being created by an active
41409 ** transaction in another process, causing SQLite to read from the database
41410 ** without rolling it back.
41412 ** To work around this, if a call to xUnlock() fails when unlocking the
41413 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
41414 ** is only changed back to a real locking state after a successful call
41415 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
41416 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
41417 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
41418 ** lock on the database file before attempting to roll it back. See function
41419 ** PagerSharedLock() for more detail.
41421 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
41422 ** PAGER_OPEN state.
41424 #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
41427 ** A macro used for invoking the codec if there is one
41429 #ifdef SQLITE_HAS_CODEC
41430 # define CODEC1(P,D,N,X,E) \
41431 if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
41432 # define CODEC2(P,D,N,X,E,O) \
41433 if( P->xCodec==0 ){ O=(char*)D; }else \
41434 if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
41435 #else
41436 # define CODEC1(P,D,N,X,E) /* NO-OP */
41437 # define CODEC2(P,D,N,X,E,O) O=(char*)D
41438 #endif
41441 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
41442 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
41443 ** This could conceivably cause corruption following a power failure on
41444 ** such a system. This is currently an undocumented limit.
41446 #define MAX_SECTOR_SIZE 0x10000
41449 ** An instance of the following structure is allocated for each active
41450 ** savepoint and statement transaction in the system. All such structures
41451 ** are stored in the Pager.aSavepoint[] array, which is allocated and
41452 ** resized using sqlite3Realloc().
41454 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
41455 ** set to 0. If a journal-header is written into the main journal while
41456 ** the savepoint is active, then iHdrOffset is set to the byte offset
41457 ** immediately following the last journal record written into the main
41458 ** journal before the journal-header. This is required during savepoint
41459 ** rollback (see pagerPlaybackSavepoint()).
41461 typedef struct PagerSavepoint PagerSavepoint;
41462 struct PagerSavepoint {
41463 i64 iOffset; /* Starting offset in main journal */
41464 i64 iHdrOffset; /* See above */
41465 Bitvec *pInSavepoint; /* Set of pages in this savepoint */
41466 Pgno nOrig; /* Original number of pages in file */
41467 Pgno iSubRec; /* Index of first record in sub-journal */
41468 #ifndef SQLITE_OMIT_WAL
41469 u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
41470 #endif
41474 ** Bits of the Pager.doNotSpill flag. See further description below.
41476 #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
41477 #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
41478 #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
41481 ** An open page cache is an instance of struct Pager. A description of
41482 ** some of the more important member variables follows:
41484 ** eState
41486 ** The current 'state' of the pager object. See the comment and state
41487 ** diagram above for a description of the pager state.
41489 ** eLock
41491 ** For a real on-disk database, the current lock held on the database file -
41492 ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
41494 ** For a temporary or in-memory database (neither of which require any
41495 ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
41496 ** databases always have Pager.exclusiveMode==1, this tricks the pager
41497 ** logic into thinking that it already has all the locks it will ever
41498 ** need (and no reason to release them).
41500 ** In some (obscure) circumstances, this variable may also be set to
41501 ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
41502 ** details.
41504 ** changeCountDone
41506 ** This boolean variable is used to make sure that the change-counter
41507 ** (the 4-byte header field at byte offset 24 of the database file) is
41508 ** not updated more often than necessary.
41510 ** It is set to true when the change-counter field is updated, which
41511 ** can only happen if an exclusive lock is held on the database file.
41512 ** It is cleared (set to false) whenever an exclusive lock is
41513 ** relinquished on the database file. Each time a transaction is committed,
41514 ** The changeCountDone flag is inspected. If it is true, the work of
41515 ** updating the change-counter is omitted for the current transaction.
41517 ** This mechanism means that when running in exclusive mode, a connection
41518 ** need only update the change-counter once, for the first transaction
41519 ** committed.
41521 ** setMaster
41523 ** When PagerCommitPhaseOne() is called to commit a transaction, it may
41524 ** (or may not) specify a master-journal name to be written into the
41525 ** journal file before it is synced to disk.
41527 ** Whether or not a journal file contains a master-journal pointer affects
41528 ** the way in which the journal file is finalized after the transaction is
41529 ** committed or rolled back when running in "journal_mode=PERSIST" mode.
41530 ** If a journal file does not contain a master-journal pointer, it is
41531 ** finalized by overwriting the first journal header with zeroes. If
41532 ** it does contain a master-journal pointer the journal file is finalized
41533 ** by truncating it to zero bytes, just as if the connection were
41534 ** running in "journal_mode=truncate" mode.
41536 ** Journal files that contain master journal pointers cannot be finalized
41537 ** simply by overwriting the first journal-header with zeroes, as the
41538 ** master journal pointer could interfere with hot-journal rollback of any
41539 ** subsequently interrupted transaction that reuses the journal file.
41541 ** The flag is cleared as soon as the journal file is finalized (either
41542 ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
41543 ** journal file from being successfully finalized, the setMaster flag
41544 ** is cleared anyway (and the pager will move to ERROR state).
41546 ** doNotSpill
41548 ** This variables control the behavior of cache-spills (calls made by
41549 ** the pcache module to the pagerStress() routine to write cached data
41550 ** to the file-system in order to free up memory).
41552 ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
41553 ** writing to the database from pagerStress() is disabled altogether.
41554 ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
41555 ** comes up during savepoint rollback that requires the pcache module
41556 ** to allocate a new page to prevent the journal file from being written
41557 ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
41558 ** case is a user preference.
41560 ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
41561 ** is permitted, but syncing the journal file is not. This flag is set
41562 ** by sqlite3PagerWrite() when the file-system sector-size is larger than
41563 ** the database page-size in order to prevent a journal sync from happening
41564 ** in between the journalling of two pages on the same sector.
41566 ** subjInMemory
41568 ** This is a boolean variable. If true, then any required sub-journal
41569 ** is opened as an in-memory journal file. If false, then in-memory
41570 ** sub-journals are only used for in-memory pager files.
41572 ** This variable is updated by the upper layer each time a new
41573 ** write-transaction is opened.
41575 ** dbSize, dbOrigSize, dbFileSize
41577 ** Variable dbSize is set to the number of pages in the database file.
41578 ** It is valid in PAGER_READER and higher states (all states except for
41579 ** OPEN and ERROR).
41581 ** dbSize is set based on the size of the database file, which may be
41582 ** larger than the size of the database (the value stored at offset
41583 ** 28 of the database header by the btree). If the size of the file
41584 ** is not an integer multiple of the page-size, the value stored in
41585 ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
41586 ** Except, any file that is greater than 0 bytes in size is considered
41587 ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
41588 ** to dbSize==1).
41590 ** During a write-transaction, if pages with page-numbers greater than
41591 ** dbSize are modified in the cache, dbSize is updated accordingly.
41592 ** Similarly, if the database is truncated using PagerTruncateImage(),
41593 ** dbSize is updated.
41595 ** Variables dbOrigSize and dbFileSize are valid in states
41596 ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
41597 ** variable at the start of the transaction. It is used during rollback,
41598 ** and to determine whether or not pages need to be journalled before
41599 ** being modified.
41601 ** Throughout a write-transaction, dbFileSize contains the size of
41602 ** the file on disk in pages. It is set to a copy of dbSize when the
41603 ** write-transaction is first opened, and updated when VFS calls are made
41604 ** to write or truncate the database file on disk.
41606 ** The only reason the dbFileSize variable is required is to suppress
41607 ** unnecessary calls to xTruncate() after committing a transaction. If,
41608 ** when a transaction is committed, the dbFileSize variable indicates
41609 ** that the database file is larger than the database image (Pager.dbSize),
41610 ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
41611 ** to measure the database file on disk, and then truncates it if required.
41612 ** dbFileSize is not used when rolling back a transaction. In this case
41613 ** pager_truncate() is called unconditionally (which means there may be
41614 ** a call to xFilesize() that is not strictly required). In either case,
41615 ** pager_truncate() may cause the file to become smaller or larger.
41617 ** dbHintSize
41619 ** The dbHintSize variable is used to limit the number of calls made to
41620 ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
41622 ** dbHintSize is set to a copy of the dbSize variable when a
41623 ** write-transaction is opened (at the same time as dbFileSize and
41624 ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
41625 ** dbHintSize is increased to the number of pages that correspond to the
41626 ** size-hint passed to the method call. See pager_write_pagelist() for
41627 ** details.
41629 ** errCode
41631 ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
41632 ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
41633 ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
41634 ** sub-codes.
41636 struct Pager {
41637 sqlite3_vfs *pVfs; /* OS functions to use for IO */
41638 u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
41639 u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
41640 u8 useJournal; /* Use a rollback journal on this file */
41641 u8 noSync; /* Do not sync the journal if true */
41642 u8 fullSync; /* Do extra syncs of the journal for robustness */
41643 u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
41644 u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
41645 u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
41646 u8 tempFile; /* zFilename is a temporary or immutable file */
41647 u8 noLock; /* Do not lock (except in WAL mode) */
41648 u8 readOnly; /* True for a read-only database */
41649 u8 memDb; /* True to inhibit all file I/O */
41651 /**************************************************************************
41652 ** The following block contains those class members that change during
41653 ** routine operation. Class members not in this block are either fixed
41654 ** when the pager is first created or else only change when there is a
41655 ** significant mode change (such as changing the page_size, locking_mode,
41656 ** or the journal_mode). From another view, these class members describe
41657 ** the "state" of the pager, while other class members describe the
41658 ** "configuration" of the pager.
41660 u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
41661 u8 eLock; /* Current lock held on database file */
41662 u8 changeCountDone; /* Set after incrementing the change-counter */
41663 u8 setMaster; /* True if a m-j name has been written to jrnl */
41664 u8 doNotSpill; /* Do not spill the cache when non-zero */
41665 u8 subjInMemory; /* True to use in-memory sub-journals */
41666 Pgno dbSize; /* Number of pages in the database */
41667 Pgno dbOrigSize; /* dbSize before the current transaction */
41668 Pgno dbFileSize; /* Number of pages in the database file */
41669 Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
41670 int errCode; /* One of several kinds of errors */
41671 int nRec; /* Pages journalled since last j-header written */
41672 u32 cksumInit; /* Quasi-random value added to every checksum */
41673 u32 nSubRec; /* Number of records written to sub-journal */
41674 Bitvec *pInJournal; /* One bit for each page in the database file */
41675 sqlite3_file *fd; /* File descriptor for database */
41676 sqlite3_file *jfd; /* File descriptor for main journal */
41677 sqlite3_file *sjfd; /* File descriptor for sub-journal */
41678 i64 journalOff; /* Current write offset in the journal file */
41679 i64 journalHdr; /* Byte offset to previous journal header */
41680 sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
41681 PagerSavepoint *aSavepoint; /* Array of active savepoints */
41682 int nSavepoint; /* Number of elements in aSavepoint[] */
41683 char dbFileVers[16]; /* Changes whenever database file changes */
41685 u8 bUseFetch; /* True to use xFetch() */
41686 int nMmapOut; /* Number of mmap pages currently outstanding */
41687 sqlite3_int64 szMmap; /* Desired maximum mmap size */
41688 PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
41690 ** End of the routinely-changing class members
41691 ***************************************************************************/
41693 u16 nExtra; /* Add this many bytes to each in-memory page */
41694 i16 nReserve; /* Number of unused bytes at end of each page */
41695 u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
41696 u32 sectorSize; /* Assumed sector size during rollback */
41697 int pageSize; /* Number of bytes in a page */
41698 Pgno mxPgno; /* Maximum allowed size of the database */
41699 i64 journalSizeLimit; /* Size limit for persistent journal files */
41700 char *zFilename; /* Name of the database file */
41701 char *zJournal; /* Name of the journal file */
41702 int (*xBusyHandler)(void*); /* Function to call when busy */
41703 void *pBusyHandlerArg; /* Context argument for xBusyHandler */
41704 int aStat[3]; /* Total cache hits, misses and writes */
41705 #ifdef SQLITE_TEST
41706 int nRead; /* Database pages read */
41707 #endif
41708 void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
41709 #ifdef SQLITE_HAS_CODEC
41710 void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
41711 void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
41712 void (*xCodecFree)(void*); /* Destructor for the codec */
41713 void *pCodec; /* First argument to xCodec... methods */
41714 #endif
41715 char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
41716 PCache *pPCache; /* Pointer to page cache object */
41717 #ifndef SQLITE_OMIT_WAL
41718 Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
41719 char *zWal; /* File name for write-ahead log */
41720 #endif
41724 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
41725 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
41726 ** or CACHE_WRITE to sqlite3_db_status().
41728 #define PAGER_STAT_HIT 0
41729 #define PAGER_STAT_MISS 1
41730 #define PAGER_STAT_WRITE 2
41733 ** The following global variables hold counters used for
41734 ** testing purposes only. These variables do not exist in
41735 ** a non-testing build. These variables are not thread-safe.
41737 #ifdef SQLITE_TEST
41738 SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
41739 SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
41740 SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
41741 # define PAGER_INCR(v) v++
41742 #else
41743 # define PAGER_INCR(v)
41744 #endif
41749 ** Journal files begin with the following magic string. The data
41750 ** was obtained from /dev/random. It is used only as a sanity check.
41752 ** Since version 2.8.0, the journal format contains additional sanity
41753 ** checking information. If the power fails while the journal is being
41754 ** written, semi-random garbage data might appear in the journal
41755 ** file after power is restored. If an attempt is then made
41756 ** to roll the journal back, the database could be corrupted. The additional
41757 ** sanity checking data is an attempt to discover the garbage in the
41758 ** journal and ignore it.
41760 ** The sanity checking information for the new journal format consists
41761 ** of a 32-bit checksum on each page of data. The checksum covers both
41762 ** the page number and the pPager->pageSize bytes of data for the page.
41763 ** This cksum is initialized to a 32-bit random value that appears in the
41764 ** journal file right after the header. The random initializer is important,
41765 ** because garbage data that appears at the end of a journal is likely
41766 ** data that was once in other files that have now been deleted. If the
41767 ** garbage data came from an obsolete journal file, the checksums might
41768 ** be correct. But by initializing the checksum to random value which
41769 ** is different for every journal, we minimize that risk.
41771 static const unsigned char aJournalMagic[] = {
41772 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
41776 ** The size of the of each page record in the journal is given by
41777 ** the following macro.
41779 #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
41782 ** The journal header size for this pager. This is usually the same
41783 ** size as a single disk sector. See also setSectorSize().
41785 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
41788 ** The macro MEMDB is true if we are dealing with an in-memory database.
41789 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
41790 ** the value of MEMDB will be a constant and the compiler will optimize
41791 ** out code that would never execute.
41793 #ifdef SQLITE_OMIT_MEMORYDB
41794 # define MEMDB 0
41795 #else
41796 # define MEMDB pPager->memDb
41797 #endif
41800 ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
41801 ** interfaces to access the database using memory-mapped I/O.
41803 #if SQLITE_MAX_MMAP_SIZE>0
41804 # define USEFETCH(x) ((x)->bUseFetch)
41805 #else
41806 # define USEFETCH(x) 0
41807 #endif
41810 ** The maximum legal page number is (2^31 - 1).
41812 #define PAGER_MAX_PGNO 2147483647
41815 ** The argument to this macro is a file descriptor (type sqlite3_file*).
41816 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
41818 ** This is so that expressions can be written as:
41820 ** if( isOpen(pPager->jfd) ){ ...
41822 ** instead of
41824 ** if( pPager->jfd->pMethods ){ ...
41826 #define isOpen(pFd) ((pFd)->pMethods)
41829 ** Return true if this pager uses a write-ahead log instead of the usual
41830 ** rollback journal. Otherwise false.
41832 #ifndef SQLITE_OMIT_WAL
41833 static int pagerUseWal(Pager *pPager){
41834 return (pPager->pWal!=0);
41836 #else
41837 # define pagerUseWal(x) 0
41838 # define pagerRollbackWal(x) 0
41839 # define pagerWalFrames(v,w,x,y) 0
41840 # define pagerOpenWalIfPresent(z) SQLITE_OK
41841 # define pagerBeginReadTransaction(z) SQLITE_OK
41842 #endif
41844 #ifndef NDEBUG
41846 ** Usage:
41848 ** assert( assert_pager_state(pPager) );
41850 ** This function runs many asserts to try to find inconsistencies in
41851 ** the internal state of the Pager object.
41853 static int assert_pager_state(Pager *p){
41854 Pager *pPager = p;
41856 /* State must be valid. */
41857 assert( p->eState==PAGER_OPEN
41858 || p->eState==PAGER_READER
41859 || p->eState==PAGER_WRITER_LOCKED
41860 || p->eState==PAGER_WRITER_CACHEMOD
41861 || p->eState==PAGER_WRITER_DBMOD
41862 || p->eState==PAGER_WRITER_FINISHED
41863 || p->eState==PAGER_ERROR
41866 /* Regardless of the current state, a temp-file connection always behaves
41867 ** as if it has an exclusive lock on the database file. It never updates
41868 ** the change-counter field, so the changeCountDone flag is always set.
41870 assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
41871 assert( p->tempFile==0 || pPager->changeCountDone );
41873 /* If the useJournal flag is clear, the journal-mode must be "OFF".
41874 ** And if the journal-mode is "OFF", the journal file must not be open.
41876 assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
41877 assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
41879 /* Check that MEMDB implies noSync. And an in-memory journal. Since
41880 ** this means an in-memory pager performs no IO at all, it cannot encounter
41881 ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
41882 ** a journal file. (although the in-memory journal implementation may
41883 ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
41884 ** is therefore not possible for an in-memory pager to enter the ERROR
41885 ** state.
41887 if( MEMDB ){
41888 assert( p->noSync );
41889 assert( p->journalMode==PAGER_JOURNALMODE_OFF
41890 || p->journalMode==PAGER_JOURNALMODE_MEMORY
41892 assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
41893 assert( pagerUseWal(p)==0 );
41896 /* If changeCountDone is set, a RESERVED lock or greater must be held
41897 ** on the file.
41899 assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
41900 assert( p->eLock!=PENDING_LOCK );
41902 switch( p->eState ){
41903 case PAGER_OPEN:
41904 assert( !MEMDB );
41905 assert( pPager->errCode==SQLITE_OK );
41906 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
41907 break;
41909 case PAGER_READER:
41910 assert( pPager->errCode==SQLITE_OK );
41911 assert( p->eLock!=UNKNOWN_LOCK );
41912 assert( p->eLock>=SHARED_LOCK );
41913 break;
41915 case PAGER_WRITER_LOCKED:
41916 assert( p->eLock!=UNKNOWN_LOCK );
41917 assert( pPager->errCode==SQLITE_OK );
41918 if( !pagerUseWal(pPager) ){
41919 assert( p->eLock>=RESERVED_LOCK );
41921 assert( pPager->dbSize==pPager->dbOrigSize );
41922 assert( pPager->dbOrigSize==pPager->dbFileSize );
41923 assert( pPager->dbOrigSize==pPager->dbHintSize );
41924 assert( pPager->setMaster==0 );
41925 break;
41927 case PAGER_WRITER_CACHEMOD:
41928 assert( p->eLock!=UNKNOWN_LOCK );
41929 assert( pPager->errCode==SQLITE_OK );
41930 if( !pagerUseWal(pPager) ){
41931 /* It is possible that if journal_mode=wal here that neither the
41932 ** journal file nor the WAL file are open. This happens during
41933 ** a rollback transaction that switches from journal_mode=off
41934 ** to journal_mode=wal.
41936 assert( p->eLock>=RESERVED_LOCK );
41937 assert( isOpen(p->jfd)
41938 || p->journalMode==PAGER_JOURNALMODE_OFF
41939 || p->journalMode==PAGER_JOURNALMODE_WAL
41942 assert( pPager->dbOrigSize==pPager->dbFileSize );
41943 assert( pPager->dbOrigSize==pPager->dbHintSize );
41944 break;
41946 case PAGER_WRITER_DBMOD:
41947 assert( p->eLock==EXCLUSIVE_LOCK );
41948 assert( pPager->errCode==SQLITE_OK );
41949 assert( !pagerUseWal(pPager) );
41950 assert( p->eLock>=EXCLUSIVE_LOCK );
41951 assert( isOpen(p->jfd)
41952 || p->journalMode==PAGER_JOURNALMODE_OFF
41953 || p->journalMode==PAGER_JOURNALMODE_WAL
41955 assert( pPager->dbOrigSize<=pPager->dbHintSize );
41956 break;
41958 case PAGER_WRITER_FINISHED:
41959 assert( p->eLock==EXCLUSIVE_LOCK );
41960 assert( pPager->errCode==SQLITE_OK );
41961 assert( !pagerUseWal(pPager) );
41962 assert( isOpen(p->jfd)
41963 || p->journalMode==PAGER_JOURNALMODE_OFF
41964 || p->journalMode==PAGER_JOURNALMODE_WAL
41966 break;
41968 case PAGER_ERROR:
41969 /* There must be at least one outstanding reference to the pager if
41970 ** in ERROR state. Otherwise the pager should have already dropped
41971 ** back to OPEN state.
41973 assert( pPager->errCode!=SQLITE_OK );
41974 assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
41975 break;
41978 return 1;
41980 #endif /* ifndef NDEBUG */
41982 #ifdef SQLITE_DEBUG
41984 ** Return a pointer to a human readable string in a static buffer
41985 ** containing the state of the Pager object passed as an argument. This
41986 ** is intended to be used within debuggers. For example, as an alternative
41987 ** to "print *pPager" in gdb:
41989 ** (gdb) printf "%s", print_pager_state(pPager)
41991 static char *print_pager_state(Pager *p){
41992 static char zRet[1024];
41994 sqlite3_snprintf(1024, zRet,
41995 "Filename: %s\n"
41996 "State: %s errCode=%d\n"
41997 "Lock: %s\n"
41998 "Locking mode: locking_mode=%s\n"
41999 "Journal mode: journal_mode=%s\n"
42000 "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
42001 "Journal: journalOff=%lld journalHdr=%lld\n"
42002 "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
42003 , p->zFilename
42004 , p->eState==PAGER_OPEN ? "OPEN" :
42005 p->eState==PAGER_READER ? "READER" :
42006 p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
42007 p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
42008 p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
42009 p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
42010 p->eState==PAGER_ERROR ? "ERROR" : "?error?"
42011 , (int)p->errCode
42012 , p->eLock==NO_LOCK ? "NO_LOCK" :
42013 p->eLock==RESERVED_LOCK ? "RESERVED" :
42014 p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
42015 p->eLock==SHARED_LOCK ? "SHARED" :
42016 p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
42017 , p->exclusiveMode ? "exclusive" : "normal"
42018 , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
42019 p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
42020 p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
42021 p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
42022 p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
42023 p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
42024 , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
42025 , p->journalOff, p->journalHdr
42026 , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
42029 return zRet;
42031 #endif
42034 ** Return true if it is necessary to write page *pPg into the sub-journal.
42035 ** A page needs to be written into the sub-journal if there exists one
42036 ** or more open savepoints for which:
42038 ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
42039 ** * The bit corresponding to the page-number is not set in
42040 ** PagerSavepoint.pInSavepoint.
42042 static int subjRequiresPage(PgHdr *pPg){
42043 Pager *pPager = pPg->pPager;
42044 PagerSavepoint *p;
42045 Pgno pgno = pPg->pgno;
42046 int i;
42047 for(i=0; i<pPager->nSavepoint; i++){
42048 p = &pPager->aSavepoint[i];
42049 if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
42050 return 1;
42053 return 0;
42057 ** Return true if the page is already in the journal file.
42059 static int pageInJournal(Pager *pPager, PgHdr *pPg){
42060 return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
42064 ** Read a 32-bit integer from the given file descriptor. Store the integer
42065 ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
42066 ** error code is something goes wrong.
42068 ** All values are stored on disk as big-endian.
42070 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
42071 unsigned char ac[4];
42072 int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
42073 if( rc==SQLITE_OK ){
42074 *pRes = sqlite3Get4byte(ac);
42076 return rc;
42080 ** Write a 32-bit integer into a string buffer in big-endian byte order.
42082 #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
42086 ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
42087 ** on success or an error code is something goes wrong.
42089 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
42090 char ac[4];
42091 put32bits(ac, val);
42092 return sqlite3OsWrite(fd, ac, 4, offset);
42096 ** Unlock the database file to level eLock, which must be either NO_LOCK
42097 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
42098 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
42100 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
42101 ** called, do not modify it. See the comment above the #define of
42102 ** UNKNOWN_LOCK for an explanation of this.
42104 static int pagerUnlockDb(Pager *pPager, int eLock){
42105 int rc = SQLITE_OK;
42107 assert( !pPager->exclusiveMode || pPager->eLock==eLock );
42108 assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
42109 assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
42110 if( isOpen(pPager->fd) ){
42111 assert( pPager->eLock>=eLock );
42112 rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
42113 if( pPager->eLock!=UNKNOWN_LOCK ){
42114 pPager->eLock = (u8)eLock;
42116 IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
42118 return rc;
42122 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
42123 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
42124 ** Pager.eLock variable to the new locking state.
42126 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
42127 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
42128 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
42129 ** of this.
42131 static int pagerLockDb(Pager *pPager, int eLock){
42132 int rc = SQLITE_OK;
42134 assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
42135 if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
42136 rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
42137 if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
42138 pPager->eLock = (u8)eLock;
42139 IOTRACE(("LOCK %p %d\n", pPager, eLock))
42142 return rc;
42146 ** This function determines whether or not the atomic-write optimization
42147 ** can be used with this pager. The optimization can be used if:
42149 ** (a) the value returned by OsDeviceCharacteristics() indicates that
42150 ** a database page may be written atomically, and
42151 ** (b) the value returned by OsSectorSize() is less than or equal
42152 ** to the page size.
42154 ** The optimization is also always enabled for temporary files. It is
42155 ** an error to call this function if pPager is opened on an in-memory
42156 ** database.
42158 ** If the optimization cannot be used, 0 is returned. If it can be used,
42159 ** then the value returned is the size of the journal file when it
42160 ** contains rollback data for exactly one page.
42162 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
42163 static int jrnlBufferSize(Pager *pPager){
42164 assert( !MEMDB );
42165 if( !pPager->tempFile ){
42166 int dc; /* Device characteristics */
42167 int nSector; /* Sector size */
42168 int szPage; /* Page size */
42170 assert( isOpen(pPager->fd) );
42171 dc = sqlite3OsDeviceCharacteristics(pPager->fd);
42172 nSector = pPager->sectorSize;
42173 szPage = pPager->pageSize;
42175 assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
42176 assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
42177 if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
42178 return 0;
42182 return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
42184 #endif
42187 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
42188 ** on the cache using a hash function. This is used for testing
42189 ** and debugging only.
42191 #ifdef SQLITE_CHECK_PAGES
42193 ** Return a 32-bit hash of the page data for pPage.
42195 static u32 pager_datahash(int nByte, unsigned char *pData){
42196 u32 hash = 0;
42197 int i;
42198 for(i=0; i<nByte; i++){
42199 hash = (hash*1039) + pData[i];
42201 return hash;
42203 static u32 pager_pagehash(PgHdr *pPage){
42204 return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
42206 static void pager_set_pagehash(PgHdr *pPage){
42207 pPage->pageHash = pager_pagehash(pPage);
42211 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
42212 ** is defined, and NDEBUG is not defined, an assert() statement checks
42213 ** that the page is either dirty or still matches the calculated page-hash.
42215 #define CHECK_PAGE(x) checkPage(x)
42216 static void checkPage(PgHdr *pPg){
42217 Pager *pPager = pPg->pPager;
42218 assert( pPager->eState!=PAGER_ERROR );
42219 assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
42222 #else
42223 #define pager_datahash(X,Y) 0
42224 #define pager_pagehash(X) 0
42225 #define pager_set_pagehash(X)
42226 #define CHECK_PAGE(x)
42227 #endif /* SQLITE_CHECK_PAGES */
42230 ** When this is called the journal file for pager pPager must be open.
42231 ** This function attempts to read a master journal file name from the
42232 ** end of the file and, if successful, copies it into memory supplied
42233 ** by the caller. See comments above writeMasterJournal() for the format
42234 ** used to store a master journal file name at the end of a journal file.
42236 ** zMaster must point to a buffer of at least nMaster bytes allocated by
42237 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
42238 ** enough space to write the master journal name). If the master journal
42239 ** name in the journal is longer than nMaster bytes (including a
42240 ** nul-terminator), then this is handled as if no master journal name
42241 ** were present in the journal.
42243 ** If a master journal file name is present at the end of the journal
42244 ** file, then it is copied into the buffer pointed to by zMaster. A
42245 ** nul-terminator byte is appended to the buffer following the master
42246 ** journal file name.
42248 ** If it is determined that no master journal file name is present
42249 ** zMaster[0] is set to 0 and SQLITE_OK returned.
42251 ** If an error occurs while reading from the journal file, an SQLite
42252 ** error code is returned.
42254 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
42255 int rc; /* Return code */
42256 u32 len; /* Length in bytes of master journal name */
42257 i64 szJ; /* Total size in bytes of journal file pJrnl */
42258 u32 cksum; /* MJ checksum value read from journal */
42259 u32 u; /* Unsigned loop counter */
42260 unsigned char aMagic[8]; /* A buffer to hold the magic header */
42261 zMaster[0] = '\0';
42263 if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
42264 || szJ<16
42265 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
42266 || len>=nMaster
42267 || len==0
42268 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
42269 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
42270 || memcmp(aMagic, aJournalMagic, 8)
42271 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
42273 return rc;
42276 /* See if the checksum matches the master journal name */
42277 for(u=0; u<len; u++){
42278 cksum -= zMaster[u];
42280 if( cksum ){
42281 /* If the checksum doesn't add up, then one or more of the disk sectors
42282 ** containing the master journal filename is corrupted. This means
42283 ** definitely roll back, so just return SQLITE_OK and report a (nul)
42284 ** master-journal filename.
42286 len = 0;
42288 zMaster[len] = '\0';
42290 return SQLITE_OK;
42294 ** Return the offset of the sector boundary at or immediately
42295 ** following the value in pPager->journalOff, assuming a sector
42296 ** size of pPager->sectorSize bytes.
42298 ** i.e for a sector size of 512:
42300 ** Pager.journalOff Return value
42301 ** ---------------------------------------
42302 ** 0 0
42303 ** 512 512
42304 ** 100 512
42305 ** 2000 2048
42308 static i64 journalHdrOffset(Pager *pPager){
42309 i64 offset = 0;
42310 i64 c = pPager->journalOff;
42311 if( c ){
42312 offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
42314 assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
42315 assert( offset>=c );
42316 assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
42317 return offset;
42321 ** The journal file must be open when this function is called.
42323 ** This function is a no-op if the journal file has not been written to
42324 ** within the current transaction (i.e. if Pager.journalOff==0).
42326 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
42327 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
42328 ** zero the 28-byte header at the start of the journal file. In either case,
42329 ** if the pager is not in no-sync mode, sync the journal file immediately
42330 ** after writing or truncating it.
42332 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
42333 ** following the truncation or zeroing described above the size of the
42334 ** journal file in bytes is larger than this value, then truncate the
42335 ** journal file to Pager.journalSizeLimit bytes. The journal file does
42336 ** not need to be synced following this operation.
42338 ** If an IO error occurs, abandon processing and return the IO error code.
42339 ** Otherwise, return SQLITE_OK.
42341 static int zeroJournalHdr(Pager *pPager, int doTruncate){
42342 int rc = SQLITE_OK; /* Return code */
42343 assert( isOpen(pPager->jfd) );
42344 if( pPager->journalOff ){
42345 const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
42347 IOTRACE(("JZEROHDR %p\n", pPager))
42348 if( doTruncate || iLimit==0 ){
42349 rc = sqlite3OsTruncate(pPager->jfd, 0);
42350 }else{
42351 static const char zeroHdr[28] = {0};
42352 rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
42354 if( rc==SQLITE_OK && !pPager->noSync ){
42355 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
42358 /* At this point the transaction is committed but the write lock
42359 ** is still held on the file. If there is a size limit configured for
42360 ** the persistent journal and the journal file currently consumes more
42361 ** space than that limit allows for, truncate it now. There is no need
42362 ** to sync the file following this operation.
42364 if( rc==SQLITE_OK && iLimit>0 ){
42365 i64 sz;
42366 rc = sqlite3OsFileSize(pPager->jfd, &sz);
42367 if( rc==SQLITE_OK && sz>iLimit ){
42368 rc = sqlite3OsTruncate(pPager->jfd, iLimit);
42372 return rc;
42376 ** The journal file must be open when this routine is called. A journal
42377 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
42378 ** current location.
42380 ** The format for the journal header is as follows:
42381 ** - 8 bytes: Magic identifying journal format.
42382 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
42383 ** - 4 bytes: Random number used for page hash.
42384 ** - 4 bytes: Initial database page count.
42385 ** - 4 bytes: Sector size used by the process that wrote this journal.
42386 ** - 4 bytes: Database page size.
42388 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
42390 static int writeJournalHdr(Pager *pPager){
42391 int rc = SQLITE_OK; /* Return code */
42392 char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
42393 u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
42394 u32 nWrite; /* Bytes of header sector written */
42395 int ii; /* Loop counter */
42397 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
42399 if( nHeader>JOURNAL_HDR_SZ(pPager) ){
42400 nHeader = JOURNAL_HDR_SZ(pPager);
42403 /* If there are active savepoints and any of them were created
42404 ** since the most recent journal header was written, update the
42405 ** PagerSavepoint.iHdrOffset fields now.
42407 for(ii=0; ii<pPager->nSavepoint; ii++){
42408 if( pPager->aSavepoint[ii].iHdrOffset==0 ){
42409 pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
42413 pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
42416 ** Write the nRec Field - the number of page records that follow this
42417 ** journal header. Normally, zero is written to this value at this time.
42418 ** After the records are added to the journal (and the journal synced,
42419 ** if in full-sync mode), the zero is overwritten with the true number
42420 ** of records (see syncJournal()).
42422 ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
42423 ** reading the journal this value tells SQLite to assume that the
42424 ** rest of the journal file contains valid page records. This assumption
42425 ** is dangerous, as if a failure occurred whilst writing to the journal
42426 ** file it may contain some garbage data. There are two scenarios
42427 ** where this risk can be ignored:
42429 ** * When the pager is in no-sync mode. Corruption can follow a
42430 ** power failure in this case anyway.
42432 ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
42433 ** that garbage data is never appended to the journal file.
42435 assert( isOpen(pPager->fd) || pPager->noSync );
42436 if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
42437 || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
42439 memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
42440 put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
42441 }else{
42442 memset(zHeader, 0, sizeof(aJournalMagic)+4);
42445 /* The random check-hash initializer */
42446 sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
42447 put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
42448 /* The initial database size */
42449 put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
42450 /* The assumed sector size for this process */
42451 put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
42453 /* The page size */
42454 put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
42456 /* Initializing the tail of the buffer is not necessary. Everything
42457 ** works find if the following memset() is omitted. But initializing
42458 ** the memory prevents valgrind from complaining, so we are willing to
42459 ** take the performance hit.
42461 memset(&zHeader[sizeof(aJournalMagic)+20], 0,
42462 nHeader-(sizeof(aJournalMagic)+20));
42464 /* In theory, it is only necessary to write the 28 bytes that the
42465 ** journal header consumes to the journal file here. Then increment the
42466 ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
42467 ** record is written to the following sector (leaving a gap in the file
42468 ** that will be implicitly filled in by the OS).
42470 ** However it has been discovered that on some systems this pattern can
42471 ** be significantly slower than contiguously writing data to the file,
42472 ** even if that means explicitly writing data to the block of
42473 ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
42474 ** is done.
42476 ** The loop is required here in case the sector-size is larger than the
42477 ** database page size. Since the zHeader buffer is only Pager.pageSize
42478 ** bytes in size, more than one call to sqlite3OsWrite() may be required
42479 ** to populate the entire journal header sector.
42481 for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
42482 IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
42483 rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
42484 assert( pPager->journalHdr <= pPager->journalOff );
42485 pPager->journalOff += nHeader;
42488 return rc;
42492 ** The journal file must be open when this is called. A journal header file
42493 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
42494 ** file. The current location in the journal file is given by
42495 ** pPager->journalOff. See comments above function writeJournalHdr() for
42496 ** a description of the journal header format.
42498 ** If the header is read successfully, *pNRec is set to the number of
42499 ** page records following this header and *pDbSize is set to the size of the
42500 ** database before the transaction began, in pages. Also, pPager->cksumInit
42501 ** is set to the value read from the journal header. SQLITE_OK is returned
42502 ** in this case.
42504 ** If the journal header file appears to be corrupted, SQLITE_DONE is
42505 ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
42506 ** cannot be read from the journal file an error code is returned.
42508 static int readJournalHdr(
42509 Pager *pPager, /* Pager object */
42510 int isHot,
42511 i64 journalSize, /* Size of the open journal file in bytes */
42512 u32 *pNRec, /* OUT: Value read from the nRec field */
42513 u32 *pDbSize /* OUT: Value of original database size field */
42515 int rc; /* Return code */
42516 unsigned char aMagic[8]; /* A buffer to hold the magic header */
42517 i64 iHdrOff; /* Offset of journal header being read */
42519 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
42521 /* Advance Pager.journalOff to the start of the next sector. If the
42522 ** journal file is too small for there to be a header stored at this
42523 ** point, return SQLITE_DONE.
42525 pPager->journalOff = journalHdrOffset(pPager);
42526 if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
42527 return SQLITE_DONE;
42529 iHdrOff = pPager->journalOff;
42531 /* Read in the first 8 bytes of the journal header. If they do not match
42532 ** the magic string found at the start of each journal header, return
42533 ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
42534 ** proceed.
42536 if( isHot || iHdrOff!=pPager->journalHdr ){
42537 rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
42538 if( rc ){
42539 return rc;
42541 if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
42542 return SQLITE_DONE;
42546 /* Read the first three 32-bit fields of the journal header: The nRec
42547 ** field, the checksum-initializer and the database size at the start
42548 ** of the transaction. Return an error code if anything goes wrong.
42550 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
42551 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
42552 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
42554 return rc;
42557 if( pPager->journalOff==0 ){
42558 u32 iPageSize; /* Page-size field of journal header */
42559 u32 iSectorSize; /* Sector-size field of journal header */
42561 /* Read the page-size and sector-size journal header fields. */
42562 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
42563 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
42565 return rc;
42568 /* Versions of SQLite prior to 3.5.8 set the page-size field of the
42569 ** journal header to zero. In this case, assume that the Pager.pageSize
42570 ** variable is already set to the correct page size.
42572 if( iPageSize==0 ){
42573 iPageSize = pPager->pageSize;
42576 /* Check that the values read from the page-size and sector-size fields
42577 ** are within range. To be 'in range', both values need to be a power
42578 ** of two greater than or equal to 512 or 32, and not greater than their
42579 ** respective compile time maximum limits.
42581 if( iPageSize<512 || iSectorSize<32
42582 || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
42583 || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
42585 /* If the either the page-size or sector-size in the journal-header is
42586 ** invalid, then the process that wrote the journal-header must have
42587 ** crashed before the header was synced. In this case stop reading
42588 ** the journal file here.
42590 return SQLITE_DONE;
42593 /* Update the page-size to match the value read from the journal.
42594 ** Use a testcase() macro to make sure that malloc failure within
42595 ** PagerSetPagesize() is tested.
42597 rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
42598 testcase( rc!=SQLITE_OK );
42600 /* Update the assumed sector-size to match the value used by
42601 ** the process that created this journal. If this journal was
42602 ** created by a process other than this one, then this routine
42603 ** is being called from within pager_playback(). The local value
42604 ** of Pager.sectorSize is restored at the end of that routine.
42606 pPager->sectorSize = iSectorSize;
42609 pPager->journalOff += JOURNAL_HDR_SZ(pPager);
42610 return rc;
42615 ** Write the supplied master journal name into the journal file for pager
42616 ** pPager at the current location. The master journal name must be the last
42617 ** thing written to a journal file. If the pager is in full-sync mode, the
42618 ** journal file descriptor is advanced to the next sector boundary before
42619 ** anything is written. The format is:
42621 ** + 4 bytes: PAGER_MJ_PGNO.
42622 ** + N bytes: Master journal filename in utf-8.
42623 ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
42624 ** + 4 bytes: Master journal name checksum.
42625 ** + 8 bytes: aJournalMagic[].
42627 ** The master journal page checksum is the sum of the bytes in the master
42628 ** journal name, where each byte is interpreted as a signed 8-bit integer.
42630 ** If zMaster is a NULL pointer (occurs for a single database transaction),
42631 ** this call is a no-op.
42633 static int writeMasterJournal(Pager *pPager, const char *zMaster){
42634 int rc; /* Return code */
42635 int nMaster; /* Length of string zMaster */
42636 i64 iHdrOff; /* Offset of header in journal file */
42637 i64 jrnlSize; /* Size of journal file on disk */
42638 u32 cksum = 0; /* Checksum of string zMaster */
42640 assert( pPager->setMaster==0 );
42641 assert( !pagerUseWal(pPager) );
42643 if( !zMaster
42644 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
42645 || !isOpen(pPager->jfd)
42647 return SQLITE_OK;
42649 pPager->setMaster = 1;
42650 assert( pPager->journalHdr <= pPager->journalOff );
42652 /* Calculate the length in bytes and the checksum of zMaster */
42653 for(nMaster=0; zMaster[nMaster]; nMaster++){
42654 cksum += zMaster[nMaster];
42657 /* If in full-sync mode, advance to the next disk sector before writing
42658 ** the master journal name. This is in case the previous page written to
42659 ** the journal has already been synced.
42661 if( pPager->fullSync ){
42662 pPager->journalOff = journalHdrOffset(pPager);
42664 iHdrOff = pPager->journalOff;
42666 /* Write the master journal data to the end of the journal file. If
42667 ** an error occurs, return the error code to the caller.
42669 if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
42670 || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
42671 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
42672 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
42673 || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
42675 return rc;
42677 pPager->journalOff += (nMaster+20);
42679 /* If the pager is in peristent-journal mode, then the physical
42680 ** journal-file may extend past the end of the master-journal name
42681 ** and 8 bytes of magic data just written to the file. This is
42682 ** dangerous because the code to rollback a hot-journal file
42683 ** will not be able to find the master-journal name to determine
42684 ** whether or not the journal is hot.
42686 ** Easiest thing to do in this scenario is to truncate the journal
42687 ** file to the required size.
42689 if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
42690 && jrnlSize>pPager->journalOff
42692 rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
42694 return rc;
42698 ** Discard the entire contents of the in-memory page-cache.
42700 static void pager_reset(Pager *pPager){
42701 sqlite3BackupRestart(pPager->pBackup);
42702 sqlite3PcacheClear(pPager->pPCache);
42706 ** Free all structures in the Pager.aSavepoint[] array and set both
42707 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
42708 ** if it is open and the pager is not in exclusive mode.
42710 static void releaseAllSavepoints(Pager *pPager){
42711 int ii; /* Iterator for looping through Pager.aSavepoint */
42712 for(ii=0; ii<pPager->nSavepoint; ii++){
42713 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
42715 if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
42716 sqlite3OsClose(pPager->sjfd);
42718 sqlite3_free(pPager->aSavepoint);
42719 pPager->aSavepoint = 0;
42720 pPager->nSavepoint = 0;
42721 pPager->nSubRec = 0;
42725 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
42726 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
42727 ** or SQLITE_NOMEM if a malloc failure occurs.
42729 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
42730 int ii; /* Loop counter */
42731 int rc = SQLITE_OK; /* Result code */
42733 for(ii=0; ii<pPager->nSavepoint; ii++){
42734 PagerSavepoint *p = &pPager->aSavepoint[ii];
42735 if( pgno<=p->nOrig ){
42736 rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
42737 testcase( rc==SQLITE_NOMEM );
42738 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
42741 return rc;
42745 ** This function is a no-op if the pager is in exclusive mode and not
42746 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
42747 ** state.
42749 ** If the pager is not in exclusive-access mode, the database file is
42750 ** completely unlocked. If the file is unlocked and the file-system does
42751 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
42752 ** closed (if it is open).
42754 ** If the pager is in ERROR state when this function is called, the
42755 ** contents of the pager cache are discarded before switching back to
42756 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
42757 ** or not, any journal file left in the file-system will be treated
42758 ** as a hot-journal and rolled back the next time a read-transaction
42759 ** is opened (by this or by any other connection).
42761 static void pager_unlock(Pager *pPager){
42763 assert( pPager->eState==PAGER_READER
42764 || pPager->eState==PAGER_OPEN
42765 || pPager->eState==PAGER_ERROR
42768 sqlite3BitvecDestroy(pPager->pInJournal);
42769 pPager->pInJournal = 0;
42770 releaseAllSavepoints(pPager);
42772 if( pagerUseWal(pPager) ){
42773 assert( !isOpen(pPager->jfd) );
42774 sqlite3WalEndReadTransaction(pPager->pWal);
42775 pPager->eState = PAGER_OPEN;
42776 }else if( !pPager->exclusiveMode ){
42777 int rc; /* Error code returned by pagerUnlockDb() */
42778 int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
42780 /* If the operating system support deletion of open files, then
42781 ** close the journal file when dropping the database lock. Otherwise
42782 ** another connection with journal_mode=delete might delete the file
42783 ** out from under us.
42785 assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
42786 assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
42787 assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
42788 assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
42789 assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
42790 assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
42791 if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
42792 || 1!=(pPager->journalMode & 5)
42794 sqlite3OsClose(pPager->jfd);
42797 /* If the pager is in the ERROR state and the call to unlock the database
42798 ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
42799 ** above the #define for UNKNOWN_LOCK for an explanation of why this
42800 ** is necessary.
42802 rc = pagerUnlockDb(pPager, NO_LOCK);
42803 if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
42804 pPager->eLock = UNKNOWN_LOCK;
42807 /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
42808 ** without clearing the error code. This is intentional - the error
42809 ** code is cleared and the cache reset in the block below.
42811 assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
42812 pPager->changeCountDone = 0;
42813 pPager->eState = PAGER_OPEN;
42816 /* If Pager.errCode is set, the contents of the pager cache cannot be
42817 ** trusted. Now that there are no outstanding references to the pager,
42818 ** it can safely move back to PAGER_OPEN state. This happens in both
42819 ** normal and exclusive-locking mode.
42821 if( pPager->errCode ){
42822 assert( !MEMDB );
42823 pager_reset(pPager);
42824 pPager->changeCountDone = pPager->tempFile;
42825 pPager->eState = PAGER_OPEN;
42826 pPager->errCode = SQLITE_OK;
42827 if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
42830 pPager->journalOff = 0;
42831 pPager->journalHdr = 0;
42832 pPager->setMaster = 0;
42836 ** This function is called whenever an IOERR or FULL error that requires
42837 ** the pager to transition into the ERROR state may ahve occurred.
42838 ** The first argument is a pointer to the pager structure, the second
42839 ** the error-code about to be returned by a pager API function. The
42840 ** value returned is a copy of the second argument to this function.
42842 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
42843 ** IOERR sub-codes, the pager enters the ERROR state and the error code
42844 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
42845 ** all major API calls on the Pager will immediately return Pager.errCode.
42847 ** The ERROR state indicates that the contents of the pager-cache
42848 ** cannot be trusted. This state can be cleared by completely discarding
42849 ** the contents of the pager-cache. If a transaction was active when
42850 ** the persistent error occurred, then the rollback journal may need
42851 ** to be replayed to restore the contents of the database file (as if
42852 ** it were a hot-journal).
42854 static int pager_error(Pager *pPager, int rc){
42855 int rc2 = rc & 0xff;
42856 assert( rc==SQLITE_OK || !MEMDB );
42857 assert(
42858 pPager->errCode==SQLITE_FULL ||
42859 pPager->errCode==SQLITE_OK ||
42860 (pPager->errCode & 0xff)==SQLITE_IOERR
42862 if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
42863 pPager->errCode = rc;
42864 pPager->eState = PAGER_ERROR;
42866 return rc;
42869 static int pager_truncate(Pager *pPager, Pgno nPage);
42872 ** This routine ends a transaction. A transaction is usually ended by
42873 ** either a COMMIT or a ROLLBACK operation. This routine may be called
42874 ** after rollback of a hot-journal, or if an error occurs while opening
42875 ** the journal file or writing the very first journal-header of a
42876 ** database transaction.
42878 ** This routine is never called in PAGER_ERROR state. If it is called
42879 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
42880 ** exclusive than a RESERVED lock, it is a no-op.
42882 ** Otherwise, any active savepoints are released.
42884 ** If the journal file is open, then it is "finalized". Once a journal
42885 ** file has been finalized it is not possible to use it to roll back a
42886 ** transaction. Nor will it be considered to be a hot-journal by this
42887 ** or any other database connection. Exactly how a journal is finalized
42888 ** depends on whether or not the pager is running in exclusive mode and
42889 ** the current journal-mode (Pager.journalMode value), as follows:
42891 ** journalMode==MEMORY
42892 ** Journal file descriptor is simply closed. This destroys an
42893 ** in-memory journal.
42895 ** journalMode==TRUNCATE
42896 ** Journal file is truncated to zero bytes in size.
42898 ** journalMode==PERSIST
42899 ** The first 28 bytes of the journal file are zeroed. This invalidates
42900 ** the first journal header in the file, and hence the entire journal
42901 ** file. An invalid journal file cannot be rolled back.
42903 ** journalMode==DELETE
42904 ** The journal file is closed and deleted using sqlite3OsDelete().
42906 ** If the pager is running in exclusive mode, this method of finalizing
42907 ** the journal file is never used. Instead, if the journalMode is
42908 ** DELETE and the pager is in exclusive mode, the method described under
42909 ** journalMode==PERSIST is used instead.
42911 ** After the journal is finalized, the pager moves to PAGER_READER state.
42912 ** If running in non-exclusive rollback mode, the lock on the file is
42913 ** downgraded to a SHARED_LOCK.
42915 ** SQLITE_OK is returned if no error occurs. If an error occurs during
42916 ** any of the IO operations to finalize the journal file or unlock the
42917 ** database then the IO error code is returned to the user. If the
42918 ** operation to finalize the journal file fails, then the code still
42919 ** tries to unlock the database file if not in exclusive mode. If the
42920 ** unlock operation fails as well, then the first error code related
42921 ** to the first error encountered (the journal finalization one) is
42922 ** returned.
42924 static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
42925 int rc = SQLITE_OK; /* Error code from journal finalization operation */
42926 int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
42928 /* Do nothing if the pager does not have an open write transaction
42929 ** or at least a RESERVED lock. This function may be called when there
42930 ** is no write-transaction active but a RESERVED or greater lock is
42931 ** held under two circumstances:
42933 ** 1. After a successful hot-journal rollback, it is called with
42934 ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
42936 ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
42937 ** lock switches back to locking_mode=normal and then executes a
42938 ** read-transaction, this function is called with eState==PAGER_READER
42939 ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
42941 assert( assert_pager_state(pPager) );
42942 assert( pPager->eState!=PAGER_ERROR );
42943 if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
42944 return SQLITE_OK;
42947 releaseAllSavepoints(pPager);
42948 assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
42949 if( isOpen(pPager->jfd) ){
42950 assert( !pagerUseWal(pPager) );
42952 /* Finalize the journal file. */
42953 if( sqlite3IsMemJournal(pPager->jfd) ){
42954 assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
42955 sqlite3OsClose(pPager->jfd);
42956 }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
42957 if( pPager->journalOff==0 ){
42958 rc = SQLITE_OK;
42959 }else{
42960 rc = sqlite3OsTruncate(pPager->jfd, 0);
42961 if( rc==SQLITE_OK && pPager->fullSync ){
42962 /* Make sure the new file size is written into the inode right away.
42963 ** Otherwise the journal might resurrect following a power loss and
42964 ** cause the last transaction to roll back. See
42965 ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
42967 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
42970 pPager->journalOff = 0;
42971 }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
42972 || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
42974 rc = zeroJournalHdr(pPager, hasMaster);
42975 pPager->journalOff = 0;
42976 }else{
42977 /* This branch may be executed with Pager.journalMode==MEMORY if
42978 ** a hot-journal was just rolled back. In this case the journal
42979 ** file should be closed and deleted. If this connection writes to
42980 ** the database file, it will do so using an in-memory journal.
42982 int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
42983 assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
42984 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
42985 || pPager->journalMode==PAGER_JOURNALMODE_WAL
42987 sqlite3OsClose(pPager->jfd);
42988 if( bDelete ){
42989 rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
42994 #ifdef SQLITE_CHECK_PAGES
42995 sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
42996 if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
42997 PgHdr *p = sqlite3PagerLookup(pPager, 1);
42998 if( p ){
42999 p->pageHash = 0;
43000 sqlite3PagerUnrefNotNull(p);
43003 #endif
43005 sqlite3BitvecDestroy(pPager->pInJournal);
43006 pPager->pInJournal = 0;
43007 pPager->nRec = 0;
43008 sqlite3PcacheCleanAll(pPager->pPCache);
43009 sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
43011 if( pagerUseWal(pPager) ){
43012 /* Drop the WAL write-lock, if any. Also, if the connection was in
43013 ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
43014 ** lock held on the database file.
43016 rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
43017 assert( rc2==SQLITE_OK );
43018 }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
43019 /* This branch is taken when committing a transaction in rollback-journal
43020 ** mode if the database file on disk is larger than the database image.
43021 ** At this point the journal has been finalized and the transaction
43022 ** successfully committed, but the EXCLUSIVE lock is still held on the
43023 ** file. So it is safe to truncate the database file to its minimum
43024 ** required size. */
43025 assert( pPager->eLock==EXCLUSIVE_LOCK );
43026 rc = pager_truncate(pPager, pPager->dbSize);
43029 if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
43030 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
43031 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
43034 if( !pPager->exclusiveMode
43035 && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
43037 rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
43038 pPager->changeCountDone = 0;
43040 pPager->eState = PAGER_READER;
43041 pPager->setMaster = 0;
43043 return (rc==SQLITE_OK?rc2:rc);
43047 ** Execute a rollback if a transaction is active and unlock the
43048 ** database file.
43050 ** If the pager has already entered the ERROR state, do not attempt
43051 ** the rollback at this time. Instead, pager_unlock() is called. The
43052 ** call to pager_unlock() will discard all in-memory pages, unlock
43053 ** the database file and move the pager back to OPEN state. If this
43054 ** means that there is a hot-journal left in the file-system, the next
43055 ** connection to obtain a shared lock on the pager (which may be this one)
43056 ** will roll it back.
43058 ** If the pager has not already entered the ERROR state, but an IO or
43059 ** malloc error occurs during a rollback, then this will itself cause
43060 ** the pager to enter the ERROR state. Which will be cleared by the
43061 ** call to pager_unlock(), as described above.
43063 static void pagerUnlockAndRollback(Pager *pPager){
43064 if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
43065 assert( assert_pager_state(pPager) );
43066 if( pPager->eState>=PAGER_WRITER_LOCKED ){
43067 sqlite3BeginBenignMalloc();
43068 sqlite3PagerRollback(pPager);
43069 sqlite3EndBenignMalloc();
43070 }else if( !pPager->exclusiveMode ){
43071 assert( pPager->eState==PAGER_READER );
43072 pager_end_transaction(pPager, 0, 0);
43075 pager_unlock(pPager);
43079 ** Parameter aData must point to a buffer of pPager->pageSize bytes
43080 ** of data. Compute and return a checksum based ont the contents of the
43081 ** page of data and the current value of pPager->cksumInit.
43083 ** This is not a real checksum. It is really just the sum of the
43084 ** random initial value (pPager->cksumInit) and every 200th byte
43085 ** of the page data, starting with byte offset (pPager->pageSize%200).
43086 ** Each byte is interpreted as an 8-bit unsigned integer.
43088 ** Changing the formula used to compute this checksum results in an
43089 ** incompatible journal file format.
43091 ** If journal corruption occurs due to a power failure, the most likely
43092 ** scenario is that one end or the other of the record will be changed.
43093 ** It is much less likely that the two ends of the journal record will be
43094 ** correct and the middle be corrupt. Thus, this "checksum" scheme,
43095 ** though fast and simple, catches the mostly likely kind of corruption.
43097 static u32 pager_cksum(Pager *pPager, const u8 *aData){
43098 u32 cksum = pPager->cksumInit; /* Checksum value to return */
43099 int i = pPager->pageSize-200; /* Loop counter */
43100 while( i>0 ){
43101 cksum += aData[i];
43102 i -= 200;
43104 return cksum;
43108 ** Report the current page size and number of reserved bytes back
43109 ** to the codec.
43111 #ifdef SQLITE_HAS_CODEC
43112 static void pagerReportSize(Pager *pPager){
43113 if( pPager->xCodecSizeChng ){
43114 pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
43115 (int)pPager->nReserve);
43118 #else
43119 # define pagerReportSize(X) /* No-op if we do not support a codec */
43120 #endif
43123 ** Read a single page from either the journal file (if isMainJrnl==1) or
43124 ** from the sub-journal (if isMainJrnl==0) and playback that page.
43125 ** The page begins at offset *pOffset into the file. The *pOffset
43126 ** value is increased to the start of the next page in the journal.
43128 ** The main rollback journal uses checksums - the statement journal does
43129 ** not.
43131 ** If the page number of the page record read from the (sub-)journal file
43132 ** is greater than the current value of Pager.dbSize, then playback is
43133 ** skipped and SQLITE_OK is returned.
43135 ** If pDone is not NULL, then it is a record of pages that have already
43136 ** been played back. If the page at *pOffset has already been played back
43137 ** (if the corresponding pDone bit is set) then skip the playback.
43138 ** Make sure the pDone bit corresponding to the *pOffset page is set
43139 ** prior to returning.
43141 ** If the page record is successfully read from the (sub-)journal file
43142 ** and played back, then SQLITE_OK is returned. If an IO error occurs
43143 ** while reading the record from the (sub-)journal file or while writing
43144 ** to the database file, then the IO error code is returned. If data
43145 ** is successfully read from the (sub-)journal file but appears to be
43146 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
43147 ** two circumstances:
43149 ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
43150 ** * If the record is being rolled back from the main journal file
43151 ** and the checksum field does not match the record content.
43153 ** Neither of these two scenarios are possible during a savepoint rollback.
43155 ** If this is a savepoint rollback, then memory may have to be dynamically
43156 ** allocated by this function. If this is the case and an allocation fails,
43157 ** SQLITE_NOMEM is returned.
43159 static int pager_playback_one_page(
43160 Pager *pPager, /* The pager being played back */
43161 i64 *pOffset, /* Offset of record to playback */
43162 Bitvec *pDone, /* Bitvec of pages already played back */
43163 int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
43164 int isSavepnt /* True for a savepoint rollback */
43166 int rc;
43167 PgHdr *pPg; /* An existing page in the cache */
43168 Pgno pgno; /* The page number of a page in journal */
43169 u32 cksum; /* Checksum used for sanity checking */
43170 char *aData; /* Temporary storage for the page */
43171 sqlite3_file *jfd; /* The file descriptor for the journal file */
43172 int isSynced; /* True if journal page is synced */
43174 assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
43175 assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
43176 assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
43177 assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
43179 aData = pPager->pTmpSpace;
43180 assert( aData ); /* Temp storage must have already been allocated */
43181 assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
43183 /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
43184 ** or savepoint rollback done at the request of the caller) or this is
43185 ** a hot-journal rollback. If it is a hot-journal rollback, the pager
43186 ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
43187 ** only reads from the main journal, not the sub-journal.
43189 assert( pPager->eState>=PAGER_WRITER_CACHEMOD
43190 || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
43192 assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
43194 /* Read the page number and page data from the journal or sub-journal
43195 ** file. Return an error code to the caller if an IO error occurs.
43197 jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
43198 rc = read32bits(jfd, *pOffset, &pgno);
43199 if( rc!=SQLITE_OK ) return rc;
43200 rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
43201 if( rc!=SQLITE_OK ) return rc;
43202 *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
43204 /* Sanity checking on the page. This is more important that I originally
43205 ** thought. If a power failure occurs while the journal is being written,
43206 ** it could cause invalid data to be written into the journal. We need to
43207 ** detect this invalid data (with high probability) and ignore it.
43209 if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
43210 assert( !isSavepnt );
43211 return SQLITE_DONE;
43213 if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
43214 return SQLITE_OK;
43216 if( isMainJrnl ){
43217 rc = read32bits(jfd, (*pOffset)-4, &cksum);
43218 if( rc ) return rc;
43219 if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
43220 return SQLITE_DONE;
43224 /* If this page has already been played by before during the current
43225 ** rollback, then don't bother to play it back again.
43227 if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
43228 return rc;
43231 /* When playing back page 1, restore the nReserve setting
43233 if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
43234 pPager->nReserve = ((u8*)aData)[20];
43235 pagerReportSize(pPager);
43238 /* If the pager is in CACHEMOD state, then there must be a copy of this
43239 ** page in the pager cache. In this case just update the pager cache,
43240 ** not the database file. The page is left marked dirty in this case.
43242 ** An exception to the above rule: If the database is in no-sync mode
43243 ** and a page is moved during an incremental vacuum then the page may
43244 ** not be in the pager cache. Later: if a malloc() or IO error occurs
43245 ** during a Movepage() call, then the page may not be in the cache
43246 ** either. So the condition described in the above paragraph is not
43247 ** assert()able.
43249 ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
43250 ** pager cache if it exists and the main file. The page is then marked
43251 ** not dirty. Since this code is only executed in PAGER_OPEN state for
43252 ** a hot-journal rollback, it is guaranteed that the page-cache is empty
43253 ** if the pager is in OPEN state.
43255 ** Ticket #1171: The statement journal might contain page content that is
43256 ** different from the page content at the start of the transaction.
43257 ** This occurs when a page is changed prior to the start of a statement
43258 ** then changed again within the statement. When rolling back such a
43259 ** statement we must not write to the original database unless we know
43260 ** for certain that original page contents are synced into the main rollback
43261 ** journal. Otherwise, a power loss might leave modified data in the
43262 ** database file without an entry in the rollback journal that can
43263 ** restore the database to its original form. Two conditions must be
43264 ** met before writing to the database files. (1) the database must be
43265 ** locked. (2) we know that the original page content is fully synced
43266 ** in the main journal either because the page is not in cache or else
43267 ** the page is marked as needSync==0.
43269 ** 2008-04-14: When attempting to vacuum a corrupt database file, it
43270 ** is possible to fail a statement on a database that does not yet exist.
43271 ** Do not attempt to write if database file has never been opened.
43273 if( pagerUseWal(pPager) ){
43274 pPg = 0;
43275 }else{
43276 pPg = sqlite3PagerLookup(pPager, pgno);
43278 assert( pPg || !MEMDB );
43279 assert( pPager->eState!=PAGER_OPEN || pPg==0 );
43280 PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
43281 PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
43282 (isMainJrnl?"main-journal":"sub-journal")
43284 if( isMainJrnl ){
43285 isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
43286 }else{
43287 isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
43289 if( isOpen(pPager->fd)
43290 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
43291 && isSynced
43293 i64 ofst = (pgno-1)*(i64)pPager->pageSize;
43294 testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
43295 assert( !pagerUseWal(pPager) );
43296 rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
43297 if( pgno>pPager->dbFileSize ){
43298 pPager->dbFileSize = pgno;
43300 if( pPager->pBackup ){
43301 CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
43302 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
43303 CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
43305 }else if( !isMainJrnl && pPg==0 ){
43306 /* If this is a rollback of a savepoint and data was not written to
43307 ** the database and the page is not in-memory, there is a potential
43308 ** problem. When the page is next fetched by the b-tree layer, it
43309 ** will be read from the database file, which may or may not be
43310 ** current.
43312 ** There are a couple of different ways this can happen. All are quite
43313 ** obscure. When running in synchronous mode, this can only happen
43314 ** if the page is on the free-list at the start of the transaction, then
43315 ** populated, then moved using sqlite3PagerMovepage().
43317 ** The solution is to add an in-memory page to the cache containing
43318 ** the data just read from the sub-journal. Mark the page as dirty
43319 ** and if the pager requires a journal-sync, then mark the page as
43320 ** requiring a journal-sync before it is written.
43322 assert( isSavepnt );
43323 assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
43324 pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
43325 rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
43326 assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
43327 pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
43328 if( rc!=SQLITE_OK ) return rc;
43329 pPg->flags &= ~PGHDR_NEED_READ;
43330 sqlite3PcacheMakeDirty(pPg);
43332 if( pPg ){
43333 /* No page should ever be explicitly rolled back that is in use, except
43334 ** for page 1 which is held in use in order to keep the lock on the
43335 ** database active. However such a page may be rolled back as a result
43336 ** of an internal error resulting in an automatic call to
43337 ** sqlite3PagerRollback().
43339 void *pData;
43340 pData = pPg->pData;
43341 memcpy(pData, (u8*)aData, pPager->pageSize);
43342 pPager->xReiniter(pPg);
43343 if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
43344 /* If the contents of this page were just restored from the main
43345 ** journal file, then its content must be as they were when the
43346 ** transaction was first opened. In this case we can mark the page
43347 ** as clean, since there will be no need to write it out to the
43348 ** database.
43350 ** There is one exception to this rule. If the page is being rolled
43351 ** back as part of a savepoint (or statement) rollback from an
43352 ** unsynced portion of the main journal file, then it is not safe
43353 ** to mark the page as clean. This is because marking the page as
43354 ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
43355 ** already in the journal file (recorded in Pager.pInJournal) and
43356 ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
43357 ** again within this transaction, it will be marked as dirty but
43358 ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
43359 ** be written out into the database file before its journal file
43360 ** segment is synced. If a crash occurs during or following this,
43361 ** database corruption may ensue.
43363 assert( !pagerUseWal(pPager) );
43364 sqlite3PcacheMakeClean(pPg);
43366 pager_set_pagehash(pPg);
43368 /* If this was page 1, then restore the value of Pager.dbFileVers.
43369 ** Do this before any decoding. */
43370 if( pgno==1 ){
43371 memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
43374 /* Decode the page just read from disk */
43375 CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
43376 sqlite3PcacheRelease(pPg);
43378 return rc;
43382 ** Parameter zMaster is the name of a master journal file. A single journal
43383 ** file that referred to the master journal file has just been rolled back.
43384 ** This routine checks if it is possible to delete the master journal file,
43385 ** and does so if it is.
43387 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
43388 ** available for use within this function.
43390 ** When a master journal file is created, it is populated with the names
43391 ** of all of its child journals, one after another, formatted as utf-8
43392 ** encoded text. The end of each child journal file is marked with a
43393 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
43394 ** file for a transaction involving two databases might be:
43396 ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
43398 ** A master journal file may only be deleted once all of its child
43399 ** journals have been rolled back.
43401 ** This function reads the contents of the master-journal file into
43402 ** memory and loops through each of the child journal names. For
43403 ** each child journal, it checks if:
43405 ** * if the child journal exists, and if so
43406 ** * if the child journal contains a reference to master journal
43407 ** file zMaster
43409 ** If a child journal can be found that matches both of the criteria
43410 ** above, this function returns without doing anything. Otherwise, if
43411 ** no such child journal can be found, file zMaster is deleted from
43412 ** the file-system using sqlite3OsDelete().
43414 ** If an IO error within this function, an error code is returned. This
43415 ** function allocates memory by calling sqlite3Malloc(). If an allocation
43416 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
43417 ** occur, SQLITE_OK is returned.
43419 ** TODO: This function allocates a single block of memory to load
43420 ** the entire contents of the master journal file. This could be
43421 ** a couple of kilobytes or so - potentially larger than the page
43422 ** size.
43424 static int pager_delmaster(Pager *pPager, const char *zMaster){
43425 sqlite3_vfs *pVfs = pPager->pVfs;
43426 int rc; /* Return code */
43427 sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
43428 sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
43429 char *zMasterJournal = 0; /* Contents of master journal file */
43430 i64 nMasterJournal; /* Size of master journal file */
43431 char *zJournal; /* Pointer to one journal within MJ file */
43432 char *zMasterPtr; /* Space to hold MJ filename from a journal file */
43433 int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
43435 /* Allocate space for both the pJournal and pMaster file descriptors.
43436 ** If successful, open the master journal file for reading.
43438 pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
43439 pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
43440 if( !pMaster ){
43441 rc = SQLITE_NOMEM;
43442 }else{
43443 const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
43444 rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
43446 if( rc!=SQLITE_OK ) goto delmaster_out;
43448 /* Load the entire master journal file into space obtained from
43449 ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
43450 ** sufficient space (in zMasterPtr) to hold the names of master
43451 ** journal files extracted from regular rollback-journals.
43453 rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
43454 if( rc!=SQLITE_OK ) goto delmaster_out;
43455 nMasterPtr = pVfs->mxPathname+1;
43456 zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
43457 if( !zMasterJournal ){
43458 rc = SQLITE_NOMEM;
43459 goto delmaster_out;
43461 zMasterPtr = &zMasterJournal[nMasterJournal+1];
43462 rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
43463 if( rc!=SQLITE_OK ) goto delmaster_out;
43464 zMasterJournal[nMasterJournal] = 0;
43466 zJournal = zMasterJournal;
43467 while( (zJournal-zMasterJournal)<nMasterJournal ){
43468 int exists;
43469 rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
43470 if( rc!=SQLITE_OK ){
43471 goto delmaster_out;
43473 if( exists ){
43474 /* One of the journals pointed to by the master journal exists.
43475 ** Open it and check if it points at the master journal. If
43476 ** so, return without deleting the master journal file.
43478 int c;
43479 int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
43480 rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
43481 if( rc!=SQLITE_OK ){
43482 goto delmaster_out;
43485 rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
43486 sqlite3OsClose(pJournal);
43487 if( rc!=SQLITE_OK ){
43488 goto delmaster_out;
43491 c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
43492 if( c ){
43493 /* We have a match. Do not delete the master journal file. */
43494 goto delmaster_out;
43497 zJournal += (sqlite3Strlen30(zJournal)+1);
43500 sqlite3OsClose(pMaster);
43501 rc = sqlite3OsDelete(pVfs, zMaster, 0);
43503 delmaster_out:
43504 sqlite3_free(zMasterJournal);
43505 if( pMaster ){
43506 sqlite3OsClose(pMaster);
43507 assert( !isOpen(pJournal) );
43508 sqlite3_free(pMaster);
43510 return rc;
43515 ** This function is used to change the actual size of the database
43516 ** file in the file-system. This only happens when committing a transaction,
43517 ** or rolling back a transaction (including rolling back a hot-journal).
43519 ** If the main database file is not open, or the pager is not in either
43520 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
43521 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
43522 ** If the file on disk is currently larger than nPage pages, then use the VFS
43523 ** xTruncate() method to truncate it.
43525 ** Or, it might be the case that the file on disk is smaller than
43526 ** nPage pages. Some operating system implementations can get confused if
43527 ** you try to truncate a file to some size that is larger than it
43528 ** currently is, so detect this case and write a single zero byte to
43529 ** the end of the new file instead.
43531 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
43532 ** the database file, return the error code to the caller.
43534 static int pager_truncate(Pager *pPager, Pgno nPage){
43535 int rc = SQLITE_OK;
43536 assert( pPager->eState!=PAGER_ERROR );
43537 assert( pPager->eState!=PAGER_READER );
43539 if( isOpen(pPager->fd)
43540 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
43542 i64 currentSize, newSize;
43543 int szPage = pPager->pageSize;
43544 assert( pPager->eLock==EXCLUSIVE_LOCK );
43545 /* TODO: Is it safe to use Pager.dbFileSize here? */
43546 rc = sqlite3OsFileSize(pPager->fd, &currentSize);
43547 newSize = szPage*(i64)nPage;
43548 if( rc==SQLITE_OK && currentSize!=newSize ){
43549 if( currentSize>newSize ){
43550 rc = sqlite3OsTruncate(pPager->fd, newSize);
43551 }else if( (currentSize+szPage)<=newSize ){
43552 char *pTmp = pPager->pTmpSpace;
43553 memset(pTmp, 0, szPage);
43554 testcase( (newSize-szPage) == currentSize );
43555 testcase( (newSize-szPage) > currentSize );
43556 rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
43558 if( rc==SQLITE_OK ){
43559 pPager->dbFileSize = nPage;
43563 return rc;
43567 ** Return a sanitized version of the sector-size of OS file pFile. The
43568 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
43570 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
43571 int iRet = sqlite3OsSectorSize(pFile);
43572 if( iRet<32 ){
43573 iRet = 512;
43574 }else if( iRet>MAX_SECTOR_SIZE ){
43575 assert( MAX_SECTOR_SIZE>=512 );
43576 iRet = MAX_SECTOR_SIZE;
43578 return iRet;
43582 ** Set the value of the Pager.sectorSize variable for the given
43583 ** pager based on the value returned by the xSectorSize method
43584 ** of the open database file. The sector size will be used
43585 ** to determine the size and alignment of journal header and
43586 ** master journal pointers within created journal files.
43588 ** For temporary files the effective sector size is always 512 bytes.
43590 ** Otherwise, for non-temporary files, the effective sector size is
43591 ** the value returned by the xSectorSize() method rounded up to 32 if
43592 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
43593 ** is greater than MAX_SECTOR_SIZE.
43595 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
43596 ** the effective sector size to its minimum value (512). The purpose of
43597 ** pPager->sectorSize is to define the "blast radius" of bytes that
43598 ** might change if a crash occurs while writing to a single byte in
43599 ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
43600 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
43601 ** size. For backwards compatibility of the rollback journal file format,
43602 ** we cannot reduce the effective sector size below 512.
43604 static void setSectorSize(Pager *pPager){
43605 assert( isOpen(pPager->fd) || pPager->tempFile );
43607 if( pPager->tempFile
43608 || (sqlite3OsDeviceCharacteristics(pPager->fd) &
43609 SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
43611 /* Sector size doesn't matter for temporary files. Also, the file
43612 ** may not have been opened yet, in which case the OsSectorSize()
43613 ** call will segfault. */
43614 pPager->sectorSize = 512;
43615 }else{
43616 pPager->sectorSize = sqlite3SectorSize(pPager->fd);
43621 ** Playback the journal and thus restore the database file to
43622 ** the state it was in before we started making changes.
43624 ** The journal file format is as follows:
43626 ** (1) 8 byte prefix. A copy of aJournalMagic[].
43627 ** (2) 4 byte big-endian integer which is the number of valid page records
43628 ** in the journal. If this value is 0xffffffff, then compute the
43629 ** number of page records from the journal size.
43630 ** (3) 4 byte big-endian integer which is the initial value for the
43631 ** sanity checksum.
43632 ** (4) 4 byte integer which is the number of pages to truncate the
43633 ** database to during a rollback.
43634 ** (5) 4 byte big-endian integer which is the sector size. The header
43635 ** is this many bytes in size.
43636 ** (6) 4 byte big-endian integer which is the page size.
43637 ** (7) zero padding out to the next sector size.
43638 ** (8) Zero or more pages instances, each as follows:
43639 ** + 4 byte page number.
43640 ** + pPager->pageSize bytes of data.
43641 ** + 4 byte checksum
43643 ** When we speak of the journal header, we mean the first 7 items above.
43644 ** Each entry in the journal is an instance of the 8th item.
43646 ** Call the value from the second bullet "nRec". nRec is the number of
43647 ** valid page entries in the journal. In most cases, you can compute the
43648 ** value of nRec from the size of the journal file. But if a power
43649 ** failure occurred while the journal was being written, it could be the
43650 ** case that the size of the journal file had already been increased but
43651 ** the extra entries had not yet made it safely to disk. In such a case,
43652 ** the value of nRec computed from the file size would be too large. For
43653 ** that reason, we always use the nRec value in the header.
43655 ** If the nRec value is 0xffffffff it means that nRec should be computed
43656 ** from the file size. This value is used when the user selects the
43657 ** no-sync option for the journal. A power failure could lead to corruption
43658 ** in this case. But for things like temporary table (which will be
43659 ** deleted when the power is restored) we don't care.
43661 ** If the file opened as the journal file is not a well-formed
43662 ** journal file then all pages up to the first corrupted page are rolled
43663 ** back (or no pages if the journal header is corrupted). The journal file
43664 ** is then deleted and SQLITE_OK returned, just as if no corruption had
43665 ** been encountered.
43667 ** If an I/O or malloc() error occurs, the journal-file is not deleted
43668 ** and an error code is returned.
43670 ** The isHot parameter indicates that we are trying to rollback a journal
43671 ** that might be a hot journal. Or, it could be that the journal is
43672 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
43673 ** If the journal really is hot, reset the pager cache prior rolling
43674 ** back any content. If the journal is merely persistent, no reset is
43675 ** needed.
43677 static int pager_playback(Pager *pPager, int isHot){
43678 sqlite3_vfs *pVfs = pPager->pVfs;
43679 i64 szJ; /* Size of the journal file in bytes */
43680 u32 nRec; /* Number of Records in the journal */
43681 u32 u; /* Unsigned loop counter */
43682 Pgno mxPg = 0; /* Size of the original file in pages */
43683 int rc; /* Result code of a subroutine */
43684 int res = 1; /* Value returned by sqlite3OsAccess() */
43685 char *zMaster = 0; /* Name of master journal file if any */
43686 int needPagerReset; /* True to reset page prior to first page rollback */
43687 int nPlayback = 0; /* Total number of pages restored from journal */
43689 /* Figure out how many records are in the journal. Abort early if
43690 ** the journal is empty.
43692 assert( isOpen(pPager->jfd) );
43693 rc = sqlite3OsFileSize(pPager->jfd, &szJ);
43694 if( rc!=SQLITE_OK ){
43695 goto end_playback;
43698 /* Read the master journal name from the journal, if it is present.
43699 ** If a master journal file name is specified, but the file is not
43700 ** present on disk, then the journal is not hot and does not need to be
43701 ** played back.
43703 ** TODO: Technically the following is an error because it assumes that
43704 ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
43705 ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
43706 ** mxPathname is 512, which is the same as the minimum allowable value
43707 ** for pageSize.
43709 zMaster = pPager->pTmpSpace;
43710 rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
43711 if( rc==SQLITE_OK && zMaster[0] ){
43712 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
43714 zMaster = 0;
43715 if( rc!=SQLITE_OK || !res ){
43716 goto end_playback;
43718 pPager->journalOff = 0;
43719 needPagerReset = isHot;
43721 /* This loop terminates either when a readJournalHdr() or
43722 ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
43723 ** occurs.
43725 while( 1 ){
43726 /* Read the next journal header from the journal file. If there are
43727 ** not enough bytes left in the journal file for a complete header, or
43728 ** it is corrupted, then a process must have failed while writing it.
43729 ** This indicates nothing more needs to be rolled back.
43731 rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
43732 if( rc!=SQLITE_OK ){
43733 if( rc==SQLITE_DONE ){
43734 rc = SQLITE_OK;
43736 goto end_playback;
43739 /* If nRec is 0xffffffff, then this journal was created by a process
43740 ** working in no-sync mode. This means that the rest of the journal
43741 ** file consists of pages, there are no more journal headers. Compute
43742 ** the value of nRec based on this assumption.
43744 if( nRec==0xffffffff ){
43745 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
43746 nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
43749 /* If nRec is 0 and this rollback is of a transaction created by this
43750 ** process and if this is the final header in the journal, then it means
43751 ** that this part of the journal was being filled but has not yet been
43752 ** synced to disk. Compute the number of pages based on the remaining
43753 ** size of the file.
43755 ** The third term of the test was added to fix ticket #2565.
43756 ** When rolling back a hot journal, nRec==0 always means that the next
43757 ** chunk of the journal contains zero pages to be rolled back. But
43758 ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
43759 ** the journal, it means that the journal might contain additional
43760 ** pages that need to be rolled back and that the number of pages
43761 ** should be computed based on the journal file size.
43763 if( nRec==0 && !isHot &&
43764 pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
43765 nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
43768 /* If this is the first header read from the journal, truncate the
43769 ** database file back to its original size.
43771 if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
43772 rc = pager_truncate(pPager, mxPg);
43773 if( rc!=SQLITE_OK ){
43774 goto end_playback;
43776 pPager->dbSize = mxPg;
43779 /* Copy original pages out of the journal and back into the
43780 ** database file and/or page cache.
43782 for(u=0; u<nRec; u++){
43783 if( needPagerReset ){
43784 pager_reset(pPager);
43785 needPagerReset = 0;
43787 rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
43788 if( rc==SQLITE_OK ){
43789 nPlayback++;
43790 }else{
43791 if( rc==SQLITE_DONE ){
43792 pPager->journalOff = szJ;
43793 break;
43794 }else if( rc==SQLITE_IOERR_SHORT_READ ){
43795 /* If the journal has been truncated, simply stop reading and
43796 ** processing the journal. This might happen if the journal was
43797 ** not completely written and synced prior to a crash. In that
43798 ** case, the database should have never been written in the
43799 ** first place so it is OK to simply abandon the rollback. */
43800 rc = SQLITE_OK;
43801 goto end_playback;
43802 }else{
43803 /* If we are unable to rollback, quit and return the error
43804 ** code. This will cause the pager to enter the error state
43805 ** so that no further harm will be done. Perhaps the next
43806 ** process to come along will be able to rollback the database.
43808 goto end_playback;
43813 /*NOTREACHED*/
43814 assert( 0 );
43816 end_playback:
43817 /* Following a rollback, the database file should be back in its original
43818 ** state prior to the start of the transaction, so invoke the
43819 ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
43820 ** assertion that the transaction counter was modified.
43822 #ifdef SQLITE_DEBUG
43823 if( pPager->fd->pMethods ){
43824 sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
43826 #endif
43828 /* If this playback is happening automatically as a result of an IO or
43829 ** malloc error that occurred after the change-counter was updated but
43830 ** before the transaction was committed, then the change-counter
43831 ** modification may just have been reverted. If this happens in exclusive
43832 ** mode, then subsequent transactions performed by the connection will not
43833 ** update the change-counter at all. This may lead to cache inconsistency
43834 ** problems for other processes at some point in the future. So, just
43835 ** in case this has happened, clear the changeCountDone flag now.
43837 pPager->changeCountDone = pPager->tempFile;
43839 if( rc==SQLITE_OK ){
43840 zMaster = pPager->pTmpSpace;
43841 rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
43842 testcase( rc!=SQLITE_OK );
43844 if( rc==SQLITE_OK
43845 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
43847 rc = sqlite3PagerSync(pPager, 0);
43849 if( rc==SQLITE_OK ){
43850 rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
43851 testcase( rc!=SQLITE_OK );
43853 if( rc==SQLITE_OK && zMaster[0] && res ){
43854 /* If there was a master journal and this routine will return success,
43855 ** see if it is possible to delete the master journal.
43857 rc = pager_delmaster(pPager, zMaster);
43858 testcase( rc!=SQLITE_OK );
43860 if( isHot && nPlayback ){
43861 sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
43862 nPlayback, pPager->zJournal);
43865 /* The Pager.sectorSize variable may have been updated while rolling
43866 ** back a journal created by a process with a different sector size
43867 ** value. Reset it to the correct value for this process.
43869 setSectorSize(pPager);
43870 return rc;
43875 ** Read the content for page pPg out of the database file and into
43876 ** pPg->pData. A shared lock or greater must be held on the database
43877 ** file before this function is called.
43879 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
43880 ** the value read from the database file.
43882 ** If an IO error occurs, then the IO error is returned to the caller.
43883 ** Otherwise, SQLITE_OK is returned.
43885 static int readDbPage(PgHdr *pPg, u32 iFrame){
43886 Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
43887 Pgno pgno = pPg->pgno; /* Page number to read */
43888 int rc = SQLITE_OK; /* Return code */
43889 int pgsz = pPager->pageSize; /* Number of bytes to read */
43891 assert( pPager->eState>=PAGER_READER && !MEMDB );
43892 assert( isOpen(pPager->fd) );
43894 #ifndef SQLITE_OMIT_WAL
43895 if( iFrame ){
43896 /* Try to pull the page from the write-ahead log. */
43897 rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
43898 }else
43899 #endif
43901 i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
43902 rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
43903 if( rc==SQLITE_IOERR_SHORT_READ ){
43904 rc = SQLITE_OK;
43908 if( pgno==1 ){
43909 if( rc ){
43910 /* If the read is unsuccessful, set the dbFileVers[] to something
43911 ** that will never be a valid file version. dbFileVers[] is a copy
43912 ** of bytes 24..39 of the database. Bytes 28..31 should always be
43913 ** zero or the size of the database in page. Bytes 32..35 and 35..39
43914 ** should be page numbers which are never 0xffffffff. So filling
43915 ** pPager->dbFileVers[] with all 0xff bytes should suffice.
43917 ** For an encrypted database, the situation is more complex: bytes
43918 ** 24..39 of the database are white noise. But the probability of
43919 ** white noising equaling 16 bytes of 0xff is vanishingly small so
43920 ** we should still be ok.
43922 memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
43923 }else{
43924 u8 *dbFileVers = &((u8*)pPg->pData)[24];
43925 memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
43928 CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
43930 PAGER_INCR(sqlite3_pager_readdb_count);
43931 PAGER_INCR(pPager->nRead);
43932 IOTRACE(("PGIN %p %d\n", pPager, pgno));
43933 PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
43934 PAGERID(pPager), pgno, pager_pagehash(pPg)));
43936 return rc;
43940 ** Update the value of the change-counter at offsets 24 and 92 in
43941 ** the header and the sqlite version number at offset 96.
43943 ** This is an unconditional update. See also the pager_incr_changecounter()
43944 ** routine which only updates the change-counter if the update is actually
43945 ** needed, as determined by the pPager->changeCountDone state variable.
43947 static void pager_write_changecounter(PgHdr *pPg){
43948 u32 change_counter;
43950 /* Increment the value just read and write it back to byte 24. */
43951 change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
43952 put32bits(((char*)pPg->pData)+24, change_counter);
43954 /* Also store the SQLite version number in bytes 96..99 and in
43955 ** bytes 92..95 store the change counter for which the version number
43956 ** is valid. */
43957 put32bits(((char*)pPg->pData)+92, change_counter);
43958 put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
43961 #ifndef SQLITE_OMIT_WAL
43963 ** This function is invoked once for each page that has already been
43964 ** written into the log file when a WAL transaction is rolled back.
43965 ** Parameter iPg is the page number of said page. The pCtx argument
43966 ** is actually a pointer to the Pager structure.
43968 ** If page iPg is present in the cache, and has no outstanding references,
43969 ** it is discarded. Otherwise, if there are one or more outstanding
43970 ** references, the page content is reloaded from the database. If the
43971 ** attempt to reload content from the database is required and fails,
43972 ** return an SQLite error code. Otherwise, SQLITE_OK.
43974 static int pagerUndoCallback(void *pCtx, Pgno iPg){
43975 int rc = SQLITE_OK;
43976 Pager *pPager = (Pager *)pCtx;
43977 PgHdr *pPg;
43979 assert( pagerUseWal(pPager) );
43980 pPg = sqlite3PagerLookup(pPager, iPg);
43981 if( pPg ){
43982 if( sqlite3PcachePageRefcount(pPg)==1 ){
43983 sqlite3PcacheDrop(pPg);
43984 }else{
43985 u32 iFrame = 0;
43986 rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
43987 if( rc==SQLITE_OK ){
43988 rc = readDbPage(pPg, iFrame);
43990 if( rc==SQLITE_OK ){
43991 pPager->xReiniter(pPg);
43993 sqlite3PagerUnrefNotNull(pPg);
43997 /* Normally, if a transaction is rolled back, any backup processes are
43998 ** updated as data is copied out of the rollback journal and into the
43999 ** database. This is not generally possible with a WAL database, as
44000 ** rollback involves simply truncating the log file. Therefore, if one
44001 ** or more frames have already been written to the log (and therefore
44002 ** also copied into the backup databases) as part of this transaction,
44003 ** the backups must be restarted.
44005 sqlite3BackupRestart(pPager->pBackup);
44007 return rc;
44011 ** This function is called to rollback a transaction on a WAL database.
44013 static int pagerRollbackWal(Pager *pPager){
44014 int rc; /* Return Code */
44015 PgHdr *pList; /* List of dirty pages to revert */
44017 /* For all pages in the cache that are currently dirty or have already
44018 ** been written (but not committed) to the log file, do one of the
44019 ** following:
44021 ** + Discard the cached page (if refcount==0), or
44022 ** + Reload page content from the database (if refcount>0).
44024 pPager->dbSize = pPager->dbOrigSize;
44025 rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
44026 pList = sqlite3PcacheDirtyList(pPager->pPCache);
44027 while( pList && rc==SQLITE_OK ){
44028 PgHdr *pNext = pList->pDirty;
44029 rc = pagerUndoCallback((void *)pPager, pList->pgno);
44030 pList = pNext;
44033 return rc;
44037 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
44038 ** the contents of the list of pages headed by pList (connected by pDirty),
44039 ** this function notifies any active backup processes that the pages have
44040 ** changed.
44042 ** The list of pages passed into this routine is always sorted by page number.
44043 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
44045 static int pagerWalFrames(
44046 Pager *pPager, /* Pager object */
44047 PgHdr *pList, /* List of frames to log */
44048 Pgno nTruncate, /* Database size after this commit */
44049 int isCommit /* True if this is a commit */
44051 int rc; /* Return code */
44052 int nList; /* Number of pages in pList */
44053 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
44054 PgHdr *p; /* For looping over pages */
44055 #endif
44057 assert( pPager->pWal );
44058 assert( pList );
44059 #ifdef SQLITE_DEBUG
44060 /* Verify that the page list is in accending order */
44061 for(p=pList; p && p->pDirty; p=p->pDirty){
44062 assert( p->pgno < p->pDirty->pgno );
44064 #endif
44066 assert( pList->pDirty==0 || isCommit );
44067 if( isCommit ){
44068 /* If a WAL transaction is being committed, there is no point in writing
44069 ** any pages with page numbers greater than nTruncate into the WAL file.
44070 ** They will never be read by any client. So remove them from the pDirty
44071 ** list here. */
44072 PgHdr *p;
44073 PgHdr **ppNext = &pList;
44074 nList = 0;
44075 for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
44076 if( p->pgno<=nTruncate ){
44077 ppNext = &p->pDirty;
44078 nList++;
44081 assert( pList );
44082 }else{
44083 nList = 1;
44085 pPager->aStat[PAGER_STAT_WRITE] += nList;
44087 if( pList->pgno==1 ) pager_write_changecounter(pList);
44088 rc = sqlite3WalFrames(pPager->pWal,
44089 pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
44091 if( rc==SQLITE_OK && pPager->pBackup ){
44092 PgHdr *p;
44093 for(p=pList; p; p=p->pDirty){
44094 sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
44098 #ifdef SQLITE_CHECK_PAGES
44099 pList = sqlite3PcacheDirtyList(pPager->pPCache);
44100 for(p=pList; p; p=p->pDirty){
44101 pager_set_pagehash(p);
44103 #endif
44105 return rc;
44109 ** Begin a read transaction on the WAL.
44111 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
44112 ** makes a snapshot of the database at the current point in time and preserves
44113 ** that snapshot for use by the reader in spite of concurrently changes by
44114 ** other writers or checkpointers.
44116 static int pagerBeginReadTransaction(Pager *pPager){
44117 int rc; /* Return code */
44118 int changed = 0; /* True if cache must be reset */
44120 assert( pagerUseWal(pPager) );
44121 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
44123 /* sqlite3WalEndReadTransaction() was not called for the previous
44124 ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
44125 ** are in locking_mode=NORMAL and EndRead() was previously called,
44126 ** the duplicate call is harmless.
44128 sqlite3WalEndReadTransaction(pPager->pWal);
44130 rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
44131 if( rc!=SQLITE_OK || changed ){
44132 pager_reset(pPager);
44133 if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
44136 return rc;
44138 #endif
44141 ** This function is called as part of the transition from PAGER_OPEN
44142 ** to PAGER_READER state to determine the size of the database file
44143 ** in pages (assuming the page size currently stored in Pager.pageSize).
44145 ** If no error occurs, SQLITE_OK is returned and the size of the database
44146 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
44147 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
44149 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
44150 Pgno nPage; /* Value to return via *pnPage */
44152 /* Query the WAL sub-system for the database size. The WalDbsize()
44153 ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
44154 ** if the database size is not available. The database size is not
44155 ** available from the WAL sub-system if the log file is empty or
44156 ** contains no valid committed transactions.
44158 assert( pPager->eState==PAGER_OPEN );
44159 assert( pPager->eLock>=SHARED_LOCK );
44160 nPage = sqlite3WalDbsize(pPager->pWal);
44162 /* If the database size was not available from the WAL sub-system,
44163 ** determine it based on the size of the database file. If the size
44164 ** of the database file is not an integer multiple of the page-size,
44165 ** round down to the nearest page. Except, any file larger than 0
44166 ** bytes in size is considered to contain at least one page.
44168 if( nPage==0 ){
44169 i64 n = 0; /* Size of db file in bytes */
44170 assert( isOpen(pPager->fd) || pPager->tempFile );
44171 if( isOpen(pPager->fd) ){
44172 int rc = sqlite3OsFileSize(pPager->fd, &n);
44173 if( rc!=SQLITE_OK ){
44174 return rc;
44177 nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
44180 /* If the current number of pages in the file is greater than the
44181 ** configured maximum pager number, increase the allowed limit so
44182 ** that the file can be read.
44184 if( nPage>pPager->mxPgno ){
44185 pPager->mxPgno = (Pgno)nPage;
44188 *pnPage = nPage;
44189 return SQLITE_OK;
44192 #ifndef SQLITE_OMIT_WAL
44194 ** Check if the *-wal file that corresponds to the database opened by pPager
44195 ** exists if the database is not empy, or verify that the *-wal file does
44196 ** not exist (by deleting it) if the database file is empty.
44198 ** If the database is not empty and the *-wal file exists, open the pager
44199 ** in WAL mode. If the database is empty or if no *-wal file exists and
44200 ** if no error occurs, make sure Pager.journalMode is not set to
44201 ** PAGER_JOURNALMODE_WAL.
44203 ** Return SQLITE_OK or an error code.
44205 ** The caller must hold a SHARED lock on the database file to call this
44206 ** function. Because an EXCLUSIVE lock on the db file is required to delete
44207 ** a WAL on a none-empty database, this ensures there is no race condition
44208 ** between the xAccess() below and an xDelete() being executed by some
44209 ** other connection.
44211 static int pagerOpenWalIfPresent(Pager *pPager){
44212 int rc = SQLITE_OK;
44213 assert( pPager->eState==PAGER_OPEN );
44214 assert( pPager->eLock>=SHARED_LOCK );
44216 if( !pPager->tempFile ){
44217 int isWal; /* True if WAL file exists */
44218 Pgno nPage; /* Size of the database file */
44220 rc = pagerPagecount(pPager, &nPage);
44221 if( rc ) return rc;
44222 if( nPage==0 ){
44223 rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
44224 if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
44225 isWal = 0;
44226 }else{
44227 rc = sqlite3OsAccess(
44228 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
44231 if( rc==SQLITE_OK ){
44232 if( isWal ){
44233 testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
44234 rc = sqlite3PagerOpenWal(pPager, 0);
44235 }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
44236 pPager->journalMode = PAGER_JOURNALMODE_DELETE;
44240 return rc;
44242 #endif
44245 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
44246 ** the entire master journal file. The case pSavepoint==NULL occurs when
44247 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
44248 ** savepoint.
44250 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
44251 ** being rolled back), then the rollback consists of up to three stages,
44252 ** performed in the order specified:
44254 ** * Pages are played back from the main journal starting at byte
44255 ** offset PagerSavepoint.iOffset and continuing to
44256 ** PagerSavepoint.iHdrOffset, or to the end of the main journal
44257 ** file if PagerSavepoint.iHdrOffset is zero.
44259 ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
44260 ** back starting from the journal header immediately following
44261 ** PagerSavepoint.iHdrOffset to the end of the main journal file.
44263 ** * Pages are then played back from the sub-journal file, starting
44264 ** with the PagerSavepoint.iSubRec and continuing to the end of
44265 ** the journal file.
44267 ** Throughout the rollback process, each time a page is rolled back, the
44268 ** corresponding bit is set in a bitvec structure (variable pDone in the
44269 ** implementation below). This is used to ensure that a page is only
44270 ** rolled back the first time it is encountered in either journal.
44272 ** If pSavepoint is NULL, then pages are only played back from the main
44273 ** journal file. There is no need for a bitvec in this case.
44275 ** In either case, before playback commences the Pager.dbSize variable
44276 ** is reset to the value that it held at the start of the savepoint
44277 ** (or transaction). No page with a page-number greater than this value
44278 ** is played back. If one is encountered it is simply skipped.
44280 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
44281 i64 szJ; /* Effective size of the main journal */
44282 i64 iHdrOff; /* End of first segment of main-journal records */
44283 int rc = SQLITE_OK; /* Return code */
44284 Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
44286 assert( pPager->eState!=PAGER_ERROR );
44287 assert( pPager->eState>=PAGER_WRITER_LOCKED );
44289 /* Allocate a bitvec to use to store the set of pages rolled back */
44290 if( pSavepoint ){
44291 pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
44292 if( !pDone ){
44293 return SQLITE_NOMEM;
44297 /* Set the database size back to the value it was before the savepoint
44298 ** being reverted was opened.
44300 pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
44301 pPager->changeCountDone = pPager->tempFile;
44303 if( !pSavepoint && pagerUseWal(pPager) ){
44304 return pagerRollbackWal(pPager);
44307 /* Use pPager->journalOff as the effective size of the main rollback
44308 ** journal. The actual file might be larger than this in
44309 ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
44310 ** past pPager->journalOff is off-limits to us.
44312 szJ = pPager->journalOff;
44313 assert( pagerUseWal(pPager)==0 || szJ==0 );
44315 /* Begin by rolling back records from the main journal starting at
44316 ** PagerSavepoint.iOffset and continuing to the next journal header.
44317 ** There might be records in the main journal that have a page number
44318 ** greater than the current database size (pPager->dbSize) but those
44319 ** will be skipped automatically. Pages are added to pDone as they
44320 ** are played back.
44322 if( pSavepoint && !pagerUseWal(pPager) ){
44323 iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
44324 pPager->journalOff = pSavepoint->iOffset;
44325 while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
44326 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
44328 assert( rc!=SQLITE_DONE );
44329 }else{
44330 pPager->journalOff = 0;
44333 /* Continue rolling back records out of the main journal starting at
44334 ** the first journal header seen and continuing until the effective end
44335 ** of the main journal file. Continue to skip out-of-range pages and
44336 ** continue adding pages rolled back to pDone.
44338 while( rc==SQLITE_OK && pPager->journalOff<szJ ){
44339 u32 ii; /* Loop counter */
44340 u32 nJRec = 0; /* Number of Journal Records */
44341 u32 dummy;
44342 rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
44343 assert( rc!=SQLITE_DONE );
44346 ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
44347 ** test is related to ticket #2565. See the discussion in the
44348 ** pager_playback() function for additional information.
44350 if( nJRec==0
44351 && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
44353 nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
44355 for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
44356 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
44358 assert( rc!=SQLITE_DONE );
44360 assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
44362 /* Finally, rollback pages from the sub-journal. Page that were
44363 ** previously rolled back out of the main journal (and are hence in pDone)
44364 ** will be skipped. Out-of-range pages are also skipped.
44366 if( pSavepoint ){
44367 u32 ii; /* Loop counter */
44368 i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
44370 if( pagerUseWal(pPager) ){
44371 rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
44373 for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
44374 assert( offset==(i64)ii*(4+pPager->pageSize) );
44375 rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
44377 assert( rc!=SQLITE_DONE );
44380 sqlite3BitvecDestroy(pDone);
44381 if( rc==SQLITE_OK ){
44382 pPager->journalOff = szJ;
44385 return rc;
44389 ** Change the maximum number of in-memory pages that are allowed.
44391 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
44392 sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
44396 ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
44398 static void pagerFixMaplimit(Pager *pPager){
44399 #if SQLITE_MAX_MMAP_SIZE>0
44400 sqlite3_file *fd = pPager->fd;
44401 if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
44402 sqlite3_int64 sz;
44403 sz = pPager->szMmap;
44404 pPager->bUseFetch = (sz>0);
44405 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
44407 #endif
44411 ** Change the maximum size of any memory mapping made of the database file.
44413 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
44414 pPager->szMmap = szMmap;
44415 pagerFixMaplimit(pPager);
44419 ** Free as much memory as possible from the pager.
44421 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
44422 sqlite3PcacheShrink(pPager->pPCache);
44426 ** Adjust settings of the pager to those specified in the pgFlags parameter.
44428 ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
44429 ** of the database to damage due to OS crashes or power failures by
44430 ** changing the number of syncs()s when writing the journals.
44431 ** There are three levels:
44433 ** OFF sqlite3OsSync() is never called. This is the default
44434 ** for temporary and transient files.
44436 ** NORMAL The journal is synced once before writes begin on the
44437 ** database. This is normally adequate protection, but
44438 ** it is theoretically possible, though very unlikely,
44439 ** that an inopertune power failure could leave the journal
44440 ** in a state which would cause damage to the database
44441 ** when it is rolled back.
44443 ** FULL The journal is synced twice before writes begin on the
44444 ** database (with some additional information - the nRec field
44445 ** of the journal header - being written in between the two
44446 ** syncs). If we assume that writing a
44447 ** single disk sector is atomic, then this mode provides
44448 ** assurance that the journal will not be corrupted to the
44449 ** point of causing damage to the database during rollback.
44451 ** The above is for a rollback-journal mode. For WAL mode, OFF continues
44452 ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
44453 ** prior to the start of checkpoint and that the database file is synced
44454 ** at the conclusion of the checkpoint if the entire content of the WAL
44455 ** was written back into the database. But no sync operations occur for
44456 ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
44457 ** file is synced following each commit operation, in addition to the
44458 ** syncs associated with NORMAL.
44460 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
44461 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
44462 ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
44463 ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
44464 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
44465 ** synchronous=FULL versus synchronous=NORMAL setting determines when
44466 ** the xSync primitive is called and is relevant to all platforms.
44468 ** Numeric values associated with these states are OFF==1, NORMAL=2,
44469 ** and FULL=3.
44471 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
44472 SQLITE_PRIVATE void sqlite3PagerSetFlags(
44473 Pager *pPager, /* The pager to set safety level for */
44474 unsigned pgFlags /* Various flags */
44476 unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
44477 assert( level>=1 && level<=3 );
44478 pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
44479 pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
44480 if( pPager->noSync ){
44481 pPager->syncFlags = 0;
44482 pPager->ckptSyncFlags = 0;
44483 }else if( pgFlags & PAGER_FULLFSYNC ){
44484 pPager->syncFlags = SQLITE_SYNC_FULL;
44485 pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
44486 }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
44487 pPager->syncFlags = SQLITE_SYNC_NORMAL;
44488 pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
44489 }else{
44490 pPager->syncFlags = SQLITE_SYNC_NORMAL;
44491 pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
44493 pPager->walSyncFlags = pPager->syncFlags;
44494 if( pPager->fullSync ){
44495 pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
44497 if( pgFlags & PAGER_CACHESPILL ){
44498 pPager->doNotSpill &= ~SPILLFLAG_OFF;
44499 }else{
44500 pPager->doNotSpill |= SPILLFLAG_OFF;
44503 #endif
44506 ** The following global variable is incremented whenever the library
44507 ** attempts to open a temporary file. This information is used for
44508 ** testing and analysis only.
44510 #ifdef SQLITE_TEST
44511 SQLITE_API int sqlite3_opentemp_count = 0;
44512 #endif
44515 ** Open a temporary file.
44517 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
44518 ** or some other error code if we fail. The OS will automatically
44519 ** delete the temporary file when it is closed.
44521 ** The flags passed to the VFS layer xOpen() call are those specified
44522 ** by parameter vfsFlags ORed with the following:
44524 ** SQLITE_OPEN_READWRITE
44525 ** SQLITE_OPEN_CREATE
44526 ** SQLITE_OPEN_EXCLUSIVE
44527 ** SQLITE_OPEN_DELETEONCLOSE
44529 static int pagerOpentemp(
44530 Pager *pPager, /* The pager object */
44531 sqlite3_file *pFile, /* Write the file descriptor here */
44532 int vfsFlags /* Flags passed through to the VFS */
44534 int rc; /* Return code */
44536 #ifdef SQLITE_TEST
44537 sqlite3_opentemp_count++; /* Used for testing and analysis only */
44538 #endif
44540 vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
44541 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
44542 rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
44543 assert( rc!=SQLITE_OK || isOpen(pFile) );
44544 return rc;
44548 ** Set the busy handler function.
44550 ** The pager invokes the busy-handler if sqlite3OsLock() returns
44551 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
44552 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
44553 ** lock. It does *not* invoke the busy handler when upgrading from
44554 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
44555 ** (which occurs during hot-journal rollback). Summary:
44557 ** Transition | Invokes xBusyHandler
44558 ** --------------------------------------------------------
44559 ** NO_LOCK -> SHARED_LOCK | Yes
44560 ** SHARED_LOCK -> RESERVED_LOCK | No
44561 ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
44562 ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
44564 ** If the busy-handler callback returns non-zero, the lock is
44565 ** retried. If it returns zero, then the SQLITE_BUSY error is
44566 ** returned to the caller of the pager API function.
44568 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
44569 Pager *pPager, /* Pager object */
44570 int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
44571 void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
44573 pPager->xBusyHandler = xBusyHandler;
44574 pPager->pBusyHandlerArg = pBusyHandlerArg;
44576 if( isOpen(pPager->fd) ){
44577 void **ap = (void **)&pPager->xBusyHandler;
44578 assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
44579 assert( ap[1]==pBusyHandlerArg );
44580 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
44585 ** Change the page size used by the Pager object. The new page size
44586 ** is passed in *pPageSize.
44588 ** If the pager is in the error state when this function is called, it
44589 ** is a no-op. The value returned is the error state error code (i.e.
44590 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
44592 ** Otherwise, if all of the following are true:
44594 ** * the new page size (value of *pPageSize) is valid (a power
44595 ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
44597 ** * there are no outstanding page references, and
44599 ** * the database is either not an in-memory database or it is
44600 ** an in-memory database that currently consists of zero pages.
44602 ** then the pager object page size is set to *pPageSize.
44604 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
44605 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
44606 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
44607 ** In all other cases, SQLITE_OK is returned.
44609 ** If the page size is not changed, either because one of the enumerated
44610 ** conditions above is not true, the pager was in error state when this
44611 ** function was called, or because the memory allocation attempt failed,
44612 ** then *pPageSize is set to the old, retained page size before returning.
44614 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
44615 int rc = SQLITE_OK;
44617 /* It is not possible to do a full assert_pager_state() here, as this
44618 ** function may be called from within PagerOpen(), before the state
44619 ** of the Pager object is internally consistent.
44621 ** At one point this function returned an error if the pager was in
44622 ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
44623 ** there is at least one outstanding page reference, this function
44624 ** is a no-op for that case anyhow.
44627 u32 pageSize = *pPageSize;
44628 assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
44629 if( (pPager->memDb==0 || pPager->dbSize==0)
44630 && sqlite3PcacheRefCount(pPager->pPCache)==0
44631 && pageSize && pageSize!=(u32)pPager->pageSize
44633 char *pNew = NULL; /* New temp space */
44634 i64 nByte = 0;
44636 if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
44637 rc = sqlite3OsFileSize(pPager->fd, &nByte);
44639 if( rc==SQLITE_OK ){
44640 pNew = (char *)sqlite3PageMalloc(pageSize);
44641 if( !pNew ) rc = SQLITE_NOMEM;
44644 if( rc==SQLITE_OK ){
44645 pager_reset(pPager);
44646 rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
44648 if( rc==SQLITE_OK ){
44649 sqlite3PageFree(pPager->pTmpSpace);
44650 pPager->pTmpSpace = pNew;
44651 pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
44652 pPager->pageSize = pageSize;
44653 }else{
44654 sqlite3PageFree(pNew);
44658 *pPageSize = pPager->pageSize;
44659 if( rc==SQLITE_OK ){
44660 if( nReserve<0 ) nReserve = pPager->nReserve;
44661 assert( nReserve>=0 && nReserve<1000 );
44662 pPager->nReserve = (i16)nReserve;
44663 pagerReportSize(pPager);
44664 pagerFixMaplimit(pPager);
44666 return rc;
44670 ** Return a pointer to the "temporary page" buffer held internally
44671 ** by the pager. This is a buffer that is big enough to hold the
44672 ** entire content of a database page. This buffer is used internally
44673 ** during rollback and will be overwritten whenever a rollback
44674 ** occurs. But other modules are free to use it too, as long as
44675 ** no rollbacks are happening.
44677 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
44678 return pPager->pTmpSpace;
44682 ** Attempt to set the maximum database page count if mxPage is positive.
44683 ** Make no changes if mxPage is zero or negative. And never reduce the
44684 ** maximum page count below the current size of the database.
44686 ** Regardless of mxPage, return the current maximum page count.
44688 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
44689 if( mxPage>0 ){
44690 pPager->mxPgno = mxPage;
44692 assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
44693 assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
44694 return pPager->mxPgno;
44698 ** The following set of routines are used to disable the simulated
44699 ** I/O error mechanism. These routines are used to avoid simulated
44700 ** errors in places where we do not care about errors.
44702 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
44703 ** and generate no code.
44705 #ifdef SQLITE_TEST
44706 SQLITE_API extern int sqlite3_io_error_pending;
44707 SQLITE_API extern int sqlite3_io_error_hit;
44708 static int saved_cnt;
44709 void disable_simulated_io_errors(void){
44710 saved_cnt = sqlite3_io_error_pending;
44711 sqlite3_io_error_pending = -1;
44713 void enable_simulated_io_errors(void){
44714 sqlite3_io_error_pending = saved_cnt;
44716 #else
44717 # define disable_simulated_io_errors()
44718 # define enable_simulated_io_errors()
44719 #endif
44722 ** Read the first N bytes from the beginning of the file into memory
44723 ** that pDest points to.
44725 ** If the pager was opened on a transient file (zFilename==""), or
44726 ** opened on a file less than N bytes in size, the output buffer is
44727 ** zeroed and SQLITE_OK returned. The rationale for this is that this
44728 ** function is used to read database headers, and a new transient or
44729 ** zero sized database has a header than consists entirely of zeroes.
44731 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
44732 ** the error code is returned to the caller and the contents of the
44733 ** output buffer undefined.
44735 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
44736 int rc = SQLITE_OK;
44737 memset(pDest, 0, N);
44738 assert( isOpen(pPager->fd) || pPager->tempFile );
44740 /* This routine is only called by btree immediately after creating
44741 ** the Pager object. There has not been an opportunity to transition
44742 ** to WAL mode yet.
44744 assert( !pagerUseWal(pPager) );
44746 if( isOpen(pPager->fd) ){
44747 IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
44748 rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
44749 if( rc==SQLITE_IOERR_SHORT_READ ){
44750 rc = SQLITE_OK;
44753 return rc;
44757 ** This function may only be called when a read-transaction is open on
44758 ** the pager. It returns the total number of pages in the database.
44760 ** However, if the file is between 1 and <page-size> bytes in size, then
44761 ** this is considered a 1 page file.
44763 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
44764 assert( pPager->eState>=PAGER_READER );
44765 assert( pPager->eState!=PAGER_WRITER_FINISHED );
44766 *pnPage = (int)pPager->dbSize;
44771 ** Try to obtain a lock of type locktype on the database file. If
44772 ** a similar or greater lock is already held, this function is a no-op
44773 ** (returning SQLITE_OK immediately).
44775 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
44776 ** the busy callback if the lock is currently not available. Repeat
44777 ** until the busy callback returns false or until the attempt to
44778 ** obtain the lock succeeds.
44780 ** Return SQLITE_OK on success and an error code if we cannot obtain
44781 ** the lock. If the lock is obtained successfully, set the Pager.state
44782 ** variable to locktype before returning.
44784 static int pager_wait_on_lock(Pager *pPager, int locktype){
44785 int rc; /* Return code */
44787 /* Check that this is either a no-op (because the requested lock is
44788 ** already held), or one of the transitions that the busy-handler
44789 ** may be invoked during, according to the comment above
44790 ** sqlite3PagerSetBusyhandler().
44792 assert( (pPager->eLock>=locktype)
44793 || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
44794 || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
44797 do {
44798 rc = pagerLockDb(pPager, locktype);
44799 }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
44800 return rc;
44804 ** Function assertTruncateConstraint(pPager) checks that one of the
44805 ** following is true for all dirty pages currently in the page-cache:
44807 ** a) The page number is less than or equal to the size of the
44808 ** current database image, in pages, OR
44810 ** b) if the page content were written at this time, it would not
44811 ** be necessary to write the current content out to the sub-journal
44812 ** (as determined by function subjRequiresPage()).
44814 ** If the condition asserted by this function were not true, and the
44815 ** dirty page were to be discarded from the cache via the pagerStress()
44816 ** routine, pagerStress() would not write the current page content to
44817 ** the database file. If a savepoint transaction were rolled back after
44818 ** this happened, the correct behavior would be to restore the current
44819 ** content of the page. However, since this content is not present in either
44820 ** the database file or the portion of the rollback journal and
44821 ** sub-journal rolled back the content could not be restored and the
44822 ** database image would become corrupt. It is therefore fortunate that
44823 ** this circumstance cannot arise.
44825 #if defined(SQLITE_DEBUG)
44826 static void assertTruncateConstraintCb(PgHdr *pPg){
44827 assert( pPg->flags&PGHDR_DIRTY );
44828 assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
44830 static void assertTruncateConstraint(Pager *pPager){
44831 sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
44833 #else
44834 # define assertTruncateConstraint(pPager)
44835 #endif
44838 ** Truncate the in-memory database file image to nPage pages. This
44839 ** function does not actually modify the database file on disk. It
44840 ** just sets the internal state of the pager object so that the
44841 ** truncation will be done when the current transaction is committed.
44843 ** This function is only called right before committing a transaction.
44844 ** Once this function has been called, the transaction must either be
44845 ** rolled back or committed. It is not safe to call this function and
44846 ** then continue writing to the database.
44848 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
44849 assert( pPager->dbSize>=nPage );
44850 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
44851 pPager->dbSize = nPage;
44853 /* At one point the code here called assertTruncateConstraint() to
44854 ** ensure that all pages being truncated away by this operation are,
44855 ** if one or more savepoints are open, present in the savepoint
44856 ** journal so that they can be restored if the savepoint is rolled
44857 ** back. This is no longer necessary as this function is now only
44858 ** called right before committing a transaction. So although the
44859 ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
44860 ** they cannot be rolled back. So the assertTruncateConstraint() call
44861 ** is no longer correct. */
44866 ** This function is called before attempting a hot-journal rollback. It
44867 ** syncs the journal file to disk, then sets pPager->journalHdr to the
44868 ** size of the journal file so that the pager_playback() routine knows
44869 ** that the entire journal file has been synced.
44871 ** Syncing a hot-journal to disk before attempting to roll it back ensures
44872 ** that if a power-failure occurs during the rollback, the process that
44873 ** attempts rollback following system recovery sees the same journal
44874 ** content as this process.
44876 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
44877 ** an SQLite error code.
44879 static int pagerSyncHotJournal(Pager *pPager){
44880 int rc = SQLITE_OK;
44881 if( !pPager->noSync ){
44882 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
44884 if( rc==SQLITE_OK ){
44885 rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
44887 return rc;
44891 ** Obtain a reference to a memory mapped page object for page number pgno.
44892 ** The new object will use the pointer pData, obtained from xFetch().
44893 ** If successful, set *ppPage to point to the new page reference
44894 ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
44895 ** *ppPage to zero.
44897 ** Page references obtained by calling this function should be released
44898 ** by calling pagerReleaseMapPage().
44900 static int pagerAcquireMapPage(
44901 Pager *pPager, /* Pager object */
44902 Pgno pgno, /* Page number */
44903 void *pData, /* xFetch()'d data for this page */
44904 PgHdr **ppPage /* OUT: Acquired page object */
44906 PgHdr *p; /* Memory mapped page to return */
44908 if( pPager->pMmapFreelist ){
44909 *ppPage = p = pPager->pMmapFreelist;
44910 pPager->pMmapFreelist = p->pDirty;
44911 p->pDirty = 0;
44912 memset(p->pExtra, 0, pPager->nExtra);
44913 }else{
44914 *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
44915 if( p==0 ){
44916 sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
44917 return SQLITE_NOMEM;
44919 p->pExtra = (void *)&p[1];
44920 p->flags = PGHDR_MMAP;
44921 p->nRef = 1;
44922 p->pPager = pPager;
44925 assert( p->pExtra==(void *)&p[1] );
44926 assert( p->pPage==0 );
44927 assert( p->flags==PGHDR_MMAP );
44928 assert( p->pPager==pPager );
44929 assert( p->nRef==1 );
44931 p->pgno = pgno;
44932 p->pData = pData;
44933 pPager->nMmapOut++;
44935 return SQLITE_OK;
44939 ** Release a reference to page pPg. pPg must have been returned by an
44940 ** earlier call to pagerAcquireMapPage().
44942 static void pagerReleaseMapPage(PgHdr *pPg){
44943 Pager *pPager = pPg->pPager;
44944 pPager->nMmapOut--;
44945 pPg->pDirty = pPager->pMmapFreelist;
44946 pPager->pMmapFreelist = pPg;
44948 assert( pPager->fd->pMethods->iVersion>=3 );
44949 sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
44953 ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
44955 static void pagerFreeMapHdrs(Pager *pPager){
44956 PgHdr *p;
44957 PgHdr *pNext;
44958 for(p=pPager->pMmapFreelist; p; p=pNext){
44959 pNext = p->pDirty;
44960 sqlite3_free(p);
44966 ** Shutdown the page cache. Free all memory and close all files.
44968 ** If a transaction was in progress when this routine is called, that
44969 ** transaction is rolled back. All outstanding pages are invalidated
44970 ** and their memory is freed. Any attempt to use a page associated
44971 ** with this page cache after this function returns will likely
44972 ** result in a coredump.
44974 ** This function always succeeds. If a transaction is active an attempt
44975 ** is made to roll it back. If an error occurs during the rollback
44976 ** a hot journal may be left in the filesystem but no error is returned
44977 ** to the caller.
44979 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
44980 u8 *pTmp = (u8 *)pPager->pTmpSpace;
44982 assert( assert_pager_state(pPager) );
44983 disable_simulated_io_errors();
44984 sqlite3BeginBenignMalloc();
44985 pagerFreeMapHdrs(pPager);
44986 /* pPager->errCode = 0; */
44987 pPager->exclusiveMode = 0;
44988 #ifndef SQLITE_OMIT_WAL
44989 sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
44990 pPager->pWal = 0;
44991 #endif
44992 pager_reset(pPager);
44993 if( MEMDB ){
44994 pager_unlock(pPager);
44995 }else{
44996 /* If it is open, sync the journal file before calling UnlockAndRollback.
44997 ** If this is not done, then an unsynced portion of the open journal
44998 ** file may be played back into the database. If a power failure occurs
44999 ** while this is happening, the database could become corrupt.
45001 ** If an error occurs while trying to sync the journal, shift the pager
45002 ** into the ERROR state. This causes UnlockAndRollback to unlock the
45003 ** database and close the journal file without attempting to roll it
45004 ** back or finalize it. The next database user will have to do hot-journal
45005 ** rollback before accessing the database file.
45007 if( isOpen(pPager->jfd) ){
45008 pager_error(pPager, pagerSyncHotJournal(pPager));
45010 pagerUnlockAndRollback(pPager);
45012 sqlite3EndBenignMalloc();
45013 enable_simulated_io_errors();
45014 PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
45015 IOTRACE(("CLOSE %p\n", pPager))
45016 sqlite3OsClose(pPager->jfd);
45017 sqlite3OsClose(pPager->fd);
45018 sqlite3PageFree(pTmp);
45019 sqlite3PcacheClose(pPager->pPCache);
45021 #ifdef SQLITE_HAS_CODEC
45022 if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
45023 #endif
45025 assert( !pPager->aSavepoint && !pPager->pInJournal );
45026 assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
45028 sqlite3_free(pPager);
45029 return SQLITE_OK;
45032 #if !defined(NDEBUG) || defined(SQLITE_TEST)
45034 ** Return the page number for page pPg.
45036 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
45037 return pPg->pgno;
45039 #endif
45042 ** Increment the reference count for page pPg.
45044 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
45045 sqlite3PcacheRef(pPg);
45049 ** Sync the journal. In other words, make sure all the pages that have
45050 ** been written to the journal have actually reached the surface of the
45051 ** disk and can be restored in the event of a hot-journal rollback.
45053 ** If the Pager.noSync flag is set, then this function is a no-op.
45054 ** Otherwise, the actions required depend on the journal-mode and the
45055 ** device characteristics of the file-system, as follows:
45057 ** * If the journal file is an in-memory journal file, no action need
45058 ** be taken.
45060 ** * Otherwise, if the device does not support the SAFE_APPEND property,
45061 ** then the nRec field of the most recently written journal header
45062 ** is updated to contain the number of journal records that have
45063 ** been written following it. If the pager is operating in full-sync
45064 ** mode, then the journal file is synced before this field is updated.
45066 ** * If the device does not support the SEQUENTIAL property, then
45067 ** journal file is synced.
45069 ** Or, in pseudo-code:
45071 ** if( NOT <in-memory journal> ){
45072 ** if( NOT SAFE_APPEND ){
45073 ** if( <full-sync mode> ) xSync(<journal file>);
45074 ** <update nRec field>
45075 ** }
45076 ** if( NOT SEQUENTIAL ) xSync(<journal file>);
45077 ** }
45079 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
45080 ** page currently held in memory before returning SQLITE_OK. If an IO
45081 ** error is encountered, then the IO error code is returned to the caller.
45083 static int syncJournal(Pager *pPager, int newHdr){
45084 int rc; /* Return code */
45086 assert( pPager->eState==PAGER_WRITER_CACHEMOD
45087 || pPager->eState==PAGER_WRITER_DBMOD
45089 assert( assert_pager_state(pPager) );
45090 assert( !pagerUseWal(pPager) );
45092 rc = sqlite3PagerExclusiveLock(pPager);
45093 if( rc!=SQLITE_OK ) return rc;
45095 if( !pPager->noSync ){
45096 assert( !pPager->tempFile );
45097 if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
45098 const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
45099 assert( isOpen(pPager->jfd) );
45101 if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
45102 /* This block deals with an obscure problem. If the last connection
45103 ** that wrote to this database was operating in persistent-journal
45104 ** mode, then the journal file may at this point actually be larger
45105 ** than Pager.journalOff bytes. If the next thing in the journal
45106 ** file happens to be a journal-header (written as part of the
45107 ** previous connection's transaction), and a crash or power-failure
45108 ** occurs after nRec is updated but before this connection writes
45109 ** anything else to the journal file (or commits/rolls back its
45110 ** transaction), then SQLite may become confused when doing the
45111 ** hot-journal rollback following recovery. It may roll back all
45112 ** of this connections data, then proceed to rolling back the old,
45113 ** out-of-date data that follows it. Database corruption.
45115 ** To work around this, if the journal file does appear to contain
45116 ** a valid header following Pager.journalOff, then write a 0x00
45117 ** byte to the start of it to prevent it from being recognized.
45119 ** Variable iNextHdrOffset is set to the offset at which this
45120 ** problematic header will occur, if it exists. aMagic is used
45121 ** as a temporary buffer to inspect the first couple of bytes of
45122 ** the potential journal header.
45124 i64 iNextHdrOffset;
45125 u8 aMagic[8];
45126 u8 zHeader[sizeof(aJournalMagic)+4];
45128 memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
45129 put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
45131 iNextHdrOffset = journalHdrOffset(pPager);
45132 rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
45133 if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
45134 static const u8 zerobyte = 0;
45135 rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
45137 if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
45138 return rc;
45141 /* Write the nRec value into the journal file header. If in
45142 ** full-synchronous mode, sync the journal first. This ensures that
45143 ** all data has really hit the disk before nRec is updated to mark
45144 ** it as a candidate for rollback.
45146 ** This is not required if the persistent media supports the
45147 ** SAFE_APPEND property. Because in this case it is not possible
45148 ** for garbage data to be appended to the file, the nRec field
45149 ** is populated with 0xFFFFFFFF when the journal header is written
45150 ** and never needs to be updated.
45152 if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
45153 PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
45154 IOTRACE(("JSYNC %p\n", pPager))
45155 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
45156 if( rc!=SQLITE_OK ) return rc;
45158 IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
45159 rc = sqlite3OsWrite(
45160 pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
45162 if( rc!=SQLITE_OK ) return rc;
45164 if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
45165 PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
45166 IOTRACE(("JSYNC %p\n", pPager))
45167 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
45168 (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
45170 if( rc!=SQLITE_OK ) return rc;
45173 pPager->journalHdr = pPager->journalOff;
45174 if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
45175 pPager->nRec = 0;
45176 rc = writeJournalHdr(pPager);
45177 if( rc!=SQLITE_OK ) return rc;
45179 }else{
45180 pPager->journalHdr = pPager->journalOff;
45184 /* Unless the pager is in noSync mode, the journal file was just
45185 ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
45186 ** all pages.
45188 sqlite3PcacheClearSyncFlags(pPager->pPCache);
45189 pPager->eState = PAGER_WRITER_DBMOD;
45190 assert( assert_pager_state(pPager) );
45191 return SQLITE_OK;
45195 ** The argument is the first in a linked list of dirty pages connected
45196 ** by the PgHdr.pDirty pointer. This function writes each one of the
45197 ** in-memory pages in the list to the database file. The argument may
45198 ** be NULL, representing an empty list. In this case this function is
45199 ** a no-op.
45201 ** The pager must hold at least a RESERVED lock when this function
45202 ** is called. Before writing anything to the database file, this lock
45203 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
45204 ** SQLITE_BUSY is returned and no data is written to the database file.
45206 ** If the pager is a temp-file pager and the actual file-system file
45207 ** is not yet open, it is created and opened before any data is
45208 ** written out.
45210 ** Once the lock has been upgraded and, if necessary, the file opened,
45211 ** the pages are written out to the database file in list order. Writing
45212 ** a page is skipped if it meets either of the following criteria:
45214 ** * The page number is greater than Pager.dbSize, or
45215 ** * The PGHDR_DONT_WRITE flag is set on the page.
45217 ** If writing out a page causes the database file to grow, Pager.dbFileSize
45218 ** is updated accordingly. If page 1 is written out, then the value cached
45219 ** in Pager.dbFileVers[] is updated to match the new value stored in
45220 ** the database file.
45222 ** If everything is successful, SQLITE_OK is returned. If an IO error
45223 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
45224 ** be obtained, SQLITE_BUSY is returned.
45226 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
45227 int rc = SQLITE_OK; /* Return code */
45229 /* This function is only called for rollback pagers in WRITER_DBMOD state. */
45230 assert( !pagerUseWal(pPager) );
45231 assert( pPager->eState==PAGER_WRITER_DBMOD );
45232 assert( pPager->eLock==EXCLUSIVE_LOCK );
45234 /* If the file is a temp-file has not yet been opened, open it now. It
45235 ** is not possible for rc to be other than SQLITE_OK if this branch
45236 ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
45238 if( !isOpen(pPager->fd) ){
45239 assert( pPager->tempFile && rc==SQLITE_OK );
45240 rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
45243 /* Before the first write, give the VFS a hint of what the final
45244 ** file size will be.
45246 assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
45247 if( rc==SQLITE_OK
45248 && pPager->dbHintSize<pPager->dbSize
45249 && (pList->pDirty || pList->pgno>pPager->dbHintSize)
45251 sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
45252 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
45253 pPager->dbHintSize = pPager->dbSize;
45256 while( rc==SQLITE_OK && pList ){
45257 Pgno pgno = pList->pgno;
45259 /* If there are dirty pages in the page cache with page numbers greater
45260 ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
45261 ** make the file smaller (presumably by auto-vacuum code). Do not write
45262 ** any such pages to the file.
45264 ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
45265 ** set (set by sqlite3PagerDontWrite()).
45267 if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
45268 i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
45269 char *pData; /* Data to write */
45271 assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
45272 if( pList->pgno==1 ) pager_write_changecounter(pList);
45274 /* Encode the database */
45275 CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
45277 /* Write out the page data. */
45278 rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
45280 /* If page 1 was just written, update Pager.dbFileVers to match
45281 ** the value now stored in the database file. If writing this
45282 ** page caused the database file to grow, update dbFileSize.
45284 if( pgno==1 ){
45285 memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
45287 if( pgno>pPager->dbFileSize ){
45288 pPager->dbFileSize = pgno;
45290 pPager->aStat[PAGER_STAT_WRITE]++;
45292 /* Update any backup objects copying the contents of this pager. */
45293 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
45295 PAGERTRACE(("STORE %d page %d hash(%08x)\n",
45296 PAGERID(pPager), pgno, pager_pagehash(pList)));
45297 IOTRACE(("PGOUT %p %d\n", pPager, pgno));
45298 PAGER_INCR(sqlite3_pager_writedb_count);
45299 }else{
45300 PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
45302 pager_set_pagehash(pList);
45303 pList = pList->pDirty;
45306 return rc;
45310 ** Ensure that the sub-journal file is open. If it is already open, this
45311 ** function is a no-op.
45313 ** SQLITE_OK is returned if everything goes according to plan. An
45314 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
45315 ** fails.
45317 static int openSubJournal(Pager *pPager){
45318 int rc = SQLITE_OK;
45319 if( !isOpen(pPager->sjfd) ){
45320 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
45321 sqlite3MemJournalOpen(pPager->sjfd);
45322 }else{
45323 rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
45326 return rc;
45330 ** Append a record of the current state of page pPg to the sub-journal.
45331 ** It is the callers responsibility to use subjRequiresPage() to check
45332 ** that it is really required before calling this function.
45334 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
45335 ** for all open savepoints before returning.
45337 ** This function returns SQLITE_OK if everything is successful, an IO
45338 ** error code if the attempt to write to the sub-journal fails, or
45339 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
45340 ** bitvec.
45342 static int subjournalPage(PgHdr *pPg){
45343 int rc = SQLITE_OK;
45344 Pager *pPager = pPg->pPager;
45345 if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
45347 /* Open the sub-journal, if it has not already been opened */
45348 assert( pPager->useJournal );
45349 assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
45350 assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
45351 assert( pagerUseWal(pPager)
45352 || pageInJournal(pPager, pPg)
45353 || pPg->pgno>pPager->dbOrigSize
45355 rc = openSubJournal(pPager);
45357 /* If the sub-journal was opened successfully (or was already open),
45358 ** write the journal record into the file. */
45359 if( rc==SQLITE_OK ){
45360 void *pData = pPg->pData;
45361 i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
45362 char *pData2;
45364 CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
45365 PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
45366 rc = write32bits(pPager->sjfd, offset, pPg->pgno);
45367 if( rc==SQLITE_OK ){
45368 rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
45372 if( rc==SQLITE_OK ){
45373 pPager->nSubRec++;
45374 assert( pPager->nSavepoint>0 );
45375 rc = addToSavepointBitvecs(pPager, pPg->pgno);
45377 return rc;
45381 ** This function is called by the pcache layer when it has reached some
45382 ** soft memory limit. The first argument is a pointer to a Pager object
45383 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
45384 ** database). The second argument is a reference to a page that is
45385 ** currently dirty but has no outstanding references. The page
45386 ** is always associated with the Pager object passed as the first
45387 ** argument.
45389 ** The job of this function is to make pPg clean by writing its contents
45390 ** out to the database file, if possible. This may involve syncing the
45391 ** journal file.
45393 ** If successful, sqlite3PcacheMakeClean() is called on the page and
45394 ** SQLITE_OK returned. If an IO error occurs while trying to make the
45395 ** page clean, the IO error code is returned. If the page cannot be
45396 ** made clean for some other reason, but no error occurs, then SQLITE_OK
45397 ** is returned by sqlite3PcacheMakeClean() is not called.
45399 static int pagerStress(void *p, PgHdr *pPg){
45400 Pager *pPager = (Pager *)p;
45401 int rc = SQLITE_OK;
45403 assert( pPg->pPager==pPager );
45404 assert( pPg->flags&PGHDR_DIRTY );
45406 /* The doNotSpill NOSYNC bit is set during times when doing a sync of
45407 ** journal (and adding a new header) is not allowed. This occurs
45408 ** during calls to sqlite3PagerWrite() while trying to journal multiple
45409 ** pages belonging to the same sector.
45411 ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
45412 ** regardless of whether or not a sync is required. This is set during
45413 ** a rollback or by user request, respectively.
45415 ** Spilling is also prohibited when in an error state since that could
45416 ** lead to database corruption. In the current implementation it
45417 ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
45418 ** while in the error state, hence it is impossible for this routine to
45419 ** be called in the error state. Nevertheless, we include a NEVER()
45420 ** test for the error state as a safeguard against future changes.
45422 if( NEVER(pPager->errCode) ) return SQLITE_OK;
45423 testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
45424 testcase( pPager->doNotSpill & SPILLFLAG_OFF );
45425 testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
45426 if( pPager->doNotSpill
45427 && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
45428 || (pPg->flags & PGHDR_NEED_SYNC)!=0)
45430 return SQLITE_OK;
45433 pPg->pDirty = 0;
45434 if( pagerUseWal(pPager) ){
45435 /* Write a single frame for this page to the log. */
45436 if( subjRequiresPage(pPg) ){
45437 rc = subjournalPage(pPg);
45439 if( rc==SQLITE_OK ){
45440 rc = pagerWalFrames(pPager, pPg, 0, 0);
45442 }else{
45444 /* Sync the journal file if required. */
45445 if( pPg->flags&PGHDR_NEED_SYNC
45446 || pPager->eState==PAGER_WRITER_CACHEMOD
45448 rc = syncJournal(pPager, 1);
45451 /* If the page number of this page is larger than the current size of
45452 ** the database image, it may need to be written to the sub-journal.
45453 ** This is because the call to pager_write_pagelist() below will not
45454 ** actually write data to the file in this case.
45456 ** Consider the following sequence of events:
45458 ** BEGIN;
45459 ** <journal page X>
45460 ** <modify page X>
45461 ** SAVEPOINT sp;
45462 ** <shrink database file to Y pages>
45463 ** pagerStress(page X)
45464 ** ROLLBACK TO sp;
45466 ** If (X>Y), then when pagerStress is called page X will not be written
45467 ** out to the database file, but will be dropped from the cache. Then,
45468 ** following the "ROLLBACK TO sp" statement, reading page X will read
45469 ** data from the database file. This will be the copy of page X as it
45470 ** was when the transaction started, not as it was when "SAVEPOINT sp"
45471 ** was executed.
45473 ** The solution is to write the current data for page X into the
45474 ** sub-journal file now (if it is not already there), so that it will
45475 ** be restored to its current value when the "ROLLBACK TO sp" is
45476 ** executed.
45478 if( NEVER(
45479 rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
45480 ) ){
45481 rc = subjournalPage(pPg);
45484 /* Write the contents of the page out to the database file. */
45485 if( rc==SQLITE_OK ){
45486 assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
45487 rc = pager_write_pagelist(pPager, pPg);
45491 /* Mark the page as clean. */
45492 if( rc==SQLITE_OK ){
45493 PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
45494 sqlite3PcacheMakeClean(pPg);
45497 return pager_error(pPager, rc);
45502 ** Allocate and initialize a new Pager object and put a pointer to it
45503 ** in *ppPager. The pager should eventually be freed by passing it
45504 ** to sqlite3PagerClose().
45506 ** The zFilename argument is the path to the database file to open.
45507 ** If zFilename is NULL then a randomly-named temporary file is created
45508 ** and used as the file to be cached. Temporary files are be deleted
45509 ** automatically when they are closed. If zFilename is ":memory:" then
45510 ** all information is held in cache. It is never written to disk.
45511 ** This can be used to implement an in-memory database.
45513 ** The nExtra parameter specifies the number of bytes of space allocated
45514 ** along with each page reference. This space is available to the user
45515 ** via the sqlite3PagerGetExtra() API.
45517 ** The flags argument is used to specify properties that affect the
45518 ** operation of the pager. It should be passed some bitwise combination
45519 ** of the PAGER_* flags.
45521 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
45522 ** of the xOpen() method of the supplied VFS when opening files.
45524 ** If the pager object is allocated and the specified file opened
45525 ** successfully, SQLITE_OK is returned and *ppPager set to point to
45526 ** the new pager object. If an error occurs, *ppPager is set to NULL
45527 ** and error code returned. This function may return SQLITE_NOMEM
45528 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
45529 ** various SQLITE_IO_XXX errors.
45531 SQLITE_PRIVATE int sqlite3PagerOpen(
45532 sqlite3_vfs *pVfs, /* The virtual file system to use */
45533 Pager **ppPager, /* OUT: Return the Pager structure here */
45534 const char *zFilename, /* Name of the database file to open */
45535 int nExtra, /* Extra bytes append to each in-memory page */
45536 int flags, /* flags controlling this file */
45537 int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
45538 void (*xReinit)(DbPage*) /* Function to reinitialize pages */
45540 u8 *pPtr;
45541 Pager *pPager = 0; /* Pager object to allocate and return */
45542 int rc = SQLITE_OK; /* Return code */
45543 int tempFile = 0; /* True for temp files (incl. in-memory files) */
45544 int memDb = 0; /* True if this is an in-memory file */
45545 int readOnly = 0; /* True if this is a read-only file */
45546 int journalFileSize; /* Bytes to allocate for each journal fd */
45547 char *zPathname = 0; /* Full path to database file */
45548 int nPathname = 0; /* Number of bytes in zPathname */
45549 int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
45550 int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
45551 u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
45552 const char *zUri = 0; /* URI args to copy */
45553 int nUri = 0; /* Number of bytes of URI args at *zUri */
45555 /* Figure out how much space is required for each journal file-handle
45556 ** (there are two of them, the main journal and the sub-journal). This
45557 ** is the maximum space required for an in-memory journal file handle
45558 ** and a regular journal file-handle. Note that a "regular journal-handle"
45559 ** may be a wrapper capable of caching the first portion of the journal
45560 ** file in memory to implement the atomic-write optimization (see
45561 ** source file journal.c).
45563 if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
45564 journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
45565 }else{
45566 journalFileSize = ROUND8(sqlite3MemJournalSize());
45569 /* Set the output variable to NULL in case an error occurs. */
45570 *ppPager = 0;
45572 #ifndef SQLITE_OMIT_MEMORYDB
45573 if( flags & PAGER_MEMORY ){
45574 memDb = 1;
45575 if( zFilename && zFilename[0] ){
45576 zPathname = sqlite3DbStrDup(0, zFilename);
45577 if( zPathname==0 ) return SQLITE_NOMEM;
45578 nPathname = sqlite3Strlen30(zPathname);
45579 zFilename = 0;
45582 #endif
45584 /* Compute and store the full pathname in an allocated buffer pointed
45585 ** to by zPathname, length nPathname. Or, if this is a temporary file,
45586 ** leave both nPathname and zPathname set to 0.
45588 if( zFilename && zFilename[0] ){
45589 const char *z;
45590 nPathname = pVfs->mxPathname+1;
45591 zPathname = sqlite3DbMallocRaw(0, nPathname*2);
45592 if( zPathname==0 ){
45593 return SQLITE_NOMEM;
45595 zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
45596 rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
45597 nPathname = sqlite3Strlen30(zPathname);
45598 z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
45599 while( *z ){
45600 z += sqlite3Strlen30(z)+1;
45601 z += sqlite3Strlen30(z)+1;
45603 nUri = (int)(&z[1] - zUri);
45604 assert( nUri>=0 );
45605 if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
45606 /* This branch is taken when the journal path required by
45607 ** the database being opened will be more than pVfs->mxPathname
45608 ** bytes in length. This means the database cannot be opened,
45609 ** as it will not be possible to open the journal file or even
45610 ** check for a hot-journal before reading.
45612 rc = SQLITE_CANTOPEN_BKPT;
45614 if( rc!=SQLITE_OK ){
45615 sqlite3DbFree(0, zPathname);
45616 return rc;
45620 /* Allocate memory for the Pager structure, PCache object, the
45621 ** three file descriptors, the database file name and the journal
45622 ** file name. The layout in memory is as follows:
45624 ** Pager object (sizeof(Pager) bytes)
45625 ** PCache object (sqlite3PcacheSize() bytes)
45626 ** Database file handle (pVfs->szOsFile bytes)
45627 ** Sub-journal file handle (journalFileSize bytes)
45628 ** Main journal file handle (journalFileSize bytes)
45629 ** Database file name (nPathname+1 bytes)
45630 ** Journal file name (nPathname+8+1 bytes)
45632 pPtr = (u8 *)sqlite3MallocZero(
45633 ROUND8(sizeof(*pPager)) + /* Pager structure */
45634 ROUND8(pcacheSize) + /* PCache object */
45635 ROUND8(pVfs->szOsFile) + /* The main db file */
45636 journalFileSize * 2 + /* The two journal files */
45637 nPathname + 1 + nUri + /* zFilename */
45638 nPathname + 8 + 2 /* zJournal */
45639 #ifndef SQLITE_OMIT_WAL
45640 + nPathname + 4 + 2 /* zWal */
45641 #endif
45643 assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
45644 if( !pPtr ){
45645 sqlite3DbFree(0, zPathname);
45646 return SQLITE_NOMEM;
45648 pPager = (Pager*)(pPtr);
45649 pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
45650 pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
45651 pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
45652 pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
45653 pPager->zFilename = (char*)(pPtr += journalFileSize);
45654 assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
45656 /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
45657 if( zPathname ){
45658 assert( nPathname>0 );
45659 pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
45660 memcpy(pPager->zFilename, zPathname, nPathname);
45661 if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
45662 memcpy(pPager->zJournal, zPathname, nPathname);
45663 memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
45664 sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
45665 #ifndef SQLITE_OMIT_WAL
45666 pPager->zWal = &pPager->zJournal[nPathname+8+1];
45667 memcpy(pPager->zWal, zPathname, nPathname);
45668 memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
45669 sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
45670 #endif
45671 sqlite3DbFree(0, zPathname);
45673 pPager->pVfs = pVfs;
45674 pPager->vfsFlags = vfsFlags;
45676 /* Open the pager file.
45678 if( zFilename && zFilename[0] ){
45679 int fout = 0; /* VFS flags returned by xOpen() */
45680 rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
45681 assert( !memDb );
45682 readOnly = (fout&SQLITE_OPEN_READONLY);
45684 /* If the file was successfully opened for read/write access,
45685 ** choose a default page size in case we have to create the
45686 ** database file. The default page size is the maximum of:
45688 ** + SQLITE_DEFAULT_PAGE_SIZE,
45689 ** + The value returned by sqlite3OsSectorSize()
45690 ** + The largest page size that can be written atomically.
45692 if( rc==SQLITE_OK ){
45693 int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
45694 if( !readOnly ){
45695 setSectorSize(pPager);
45696 assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
45697 if( szPageDflt<pPager->sectorSize ){
45698 if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
45699 szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
45700 }else{
45701 szPageDflt = (u32)pPager->sectorSize;
45704 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
45706 int ii;
45707 assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
45708 assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
45709 assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
45710 for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
45711 if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
45712 szPageDflt = ii;
45716 #endif
45718 pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
45719 if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
45720 || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
45721 vfsFlags |= SQLITE_OPEN_READONLY;
45722 goto act_like_temp_file;
45725 }else{
45726 /* If a temporary file is requested, it is not opened immediately.
45727 ** In this case we accept the default page size and delay actually
45728 ** opening the file until the first call to OsWrite().
45730 ** This branch is also run for an in-memory database. An in-memory
45731 ** database is the same as a temp-file that is never written out to
45732 ** disk and uses an in-memory rollback journal.
45734 ** This branch also runs for files marked as immutable.
45736 act_like_temp_file:
45737 tempFile = 1;
45738 pPager->eState = PAGER_READER; /* Pretend we already have a lock */
45739 pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE locking mode */
45740 pPager->noLock = 1; /* Do no locking */
45741 readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
45744 /* The following call to PagerSetPagesize() serves to set the value of
45745 ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
45747 if( rc==SQLITE_OK ){
45748 assert( pPager->memDb==0 );
45749 rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
45750 testcase( rc!=SQLITE_OK );
45753 /* Initialize the PCache object. */
45754 if( rc==SQLITE_OK ){
45755 assert( nExtra<1000 );
45756 nExtra = ROUND8(nExtra);
45757 rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
45758 !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
45761 /* If an error occurred above, free the Pager structure and close the file.
45763 if( rc!=SQLITE_OK ){
45764 sqlite3OsClose(pPager->fd);
45765 sqlite3PageFree(pPager->pTmpSpace);
45766 sqlite3_free(pPager);
45767 return rc;
45770 PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
45771 IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
45773 pPager->useJournal = (u8)useJournal;
45774 /* pPager->stmtOpen = 0; */
45775 /* pPager->stmtInUse = 0; */
45776 /* pPager->nRef = 0; */
45777 /* pPager->stmtSize = 0; */
45778 /* pPager->stmtJSize = 0; */
45779 /* pPager->nPage = 0; */
45780 pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
45781 /* pPager->state = PAGER_UNLOCK; */
45782 /* pPager->errMask = 0; */
45783 pPager->tempFile = (u8)tempFile;
45784 assert( tempFile==PAGER_LOCKINGMODE_NORMAL
45785 || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
45786 assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
45787 pPager->exclusiveMode = (u8)tempFile;
45788 pPager->changeCountDone = pPager->tempFile;
45789 pPager->memDb = (u8)memDb;
45790 pPager->readOnly = (u8)readOnly;
45791 assert( useJournal || pPager->tempFile );
45792 pPager->noSync = pPager->tempFile;
45793 if( pPager->noSync ){
45794 assert( pPager->fullSync==0 );
45795 assert( pPager->syncFlags==0 );
45796 assert( pPager->walSyncFlags==0 );
45797 assert( pPager->ckptSyncFlags==0 );
45798 }else{
45799 pPager->fullSync = 1;
45800 pPager->syncFlags = SQLITE_SYNC_NORMAL;
45801 pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
45802 pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
45804 /* pPager->pFirst = 0; */
45805 /* pPager->pFirstSynced = 0; */
45806 /* pPager->pLast = 0; */
45807 pPager->nExtra = (u16)nExtra;
45808 pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
45809 assert( isOpen(pPager->fd) || tempFile );
45810 setSectorSize(pPager);
45811 if( !useJournal ){
45812 pPager->journalMode = PAGER_JOURNALMODE_OFF;
45813 }else if( memDb ){
45814 pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
45816 /* pPager->xBusyHandler = 0; */
45817 /* pPager->pBusyHandlerArg = 0; */
45818 pPager->xReiniter = xReinit;
45819 /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
45820 /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
45822 *ppPager = pPager;
45823 return SQLITE_OK;
45827 /* Verify that the database file has not be deleted or renamed out from
45828 ** under the pager. Return SQLITE_OK if the database is still were it ought
45829 ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
45830 ** code from sqlite3OsAccess()) if the database has gone missing.
45832 static int databaseIsUnmoved(Pager *pPager){
45833 int bHasMoved = 0;
45834 int rc;
45836 if( pPager->tempFile ) return SQLITE_OK;
45837 if( pPager->dbSize==0 ) return SQLITE_OK;
45838 assert( pPager->zFilename && pPager->zFilename[0] );
45839 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
45840 if( rc==SQLITE_NOTFOUND ){
45841 /* If the HAS_MOVED file-control is unimplemented, assume that the file
45842 ** has not been moved. That is the historical behavior of SQLite: prior to
45843 ** version 3.8.3, it never checked */
45844 rc = SQLITE_OK;
45845 }else if( rc==SQLITE_OK && bHasMoved ){
45846 rc = SQLITE_READONLY_DBMOVED;
45848 return rc;
45853 ** This function is called after transitioning from PAGER_UNLOCK to
45854 ** PAGER_SHARED state. It tests if there is a hot journal present in
45855 ** the file-system for the given pager. A hot journal is one that
45856 ** needs to be played back. According to this function, a hot-journal
45857 ** file exists if the following criteria are met:
45859 ** * The journal file exists in the file system, and
45860 ** * No process holds a RESERVED or greater lock on the database file, and
45861 ** * The database file itself is greater than 0 bytes in size, and
45862 ** * The first byte of the journal file exists and is not 0x00.
45864 ** If the current size of the database file is 0 but a journal file
45865 ** exists, that is probably an old journal left over from a prior
45866 ** database with the same name. In this case the journal file is
45867 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
45868 ** is returned.
45870 ** This routine does not check if there is a master journal filename
45871 ** at the end of the file. If there is, and that master journal file
45872 ** does not exist, then the journal file is not really hot. In this
45873 ** case this routine will return a false-positive. The pager_playback()
45874 ** routine will discover that the journal file is not really hot and
45875 ** will not roll it back.
45877 ** If a hot-journal file is found to exist, *pExists is set to 1 and
45878 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
45879 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
45880 ** to determine whether or not a hot-journal file exists, the IO error
45881 ** code is returned and the value of *pExists is undefined.
45883 static int hasHotJournal(Pager *pPager, int *pExists){
45884 sqlite3_vfs * const pVfs = pPager->pVfs;
45885 int rc = SQLITE_OK; /* Return code */
45886 int exists = 1; /* True if a journal file is present */
45887 int jrnlOpen = !!isOpen(pPager->jfd);
45889 assert( pPager->useJournal );
45890 assert( isOpen(pPager->fd) );
45891 assert( pPager->eState==PAGER_OPEN );
45893 assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
45894 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
45897 *pExists = 0;
45898 if( !jrnlOpen ){
45899 rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
45901 if( rc==SQLITE_OK && exists ){
45902 int locked = 0; /* True if some process holds a RESERVED lock */
45904 /* Race condition here: Another process might have been holding the
45905 ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
45906 ** call above, but then delete the journal and drop the lock before
45907 ** we get to the following sqlite3OsCheckReservedLock() call. If that
45908 ** is the case, this routine might think there is a hot journal when
45909 ** in fact there is none. This results in a false-positive which will
45910 ** be dealt with by the playback routine. Ticket #3883.
45912 rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
45913 if( rc==SQLITE_OK && !locked ){
45914 Pgno nPage; /* Number of pages in database file */
45916 rc = pagerPagecount(pPager, &nPage);
45917 if( rc==SQLITE_OK ){
45918 /* If the database is zero pages in size, that means that either (1) the
45919 ** journal is a remnant from a prior database with the same name where
45920 ** the database file but not the journal was deleted, or (2) the initial
45921 ** transaction that populates a new database is being rolled back.
45922 ** In either case, the journal file can be deleted. However, take care
45923 ** not to delete the journal file if it is already open due to
45924 ** journal_mode=PERSIST.
45926 if( nPage==0 && !jrnlOpen ){
45927 sqlite3BeginBenignMalloc();
45928 if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
45929 sqlite3OsDelete(pVfs, pPager->zJournal, 0);
45930 if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
45932 sqlite3EndBenignMalloc();
45933 }else{
45934 /* The journal file exists and no other connection has a reserved
45935 ** or greater lock on the database file. Now check that there is
45936 ** at least one non-zero bytes at the start of the journal file.
45937 ** If there is, then we consider this journal to be hot. If not,
45938 ** it can be ignored.
45940 if( !jrnlOpen ){
45941 int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
45942 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
45944 if( rc==SQLITE_OK ){
45945 u8 first = 0;
45946 rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
45947 if( rc==SQLITE_IOERR_SHORT_READ ){
45948 rc = SQLITE_OK;
45950 if( !jrnlOpen ){
45951 sqlite3OsClose(pPager->jfd);
45953 *pExists = (first!=0);
45954 }else if( rc==SQLITE_CANTOPEN ){
45955 /* If we cannot open the rollback journal file in order to see if
45956 ** it has a zero header, that might be due to an I/O error, or
45957 ** it might be due to the race condition described above and in
45958 ** ticket #3883. Either way, assume that the journal is hot.
45959 ** This might be a false positive. But if it is, then the
45960 ** automatic journal playback and recovery mechanism will deal
45961 ** with it under an EXCLUSIVE lock where we do not need to
45962 ** worry so much with race conditions.
45964 *pExists = 1;
45965 rc = SQLITE_OK;
45972 return rc;
45976 ** This function is called to obtain a shared lock on the database file.
45977 ** It is illegal to call sqlite3PagerAcquire() until after this function
45978 ** has been successfully called. If a shared-lock is already held when
45979 ** this function is called, it is a no-op.
45981 ** The following operations are also performed by this function.
45983 ** 1) If the pager is currently in PAGER_OPEN state (no lock held
45984 ** on the database file), then an attempt is made to obtain a
45985 ** SHARED lock on the database file. Immediately after obtaining
45986 ** the SHARED lock, the file-system is checked for a hot-journal,
45987 ** which is played back if present. Following any hot-journal
45988 ** rollback, the contents of the cache are validated by checking
45989 ** the 'change-counter' field of the database file header and
45990 ** discarded if they are found to be invalid.
45992 ** 2) If the pager is running in exclusive-mode, and there are currently
45993 ** no outstanding references to any pages, and is in the error state,
45994 ** then an attempt is made to clear the error state by discarding
45995 ** the contents of the page cache and rolling back any open journal
45996 ** file.
45998 ** If everything is successful, SQLITE_OK is returned. If an IO error
45999 ** occurs while locking the database, checking for a hot-journal file or
46000 ** rolling back a journal file, the IO error code is returned.
46002 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
46003 int rc = SQLITE_OK; /* Return code */
46005 /* This routine is only called from b-tree and only when there are no
46006 ** outstanding pages. This implies that the pager state should either
46007 ** be OPEN or READER. READER is only possible if the pager is or was in
46008 ** exclusive access mode.
46010 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
46011 assert( assert_pager_state(pPager) );
46012 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
46013 if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
46015 if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
46016 int bHotJournal = 1; /* True if there exists a hot journal-file */
46018 assert( !MEMDB );
46020 rc = pager_wait_on_lock(pPager, SHARED_LOCK);
46021 if( rc!=SQLITE_OK ){
46022 assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
46023 goto failed;
46026 /* If a journal file exists, and there is no RESERVED lock on the
46027 ** database file, then it either needs to be played back or deleted.
46029 if( pPager->eLock<=SHARED_LOCK ){
46030 rc = hasHotJournal(pPager, &bHotJournal);
46032 if( rc!=SQLITE_OK ){
46033 goto failed;
46035 if( bHotJournal ){
46036 if( pPager->readOnly ){
46037 rc = SQLITE_READONLY_ROLLBACK;
46038 goto failed;
46041 /* Get an EXCLUSIVE lock on the database file. At this point it is
46042 ** important that a RESERVED lock is not obtained on the way to the
46043 ** EXCLUSIVE lock. If it were, another process might open the
46044 ** database file, detect the RESERVED lock, and conclude that the
46045 ** database is safe to read while this process is still rolling the
46046 ** hot-journal back.
46048 ** Because the intermediate RESERVED lock is not requested, any
46049 ** other process attempting to access the database file will get to
46050 ** this point in the code and fail to obtain its own EXCLUSIVE lock
46051 ** on the database file.
46053 ** Unless the pager is in locking_mode=exclusive mode, the lock is
46054 ** downgraded to SHARED_LOCK before this function returns.
46056 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
46057 if( rc!=SQLITE_OK ){
46058 goto failed;
46061 /* If it is not already open and the file exists on disk, open the
46062 ** journal for read/write access. Write access is required because
46063 ** in exclusive-access mode the file descriptor will be kept open
46064 ** and possibly used for a transaction later on. Also, write-access
46065 ** is usually required to finalize the journal in journal_mode=persist
46066 ** mode (and also for journal_mode=truncate on some systems).
46068 ** If the journal does not exist, it usually means that some
46069 ** other connection managed to get in and roll it back before
46070 ** this connection obtained the exclusive lock above. Or, it
46071 ** may mean that the pager was in the error-state when this
46072 ** function was called and the journal file does not exist.
46074 if( !isOpen(pPager->jfd) ){
46075 sqlite3_vfs * const pVfs = pPager->pVfs;
46076 int bExists; /* True if journal file exists */
46077 rc = sqlite3OsAccess(
46078 pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
46079 if( rc==SQLITE_OK && bExists ){
46080 int fout = 0;
46081 int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
46082 assert( !pPager->tempFile );
46083 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
46084 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
46085 if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
46086 rc = SQLITE_CANTOPEN_BKPT;
46087 sqlite3OsClose(pPager->jfd);
46092 /* Playback and delete the journal. Drop the database write
46093 ** lock and reacquire the read lock. Purge the cache before
46094 ** playing back the hot-journal so that we don't end up with
46095 ** an inconsistent cache. Sync the hot journal before playing
46096 ** it back since the process that crashed and left the hot journal
46097 ** probably did not sync it and we are required to always sync
46098 ** the journal before playing it back.
46100 if( isOpen(pPager->jfd) ){
46101 assert( rc==SQLITE_OK );
46102 rc = pagerSyncHotJournal(pPager);
46103 if( rc==SQLITE_OK ){
46104 rc = pager_playback(pPager, 1);
46105 pPager->eState = PAGER_OPEN;
46107 }else if( !pPager->exclusiveMode ){
46108 pagerUnlockDb(pPager, SHARED_LOCK);
46111 if( rc!=SQLITE_OK ){
46112 /* This branch is taken if an error occurs while trying to open
46113 ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
46114 ** pager_unlock() routine will be called before returning to unlock
46115 ** the file. If the unlock attempt fails, then Pager.eLock must be
46116 ** set to UNKNOWN_LOCK (see the comment above the #define for
46117 ** UNKNOWN_LOCK above for an explanation).
46119 ** In order to get pager_unlock() to do this, set Pager.eState to
46120 ** PAGER_ERROR now. This is not actually counted as a transition
46121 ** to ERROR state in the state diagram at the top of this file,
46122 ** since we know that the same call to pager_unlock() will very
46123 ** shortly transition the pager object to the OPEN state. Calling
46124 ** assert_pager_state() would fail now, as it should not be possible
46125 ** to be in ERROR state when there are zero outstanding page
46126 ** references.
46128 pager_error(pPager, rc);
46129 goto failed;
46132 assert( pPager->eState==PAGER_OPEN );
46133 assert( (pPager->eLock==SHARED_LOCK)
46134 || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
46138 if( !pPager->tempFile && (
46139 pPager->pBackup
46140 || sqlite3PcachePagecount(pPager->pPCache)>0
46141 || USEFETCH(pPager)
46143 /* The shared-lock has just been acquired on the database file
46144 ** and there are already pages in the cache (from a previous
46145 ** read or write transaction). Check to see if the database
46146 ** has been modified. If the database has changed, flush the
46147 ** cache.
46149 ** Database changes is detected by looking at 15 bytes beginning
46150 ** at offset 24 into the file. The first 4 of these 16 bytes are
46151 ** a 32-bit counter that is incremented with each change. The
46152 ** other bytes change randomly with each file change when
46153 ** a codec is in use.
46155 ** There is a vanishingly small chance that a change will not be
46156 ** detected. The chance of an undetected change is so small that
46157 ** it can be neglected.
46159 Pgno nPage = 0;
46160 char dbFileVers[sizeof(pPager->dbFileVers)];
46162 rc = pagerPagecount(pPager, &nPage);
46163 if( rc ) goto failed;
46165 if( nPage>0 ){
46166 IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
46167 rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
46168 if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
46169 goto failed;
46171 }else{
46172 memset(dbFileVers, 0, sizeof(dbFileVers));
46175 if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
46176 pager_reset(pPager);
46178 /* Unmap the database file. It is possible that external processes
46179 ** may have truncated the database file and then extended it back
46180 ** to its original size while this process was not holding a lock.
46181 ** In this case there may exist a Pager.pMap mapping that appears
46182 ** to be the right size but is not actually valid. Avoid this
46183 ** possibility by unmapping the db here. */
46184 if( USEFETCH(pPager) ){
46185 sqlite3OsUnfetch(pPager->fd, 0, 0);
46190 /* If there is a WAL file in the file-system, open this database in WAL
46191 ** mode. Otherwise, the following function call is a no-op.
46193 rc = pagerOpenWalIfPresent(pPager);
46194 #ifndef SQLITE_OMIT_WAL
46195 assert( pPager->pWal==0 || rc==SQLITE_OK );
46196 #endif
46199 if( pagerUseWal(pPager) ){
46200 assert( rc==SQLITE_OK );
46201 rc = pagerBeginReadTransaction(pPager);
46204 if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
46205 rc = pagerPagecount(pPager, &pPager->dbSize);
46208 failed:
46209 if( rc!=SQLITE_OK ){
46210 assert( !MEMDB );
46211 pager_unlock(pPager);
46212 assert( pPager->eState==PAGER_OPEN );
46213 }else{
46214 pPager->eState = PAGER_READER;
46216 return rc;
46220 ** If the reference count has reached zero, rollback any active
46221 ** transaction and unlock the pager.
46223 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
46224 ** the rollback journal, the unlock is not performed and there is
46225 ** nothing to rollback, so this routine is a no-op.
46227 static void pagerUnlockIfUnused(Pager *pPager){
46228 if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
46229 pagerUnlockAndRollback(pPager);
46234 ** Acquire a reference to page number pgno in pager pPager (a page
46235 ** reference has type DbPage*). If the requested reference is
46236 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
46238 ** If the requested page is already in the cache, it is returned.
46239 ** Otherwise, a new page object is allocated and populated with data
46240 ** read from the database file. In some cases, the pcache module may
46241 ** choose not to allocate a new page object and may reuse an existing
46242 ** object with no outstanding references.
46244 ** The extra data appended to a page is always initialized to zeros the
46245 ** first time a page is loaded into memory. If the page requested is
46246 ** already in the cache when this function is called, then the extra
46247 ** data is left as it was when the page object was last used.
46249 ** If the database image is smaller than the requested page or if a
46250 ** non-zero value is passed as the noContent parameter and the
46251 ** requested page is not already stored in the cache, then no
46252 ** actual disk read occurs. In this case the memory image of the
46253 ** page is initialized to all zeros.
46255 ** If noContent is true, it means that we do not care about the contents
46256 ** of the page. This occurs in two scenarios:
46258 ** a) When reading a free-list leaf page from the database, and
46260 ** b) When a savepoint is being rolled back and we need to load
46261 ** a new page into the cache to be filled with the data read
46262 ** from the savepoint journal.
46264 ** If noContent is true, then the data returned is zeroed instead of
46265 ** being read from the database. Additionally, the bits corresponding
46266 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
46267 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
46268 ** savepoints are set. This means if the page is made writable at any
46269 ** point in the future, using a call to sqlite3PagerWrite(), its contents
46270 ** will not be journaled. This saves IO.
46272 ** The acquisition might fail for several reasons. In all cases,
46273 ** an appropriate error code is returned and *ppPage is set to NULL.
46275 ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
46276 ** to find a page in the in-memory cache first. If the page is not already
46277 ** in memory, this routine goes to disk to read it in whereas Lookup()
46278 ** just returns 0. This routine acquires a read-lock the first time it
46279 ** has to go to disk, and could also playback an old journal if necessary.
46280 ** Since Lookup() never goes to disk, it never has to deal with locks
46281 ** or journal files.
46283 SQLITE_PRIVATE int sqlite3PagerAcquire(
46284 Pager *pPager, /* The pager open on the database file */
46285 Pgno pgno, /* Page number to fetch */
46286 DbPage **ppPage, /* Write a pointer to the page here */
46287 int flags /* PAGER_GET_XXX flags */
46289 int rc = SQLITE_OK;
46290 PgHdr *pPg = 0;
46291 u32 iFrame = 0; /* Frame to read from WAL file */
46292 const int noContent = (flags & PAGER_GET_NOCONTENT);
46294 /* It is acceptable to use a read-only (mmap) page for any page except
46295 ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
46296 ** flag was specified by the caller. And so long as the db is not a
46297 ** temporary or in-memory database. */
46298 const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
46299 && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
46300 #ifdef SQLITE_HAS_CODEC
46301 && pPager->xCodec==0
46302 #endif
46305 assert( pPager->eState>=PAGER_READER );
46306 assert( assert_pager_state(pPager) );
46307 assert( noContent==0 || bMmapOk==0 );
46309 if( pgno==0 ){
46310 return SQLITE_CORRUPT_BKPT;
46313 /* If the pager is in the error state, return an error immediately.
46314 ** Otherwise, request the page from the PCache layer. */
46315 if( pPager->errCode!=SQLITE_OK ){
46316 rc = pPager->errCode;
46317 }else{
46318 if( bMmapOk && pagerUseWal(pPager) ){
46319 rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
46320 if( rc!=SQLITE_OK ) goto pager_acquire_err;
46323 if( bMmapOk && iFrame==0 ){
46324 void *pData = 0;
46326 rc = sqlite3OsFetch(pPager->fd,
46327 (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
46330 if( rc==SQLITE_OK && pData ){
46331 if( pPager->eState>PAGER_READER ){
46332 pPg = sqlite3PagerLookup(pPager, pgno);
46334 if( pPg==0 ){
46335 rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
46336 }else{
46337 sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
46339 if( pPg ){
46340 assert( rc==SQLITE_OK );
46341 *ppPage = pPg;
46342 return SQLITE_OK;
46345 if( rc!=SQLITE_OK ){
46346 goto pager_acquire_err;
46351 sqlite3_pcache_page *pBase;
46352 pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
46353 if( pBase==0 ){
46354 rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
46355 if( rc!=SQLITE_OK ) goto pager_acquire_err;
46357 pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
46358 if( pPg==0 ) rc = SQLITE_NOMEM;
46362 if( rc!=SQLITE_OK ){
46363 /* Either the call to sqlite3PcacheFetch() returned an error or the
46364 ** pager was already in the error-state when this function was called.
46365 ** Set pPg to 0 and jump to the exception handler. */
46366 pPg = 0;
46367 goto pager_acquire_err;
46369 assert( (*ppPage)->pgno==pgno );
46370 assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
46372 if( (*ppPage)->pPager && !noContent ){
46373 /* In this case the pcache already contains an initialized copy of
46374 ** the page. Return without further ado. */
46375 assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
46376 pPager->aStat[PAGER_STAT_HIT]++;
46377 return SQLITE_OK;
46379 }else{
46380 /* The pager cache has created a new page. Its content needs to
46381 ** be initialized. */
46383 pPg = *ppPage;
46384 pPg->pPager = pPager;
46386 /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
46387 ** number greater than this, or the unused locking-page, is requested. */
46388 if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
46389 rc = SQLITE_CORRUPT_BKPT;
46390 goto pager_acquire_err;
46393 if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
46394 if( pgno>pPager->mxPgno ){
46395 rc = SQLITE_FULL;
46396 goto pager_acquire_err;
46398 if( noContent ){
46399 /* Failure to set the bits in the InJournal bit-vectors is benign.
46400 ** It merely means that we might do some extra work to journal a
46401 ** page that does not need to be journaled. Nevertheless, be sure
46402 ** to test the case where a malloc error occurs while trying to set
46403 ** a bit in a bit vector.
46405 sqlite3BeginBenignMalloc();
46406 if( pgno<=pPager->dbOrigSize ){
46407 TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
46408 testcase( rc==SQLITE_NOMEM );
46410 TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
46411 testcase( rc==SQLITE_NOMEM );
46412 sqlite3EndBenignMalloc();
46414 memset(pPg->pData, 0, pPager->pageSize);
46415 IOTRACE(("ZERO %p %d\n", pPager, pgno));
46416 }else{
46417 if( pagerUseWal(pPager) && bMmapOk==0 ){
46418 rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
46419 if( rc!=SQLITE_OK ) goto pager_acquire_err;
46421 assert( pPg->pPager==pPager );
46422 pPager->aStat[PAGER_STAT_MISS]++;
46423 rc = readDbPage(pPg, iFrame);
46424 if( rc!=SQLITE_OK ){
46425 goto pager_acquire_err;
46428 pager_set_pagehash(pPg);
46431 return SQLITE_OK;
46433 pager_acquire_err:
46434 assert( rc!=SQLITE_OK );
46435 if( pPg ){
46436 sqlite3PcacheDrop(pPg);
46438 pagerUnlockIfUnused(pPager);
46440 *ppPage = 0;
46441 return rc;
46445 ** Acquire a page if it is already in the in-memory cache. Do
46446 ** not read the page from disk. Return a pointer to the page,
46447 ** or 0 if the page is not in cache.
46449 ** See also sqlite3PagerGet(). The difference between this routine
46450 ** and sqlite3PagerGet() is that _get() will go to the disk and read
46451 ** in the page if the page is not already in cache. This routine
46452 ** returns NULL if the page is not in cache or if a disk I/O error
46453 ** has ever happened.
46455 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
46456 sqlite3_pcache_page *pPage;
46457 assert( pPager!=0 );
46458 assert( pgno!=0 );
46459 assert( pPager->pPCache!=0 );
46460 pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
46461 return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
46465 ** Release a page reference.
46467 ** If the number of references to the page drop to zero, then the
46468 ** page is added to the LRU list. When all references to all pages
46469 ** are released, a rollback occurs and the lock on the database is
46470 ** removed.
46472 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
46473 Pager *pPager;
46474 assert( pPg!=0 );
46475 pPager = pPg->pPager;
46476 if( pPg->flags & PGHDR_MMAP ){
46477 pagerReleaseMapPage(pPg);
46478 }else{
46479 sqlite3PcacheRelease(pPg);
46481 pagerUnlockIfUnused(pPager);
46483 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
46484 if( pPg ) sqlite3PagerUnrefNotNull(pPg);
46487 #if defined(__APPLE__)
46489 ** Create and return a CFURLRef given a cstring containing the path to a file.
46491 static CFURLRef create_cfurl_from_cstring(const char* filePath){
46492 CFStringRef urlString = CFStringCreateWithFileSystemRepresentation(
46493 kCFAllocatorDefault, filePath);
46494 CFURLRef urlRef = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
46495 urlString, kCFURLPOSIXPathStyle, FALSE);
46496 CFRelease(urlString);
46497 return urlRef;
46499 #endif
46502 ** This function is called at the start of every write transaction.
46503 ** There must already be a RESERVED or EXCLUSIVE lock on the database
46504 ** file when this routine is called.
46506 ** Open the journal file for pager pPager and write a journal header
46507 ** to the start of it. If there are active savepoints, open the sub-journal
46508 ** as well. This function is only used when the journal file is being
46509 ** opened to write a rollback log for a transaction. It is not used
46510 ** when opening a hot journal file to roll it back.
46512 ** If the journal file is already open (as it may be in exclusive mode),
46513 ** then this function just writes a journal header to the start of the
46514 ** already open file.
46516 ** Whether or not the journal file is opened by this function, the
46517 ** Pager.pInJournal bitvec structure is allocated.
46519 ** Return SQLITE_OK if everything is successful. Otherwise, return
46520 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
46521 ** an IO error code if opening or writing the journal file fails.
46523 static int pager_open_journal(Pager *pPager){
46524 int rc = SQLITE_OK; /* Return code */
46525 sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
46527 assert( pPager->eState==PAGER_WRITER_LOCKED );
46528 assert( assert_pager_state(pPager) );
46529 assert( pPager->pInJournal==0 );
46531 /* If already in the error state, this function is a no-op. But on
46532 ** the other hand, this routine is never called if we are already in
46533 ** an error state. */
46534 if( NEVER(pPager->errCode) ) return pPager->errCode;
46536 if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
46537 pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
46538 if( pPager->pInJournal==0 ){
46539 return SQLITE_NOMEM;
46542 /* Open the journal file if it is not already open. */
46543 if( !isOpen(pPager->jfd) ){
46544 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
46545 sqlite3MemJournalOpen(pPager->jfd);
46546 }else{
46547 const int flags = /* VFS flags to open journal file */
46548 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
46549 (pPager->tempFile ?
46550 (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
46551 (SQLITE_OPEN_MAIN_JOURNAL)
46554 /* Verify that the database still has the same name as it did when
46555 ** it was originally opened. */
46556 rc = databaseIsUnmoved(pPager);
46557 if( rc==SQLITE_OK ){
46558 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
46559 rc = sqlite3JournalOpen(
46560 pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
46562 #else
46563 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
46564 #endif
46565 #if defined(__APPLE__)
46566 /* Set the TimeMachine exclusion metadata for the journal if it has
46567 ** been set for the database. Only do this for unix-type vfs
46568 ** implementations. */
46569 if( rc==SQLITE_OK && pPager->zFilename!=NULL
46570 && strlen(pPager->zFilename)>0
46571 && strncmp(pVfs->zName, "unix", 4)==0
46572 && ( pVfs->zName[4]=='-' || pVfs->zName[4]=='\0' ) ){
46573 CFURLRef database = create_cfurl_from_cstring(pPager->zFilename);
46574 if( CSBackupIsItemExcluded(database, NULL) ){
46575 CFURLRef journal = create_cfurl_from_cstring(pPager->zJournal);
46576 /* Ignore errors from the following exclusion call. */
46577 CSBackupSetItemExcluded(journal, TRUE, FALSE);
46578 CFRelease(journal);
46580 CFRelease(database);
46582 #endif
46585 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
46589 /* Write the first journal header to the journal file and open
46590 ** the sub-journal if necessary.
46592 if( rc==SQLITE_OK ){
46593 /* TODO: Check if all of these are really required. */
46594 pPager->nRec = 0;
46595 pPager->journalOff = 0;
46596 pPager->setMaster = 0;
46597 pPager->journalHdr = 0;
46598 rc = writeJournalHdr(pPager);
46602 if( rc!=SQLITE_OK ){
46603 sqlite3BitvecDestroy(pPager->pInJournal);
46604 pPager->pInJournal = 0;
46605 }else{
46606 assert( pPager->eState==PAGER_WRITER_LOCKED );
46607 pPager->eState = PAGER_WRITER_CACHEMOD;
46610 return rc;
46614 ** Begin a write-transaction on the specified pager object. If a
46615 ** write-transaction has already been opened, this function is a no-op.
46617 ** If the exFlag argument is false, then acquire at least a RESERVED
46618 ** lock on the database file. If exFlag is true, then acquire at least
46619 ** an EXCLUSIVE lock. If such a lock is already held, no locking
46620 ** functions need be called.
46622 ** If the subjInMemory argument is non-zero, then any sub-journal opened
46623 ** within this transaction will be opened as an in-memory file. This
46624 ** has no effect if the sub-journal is already opened (as it may be when
46625 ** running in exclusive mode) or if the transaction does not require a
46626 ** sub-journal. If the subjInMemory argument is zero, then any required
46627 ** sub-journal is implemented in-memory if pPager is an in-memory database,
46628 ** or using a temporary file otherwise.
46630 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
46631 int rc = SQLITE_OK;
46633 if( pPager->errCode ) return pPager->errCode;
46634 assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
46635 pPager->subjInMemory = (u8)subjInMemory;
46637 if( ALWAYS(pPager->eState==PAGER_READER) ){
46638 assert( pPager->pInJournal==0 );
46640 if( pagerUseWal(pPager) ){
46641 /* If the pager is configured to use locking_mode=exclusive, and an
46642 ** exclusive lock on the database is not already held, obtain it now.
46644 if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
46645 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
46646 if( rc!=SQLITE_OK ){
46647 return rc;
46649 sqlite3WalExclusiveMode(pPager->pWal, 1);
46652 /* Grab the write lock on the log file. If successful, upgrade to
46653 ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
46654 ** The busy-handler is not invoked if another connection already
46655 ** holds the write-lock. If possible, the upper layer will call it.
46657 rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
46658 }else{
46659 /* Obtain a RESERVED lock on the database file. If the exFlag parameter
46660 ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
46661 ** busy-handler callback can be used when upgrading to the EXCLUSIVE
46662 ** lock, but not when obtaining the RESERVED lock.
46664 rc = pagerLockDb(pPager, RESERVED_LOCK);
46665 if( rc==SQLITE_OK && exFlag ){
46666 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
46670 if( rc==SQLITE_OK ){
46671 /* Change to WRITER_LOCKED state.
46673 ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
46674 ** when it has an open transaction, but never to DBMOD or FINISHED.
46675 ** This is because in those states the code to roll back savepoint
46676 ** transactions may copy data from the sub-journal into the database
46677 ** file as well as into the page cache. Which would be incorrect in
46678 ** WAL mode.
46680 pPager->eState = PAGER_WRITER_LOCKED;
46681 pPager->dbHintSize = pPager->dbSize;
46682 pPager->dbFileSize = pPager->dbSize;
46683 pPager->dbOrigSize = pPager->dbSize;
46684 pPager->journalOff = 0;
46687 assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
46688 assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
46689 assert( assert_pager_state(pPager) );
46692 PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
46693 return rc;
46697 ** Mark a single data page as writeable. The page is written into the
46698 ** main journal or sub-journal as required. If the page is written into
46699 ** one of the journals, the corresponding bit is set in the
46700 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
46701 ** of any open savepoints as appropriate.
46703 static int pager_write(PgHdr *pPg){
46704 Pager *pPager = pPg->pPager;
46705 int rc = SQLITE_OK;
46706 int inJournal;
46708 /* This routine is not called unless a write-transaction has already
46709 ** been started. The journal file may or may not be open at this point.
46710 ** It is never called in the ERROR state.
46712 assert( pPager->eState==PAGER_WRITER_LOCKED
46713 || pPager->eState==PAGER_WRITER_CACHEMOD
46714 || pPager->eState==PAGER_WRITER_DBMOD
46716 assert( assert_pager_state(pPager) );
46717 assert( pPager->errCode==0 );
46718 assert( pPager->readOnly==0 );
46720 CHECK_PAGE(pPg);
46722 /* The journal file needs to be opened. Higher level routines have already
46723 ** obtained the necessary locks to begin the write-transaction, but the
46724 ** rollback journal might not yet be open. Open it now if this is the case.
46726 ** This is done before calling sqlite3PcacheMakeDirty() on the page.
46727 ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
46728 ** an error might occur and the pager would end up in WRITER_LOCKED state
46729 ** with pages marked as dirty in the cache.
46731 if( pPager->eState==PAGER_WRITER_LOCKED ){
46732 rc = pager_open_journal(pPager);
46733 if( rc!=SQLITE_OK ) return rc;
46735 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
46736 assert( assert_pager_state(pPager) );
46738 /* Mark the page as dirty. If the page has already been written
46739 ** to the journal then we can return right away.
46741 sqlite3PcacheMakeDirty(pPg);
46742 inJournal = pageInJournal(pPager, pPg);
46743 if( inJournal && (pPager->nSavepoint==0 || !subjRequiresPage(pPg)) ){
46744 assert( !pagerUseWal(pPager) );
46745 }else{
46747 /* The transaction journal now exists and we have a RESERVED or an
46748 ** EXCLUSIVE lock on the main database file. Write the current page to
46749 ** the transaction journal if it is not there already.
46751 if( !inJournal && !pagerUseWal(pPager) ){
46752 assert( pagerUseWal(pPager)==0 );
46753 if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
46754 u32 cksum;
46755 char *pData2;
46756 i64 iOff = pPager->journalOff;
46758 /* We should never write to the journal file the page that
46759 ** contains the database locks. The following assert verifies
46760 ** that we do not. */
46761 assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
46763 assert( pPager->journalHdr<=pPager->journalOff );
46764 CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
46765 cksum = pager_cksum(pPager, (u8*)pData2);
46767 /* Even if an IO or diskfull error occurs while journalling the
46768 ** page in the block above, set the need-sync flag for the page.
46769 ** Otherwise, when the transaction is rolled back, the logic in
46770 ** playback_one_page() will think that the page needs to be restored
46771 ** in the database file. And if an IO error occurs while doing so,
46772 ** then corruption may follow.
46774 pPg->flags |= PGHDR_NEED_SYNC;
46776 rc = write32bits(pPager->jfd, iOff, pPg->pgno);
46777 if( rc!=SQLITE_OK ) return rc;
46778 rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
46779 if( rc!=SQLITE_OK ) return rc;
46780 rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
46781 if( rc!=SQLITE_OK ) return rc;
46783 IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
46784 pPager->journalOff, pPager->pageSize));
46785 PAGER_INCR(sqlite3_pager_writej_count);
46786 PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
46787 PAGERID(pPager), pPg->pgno,
46788 ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
46790 pPager->journalOff += 8 + pPager->pageSize;
46791 pPager->nRec++;
46792 assert( pPager->pInJournal!=0 );
46793 rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
46794 testcase( rc==SQLITE_NOMEM );
46795 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
46796 rc |= addToSavepointBitvecs(pPager, pPg->pgno);
46797 if( rc!=SQLITE_OK ){
46798 assert( rc==SQLITE_NOMEM );
46799 return rc;
46801 }else{
46802 if( pPager->eState!=PAGER_WRITER_DBMOD ){
46803 pPg->flags |= PGHDR_NEED_SYNC;
46805 PAGERTRACE(("APPEND %d page %d needSync=%d\n",
46806 PAGERID(pPager), pPg->pgno,
46807 ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
46811 /* If the statement journal is open and the page is not in it,
46812 ** then write the current page to the statement journal. Note that
46813 ** the statement journal format differs from the standard journal format
46814 ** in that it omits the checksums and the header.
46816 if( pPager->nSavepoint>0 && subjRequiresPage(pPg) ){
46817 rc = subjournalPage(pPg);
46821 /* Update the database size and return.
46823 if( pPager->dbSize<pPg->pgno ){
46824 pPager->dbSize = pPg->pgno;
46826 return rc;
46830 ** This is a variant of sqlite3PagerWrite() that runs when the sector size
46831 ** is larger than the page size. SQLite makes the (reasonable) assumption that
46832 ** all bytes of a sector are written together by hardware. Hence, all bytes of
46833 ** a sector need to be journalled in case of a power loss in the middle of
46834 ** a write.
46836 ** Usually, the sector size is less than or equal to the page size, in which
46837 ** case pages can be individually written. This routine only runs in the exceptional
46838 ** case where the page size is smaller than the sector size.
46840 static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
46841 int rc = SQLITE_OK; /* Return code */
46842 Pgno nPageCount; /* Total number of pages in database file */
46843 Pgno pg1; /* First page of the sector pPg is located on. */
46844 int nPage = 0; /* Number of pages starting at pg1 to journal */
46845 int ii; /* Loop counter */
46846 int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
46847 Pager *pPager = pPg->pPager; /* The pager that owns pPg */
46848 Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
46850 /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
46851 ** a journal header to be written between the pages journaled by
46852 ** this function.
46854 assert( !MEMDB );
46855 assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
46856 pPager->doNotSpill |= SPILLFLAG_NOSYNC;
46858 /* This trick assumes that both the page-size and sector-size are
46859 ** an integer power of 2. It sets variable pg1 to the identifier
46860 ** of the first page of the sector pPg is located on.
46862 pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
46864 nPageCount = pPager->dbSize;
46865 if( pPg->pgno>nPageCount ){
46866 nPage = (pPg->pgno - pg1)+1;
46867 }else if( (pg1+nPagePerSector-1)>nPageCount ){
46868 nPage = nPageCount+1-pg1;
46869 }else{
46870 nPage = nPagePerSector;
46872 assert(nPage>0);
46873 assert(pg1<=pPg->pgno);
46874 assert((pg1+nPage)>pPg->pgno);
46876 for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
46877 Pgno pg = pg1+ii;
46878 PgHdr *pPage;
46879 if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
46880 if( pg!=PAGER_MJ_PGNO(pPager) ){
46881 rc = sqlite3PagerGet(pPager, pg, &pPage);
46882 if( rc==SQLITE_OK ){
46883 rc = pager_write(pPage);
46884 if( pPage->flags&PGHDR_NEED_SYNC ){
46885 needSync = 1;
46887 sqlite3PagerUnrefNotNull(pPage);
46890 }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
46891 if( pPage->flags&PGHDR_NEED_SYNC ){
46892 needSync = 1;
46894 sqlite3PagerUnrefNotNull(pPage);
46898 /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
46899 ** starting at pg1, then it needs to be set for all of them. Because
46900 ** writing to any of these nPage pages may damage the others, the
46901 ** journal file must contain sync()ed copies of all of them
46902 ** before any of them can be written out to the database file.
46904 if( rc==SQLITE_OK && needSync ){
46905 assert( !MEMDB );
46906 for(ii=0; ii<nPage; ii++){
46907 PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
46908 if( pPage ){
46909 pPage->flags |= PGHDR_NEED_SYNC;
46910 sqlite3PagerUnrefNotNull(pPage);
46915 assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
46916 pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
46917 return rc;
46921 ** Mark a data page as writeable. This routine must be called before
46922 ** making changes to a page. The caller must check the return value
46923 ** of this function and be careful not to change any page data unless
46924 ** this routine returns SQLITE_OK.
46926 ** The difference between this function and pager_write() is that this
46927 ** function also deals with the special case where 2 or more pages
46928 ** fit on a single disk sector. In this case all co-resident pages
46929 ** must have been written to the journal file before returning.
46931 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
46932 ** as appropriate. Otherwise, SQLITE_OK.
46934 SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
46935 assert( (pPg->flags & PGHDR_MMAP)==0 );
46936 assert( pPg->pPager->eState>=PAGER_WRITER_LOCKED );
46937 assert( pPg->pPager->eState!=PAGER_ERROR );
46938 assert( assert_pager_state(pPg->pPager) );
46939 if( pPg->pPager->sectorSize > (u32)pPg->pPager->pageSize ){
46940 return pagerWriteLargeSector(pPg);
46941 }else{
46942 return pager_write(pPg);
46947 ** Return TRUE if the page given in the argument was previously passed
46948 ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
46949 ** to change the content of the page.
46951 #ifndef NDEBUG
46952 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
46953 return pPg->flags&PGHDR_DIRTY;
46955 #endif
46958 ** A call to this routine tells the pager that it is not necessary to
46959 ** write the information on page pPg back to the disk, even though
46960 ** that page might be marked as dirty. This happens, for example, when
46961 ** the page has been added as a leaf of the freelist and so its
46962 ** content no longer matters.
46964 ** The overlying software layer calls this routine when all of the data
46965 ** on the given page is unused. The pager marks the page as clean so
46966 ** that it does not get written to disk.
46968 ** Tests show that this optimization can quadruple the speed of large
46969 ** DELETE operations.
46971 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
46972 Pager *pPager = pPg->pPager;
46973 if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
46974 PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
46975 IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
46976 pPg->flags |= PGHDR_DONT_WRITE;
46977 pager_set_pagehash(pPg);
46982 ** This routine is called to increment the value of the database file
46983 ** change-counter, stored as a 4-byte big-endian integer starting at
46984 ** byte offset 24 of the pager file. The secondary change counter at
46985 ** 92 is also updated, as is the SQLite version number at offset 96.
46987 ** But this only happens if the pPager->changeCountDone flag is false.
46988 ** To avoid excess churning of page 1, the update only happens once.
46989 ** See also the pager_write_changecounter() routine that does an
46990 ** unconditional update of the change counters.
46992 ** If the isDirectMode flag is zero, then this is done by calling
46993 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
46994 ** page data. In this case the file will be updated when the current
46995 ** transaction is committed.
46997 ** The isDirectMode flag may only be non-zero if the library was compiled
46998 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
46999 ** if isDirect is non-zero, then the database file is updated directly
47000 ** by writing an updated version of page 1 using a call to the
47001 ** sqlite3OsWrite() function.
47003 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
47004 int rc = SQLITE_OK;
47006 assert( pPager->eState==PAGER_WRITER_CACHEMOD
47007 || pPager->eState==PAGER_WRITER_DBMOD
47009 assert( assert_pager_state(pPager) );
47011 /* Declare and initialize constant integer 'isDirect'. If the
47012 ** atomic-write optimization is enabled in this build, then isDirect
47013 ** is initialized to the value passed as the isDirectMode parameter
47014 ** to this function. Otherwise, it is always set to zero.
47016 ** The idea is that if the atomic-write optimization is not
47017 ** enabled at compile time, the compiler can omit the tests of
47018 ** 'isDirect' below, as well as the block enclosed in the
47019 ** "if( isDirect )" condition.
47021 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
47022 # define DIRECT_MODE 0
47023 assert( isDirectMode==0 );
47024 UNUSED_PARAMETER(isDirectMode);
47025 #else
47026 # define DIRECT_MODE isDirectMode
47027 #endif
47029 if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
47030 PgHdr *pPgHdr; /* Reference to page 1 */
47032 assert( !pPager->tempFile && isOpen(pPager->fd) );
47034 /* Open page 1 of the file for writing. */
47035 rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
47036 assert( pPgHdr==0 || rc==SQLITE_OK );
47038 /* If page one was fetched successfully, and this function is not
47039 ** operating in direct-mode, make page 1 writable. When not in
47040 ** direct mode, page 1 is always held in cache and hence the PagerGet()
47041 ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
47043 if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
47044 rc = sqlite3PagerWrite(pPgHdr);
47047 if( rc==SQLITE_OK ){
47048 /* Actually do the update of the change counter */
47049 pager_write_changecounter(pPgHdr);
47051 /* If running in direct mode, write the contents of page 1 to the file. */
47052 if( DIRECT_MODE ){
47053 const void *zBuf;
47054 assert( pPager->dbFileSize>0 );
47055 CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
47056 if( rc==SQLITE_OK ){
47057 rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
47058 pPager->aStat[PAGER_STAT_WRITE]++;
47060 if( rc==SQLITE_OK ){
47061 /* Update the pager's copy of the change-counter. Otherwise, the
47062 ** next time a read transaction is opened the cache will be
47063 ** flushed (as the change-counter values will not match). */
47064 const void *pCopy = (const void *)&((const char *)zBuf)[24];
47065 memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
47066 pPager->changeCountDone = 1;
47068 }else{
47069 pPager->changeCountDone = 1;
47073 /* Release the page reference. */
47074 sqlite3PagerUnref(pPgHdr);
47076 return rc;
47080 ** Sync the database file to disk. This is a no-op for in-memory databases
47081 ** or pages with the Pager.noSync flag set.
47083 ** If successful, or if called on a pager for which it is a no-op, this
47084 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
47086 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
47087 int rc = SQLITE_OK;
47089 if( isOpen(pPager->fd) ){
47090 void *pArg = (void*)zMaster;
47091 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
47092 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
47094 if( rc==SQLITE_OK && !pPager->noSync ){
47095 assert( !MEMDB );
47096 rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
47098 return rc;
47102 ** This function may only be called while a write-transaction is active in
47103 ** rollback. If the connection is in WAL mode, this call is a no-op.
47104 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
47105 ** the database file, an attempt is made to obtain one.
47107 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
47108 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
47109 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
47110 ** returned.
47112 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
47113 int rc = SQLITE_OK;
47114 assert( pPager->eState==PAGER_WRITER_CACHEMOD
47115 || pPager->eState==PAGER_WRITER_DBMOD
47116 || pPager->eState==PAGER_WRITER_LOCKED
47118 assert( assert_pager_state(pPager) );
47119 if( 0==pagerUseWal(pPager) ){
47120 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
47122 return rc;
47126 ** Sync the database file for the pager pPager. zMaster points to the name
47127 ** of a master journal file that should be written into the individual
47128 ** journal file. zMaster may be NULL, which is interpreted as no master
47129 ** journal (a single database transaction).
47131 ** This routine ensures that:
47133 ** * The database file change-counter is updated,
47134 ** * the journal is synced (unless the atomic-write optimization is used),
47135 ** * all dirty pages are written to the database file,
47136 ** * the database file is truncated (if required), and
47137 ** * the database file synced.
47139 ** The only thing that remains to commit the transaction is to finalize
47140 ** (delete, truncate or zero the first part of) the journal file (or
47141 ** delete the master journal file if specified).
47143 ** Note that if zMaster==NULL, this does not overwrite a previous value
47144 ** passed to an sqlite3PagerCommitPhaseOne() call.
47146 ** If the final parameter - noSync - is true, then the database file itself
47147 ** is not synced. The caller must call sqlite3PagerSync() directly to
47148 ** sync the database file before calling CommitPhaseTwo() to delete the
47149 ** journal file in this case.
47151 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
47152 Pager *pPager, /* Pager object */
47153 const char *zMaster, /* If not NULL, the master journal name */
47154 int noSync /* True to omit the xSync on the db file */
47156 int rc = SQLITE_OK; /* Return code */
47158 assert( pPager->eState==PAGER_WRITER_LOCKED
47159 || pPager->eState==PAGER_WRITER_CACHEMOD
47160 || pPager->eState==PAGER_WRITER_DBMOD
47161 || pPager->eState==PAGER_ERROR
47163 assert( assert_pager_state(pPager) );
47165 /* If a prior error occurred, report that error again. */
47166 if( NEVER(pPager->errCode) ) return pPager->errCode;
47168 PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
47169 pPager->zFilename, zMaster, pPager->dbSize));
47171 /* If no database changes have been made, return early. */
47172 if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
47174 if( MEMDB ){
47175 /* If this is an in-memory db, or no pages have been written to, or this
47176 ** function has already been called, it is mostly a no-op. However, any
47177 ** backup in progress needs to be restarted.
47179 sqlite3BackupRestart(pPager->pBackup);
47180 }else{
47181 if( pagerUseWal(pPager) ){
47182 PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
47183 PgHdr *pPageOne = 0;
47184 if( pList==0 ){
47185 /* Must have at least one page for the WAL commit flag.
47186 ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
47187 rc = sqlite3PagerGet(pPager, 1, &pPageOne);
47188 pList = pPageOne;
47189 pList->pDirty = 0;
47191 assert( rc==SQLITE_OK );
47192 if( ALWAYS(pList) ){
47193 rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
47195 sqlite3PagerUnref(pPageOne);
47196 if( rc==SQLITE_OK ){
47197 sqlite3PcacheCleanAll(pPager->pPCache);
47199 }else{
47200 /* The following block updates the change-counter. Exactly how it
47201 ** does this depends on whether or not the atomic-update optimization
47202 ** was enabled at compile time, and if this transaction meets the
47203 ** runtime criteria to use the operation:
47205 ** * The file-system supports the atomic-write property for
47206 ** blocks of size page-size, and
47207 ** * This commit is not part of a multi-file transaction, and
47208 ** * Exactly one page has been modified and store in the journal file.
47210 ** If the optimization was not enabled at compile time, then the
47211 ** pager_incr_changecounter() function is called to update the change
47212 ** counter in 'indirect-mode'. If the optimization is compiled in but
47213 ** is not applicable to this transaction, call sqlite3JournalCreate()
47214 ** to make sure the journal file has actually been created, then call
47215 ** pager_incr_changecounter() to update the change-counter in indirect
47216 ** mode.
47218 ** Otherwise, if the optimization is both enabled and applicable,
47219 ** then call pager_incr_changecounter() to update the change-counter
47220 ** in 'direct' mode. In this case the journal file will never be
47221 ** created for this transaction.
47223 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
47224 PgHdr *pPg;
47225 assert( isOpen(pPager->jfd)
47226 || pPager->journalMode==PAGER_JOURNALMODE_OFF
47227 || pPager->journalMode==PAGER_JOURNALMODE_WAL
47229 if( !zMaster && isOpen(pPager->jfd)
47230 && pPager->journalOff==jrnlBufferSize(pPager)
47231 && pPager->dbSize>=pPager->dbOrigSize
47232 && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
47234 /* Update the db file change counter via the direct-write method. The
47235 ** following call will modify the in-memory representation of page 1
47236 ** to include the updated change counter and then write page 1
47237 ** directly to the database file. Because of the atomic-write
47238 ** property of the host file-system, this is safe.
47240 rc = pager_incr_changecounter(pPager, 1);
47241 }else{
47242 rc = sqlite3JournalCreate(pPager->jfd);
47243 if( rc==SQLITE_OK ){
47244 rc = pager_incr_changecounter(pPager, 0);
47247 #else
47248 rc = pager_incr_changecounter(pPager, 0);
47249 #endif
47250 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47252 /* Write the master journal name into the journal file. If a master
47253 ** journal file name has already been written to the journal file,
47254 ** or if zMaster is NULL (no master journal), then this call is a no-op.
47256 rc = writeMasterJournal(pPager, zMaster);
47257 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47259 /* Sync the journal file and write all dirty pages to the database.
47260 ** If the atomic-update optimization is being used, this sync will not
47261 ** create the journal file or perform any real IO.
47263 ** Because the change-counter page was just modified, unless the
47264 ** atomic-update optimization is used it is almost certain that the
47265 ** journal requires a sync here. However, in locking_mode=exclusive
47266 ** on a system under memory pressure it is just possible that this is
47267 ** not the case. In this case it is likely enough that the redundant
47268 ** xSync() call will be changed to a no-op by the OS anyhow.
47270 rc = syncJournal(pPager, 0);
47271 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47273 rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
47274 if( rc!=SQLITE_OK ){
47275 assert( rc!=SQLITE_IOERR_BLOCKED );
47276 goto commit_phase_one_exit;
47278 sqlite3PcacheCleanAll(pPager->pPCache);
47280 /* If the file on disk is smaller than the database image, use
47281 ** pager_truncate to grow the file here. This can happen if the database
47282 ** image was extended as part of the current transaction and then the
47283 ** last page in the db image moved to the free-list. In this case the
47284 ** last page is never written out to disk, leaving the database file
47285 ** undersized. Fix this now if it is the case. */
47286 if( pPager->dbSize>pPager->dbFileSize ){
47287 Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
47288 assert( pPager->eState==PAGER_WRITER_DBMOD );
47289 rc = pager_truncate(pPager, nNew);
47290 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47293 /* Finally, sync the database file. */
47294 if( !noSync ){
47295 rc = sqlite3PagerSync(pPager, zMaster);
47297 IOTRACE(("DBSYNC %p\n", pPager))
47301 commit_phase_one_exit:
47302 if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
47303 pPager->eState = PAGER_WRITER_FINISHED;
47305 return rc;
47310 ** When this function is called, the database file has been completely
47311 ** updated to reflect the changes made by the current transaction and
47312 ** synced to disk. The journal file still exists in the file-system
47313 ** though, and if a failure occurs at this point it will eventually
47314 ** be used as a hot-journal and the current transaction rolled back.
47316 ** This function finalizes the journal file, either by deleting,
47317 ** truncating or partially zeroing it, so that it cannot be used
47318 ** for hot-journal rollback. Once this is done the transaction is
47319 ** irrevocably committed.
47321 ** If an error occurs, an IO error code is returned and the pager
47322 ** moves into the error state. Otherwise, SQLITE_OK is returned.
47324 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
47325 int rc = SQLITE_OK; /* Return code */
47327 /* This routine should not be called if a prior error has occurred.
47328 ** But if (due to a coding error elsewhere in the system) it does get
47329 ** called, just return the same error code without doing anything. */
47330 if( NEVER(pPager->errCode) ) return pPager->errCode;
47332 assert( pPager->eState==PAGER_WRITER_LOCKED
47333 || pPager->eState==PAGER_WRITER_FINISHED
47334 || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
47336 assert( assert_pager_state(pPager) );
47338 /* An optimization. If the database was not actually modified during
47339 ** this transaction, the pager is running in exclusive-mode and is
47340 ** using persistent journals, then this function is a no-op.
47342 ** The start of the journal file currently contains a single journal
47343 ** header with the nRec field set to 0. If such a journal is used as
47344 ** a hot-journal during hot-journal rollback, 0 changes will be made
47345 ** to the database file. So there is no need to zero the journal
47346 ** header. Since the pager is in exclusive mode, there is no need
47347 ** to drop any locks either.
47349 if( pPager->eState==PAGER_WRITER_LOCKED
47350 && pPager->exclusiveMode
47351 && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
47353 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
47354 pPager->eState = PAGER_READER;
47355 return SQLITE_OK;
47358 PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
47359 rc = pager_end_transaction(pPager, pPager->setMaster, 1);
47360 return pager_error(pPager, rc);
47364 ** If a write transaction is open, then all changes made within the
47365 ** transaction are reverted and the current write-transaction is closed.
47366 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
47367 ** state if an error occurs.
47369 ** If the pager is already in PAGER_ERROR state when this function is called,
47370 ** it returns Pager.errCode immediately. No work is performed in this case.
47372 ** Otherwise, in rollback mode, this function performs two functions:
47374 ** 1) It rolls back the journal file, restoring all database file and
47375 ** in-memory cache pages to the state they were in when the transaction
47376 ** was opened, and
47378 ** 2) It finalizes the journal file, so that it is not used for hot
47379 ** rollback at any point in the future.
47381 ** Finalization of the journal file (task 2) is only performed if the
47382 ** rollback is successful.
47384 ** In WAL mode, all cache-entries containing data modified within the
47385 ** current transaction are either expelled from the cache or reverted to
47386 ** their pre-transaction state by re-reading data from the database or
47387 ** WAL files. The WAL transaction is then closed.
47389 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
47390 int rc = SQLITE_OK; /* Return code */
47391 PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
47393 /* PagerRollback() is a no-op if called in READER or OPEN state. If
47394 ** the pager is already in the ERROR state, the rollback is not
47395 ** attempted here. Instead, the error code is returned to the caller.
47397 assert( assert_pager_state(pPager) );
47398 if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
47399 if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
47401 if( pagerUseWal(pPager) ){
47402 int rc2;
47403 rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
47404 rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
47405 if( rc==SQLITE_OK ) rc = rc2;
47406 }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
47407 int eState = pPager->eState;
47408 rc = pager_end_transaction(pPager, 0, 0);
47409 if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
47410 /* This can happen using journal_mode=off. Move the pager to the error
47411 ** state to indicate that the contents of the cache may not be trusted.
47412 ** Any active readers will get SQLITE_ABORT.
47414 pPager->errCode = SQLITE_ABORT;
47415 pPager->eState = PAGER_ERROR;
47416 return rc;
47418 }else{
47419 rc = pager_playback(pPager, 0);
47422 assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
47423 assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
47424 || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
47425 || rc==SQLITE_CANTOPEN
47428 /* If an error occurs during a ROLLBACK, we can no longer trust the pager
47429 ** cache. So call pager_error() on the way out to make any error persistent.
47431 return pager_error(pPager, rc);
47435 ** Return TRUE if the database file is opened read-only. Return FALSE
47436 ** if the database is (in theory) writable.
47438 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
47439 return pPager->readOnly;
47443 ** Return the number of references to the pager.
47445 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
47446 return sqlite3PcacheRefCount(pPager->pPCache);
47450 ** Return the approximate number of bytes of memory currently
47451 ** used by the pager and its associated cache.
47453 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
47454 int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
47455 + 5*sizeof(void*);
47456 return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
47457 + sqlite3MallocSize(pPager)
47458 + pPager->pageSize;
47462 ** Return the number of references to the specified page.
47464 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
47465 return sqlite3PcachePageRefcount(pPage);
47468 #ifdef SQLITE_TEST
47470 ** This routine is used for testing and analysis only.
47472 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
47473 static int a[11];
47474 a[0] = sqlite3PcacheRefCount(pPager->pPCache);
47475 a[1] = sqlite3PcachePagecount(pPager->pPCache);
47476 a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
47477 a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
47478 a[4] = pPager->eState;
47479 a[5] = pPager->errCode;
47480 a[6] = pPager->aStat[PAGER_STAT_HIT];
47481 a[7] = pPager->aStat[PAGER_STAT_MISS];
47482 a[8] = 0; /* Used to be pPager->nOvfl */
47483 a[9] = pPager->nRead;
47484 a[10] = pPager->aStat[PAGER_STAT_WRITE];
47485 return a;
47487 #endif
47490 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
47491 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
47492 ** current cache hit or miss count, according to the value of eStat. If the
47493 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
47494 ** returning.
47496 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
47498 assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
47499 || eStat==SQLITE_DBSTATUS_CACHE_MISS
47500 || eStat==SQLITE_DBSTATUS_CACHE_WRITE
47503 assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
47504 assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
47505 assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
47507 *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
47508 if( reset ){
47509 pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
47514 ** Return true if this is an in-memory pager.
47516 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
47517 return MEMDB;
47521 ** Check that there are at least nSavepoint savepoints open. If there are
47522 ** currently less than nSavepoints open, then open one or more savepoints
47523 ** to make up the difference. If the number of savepoints is already
47524 ** equal to nSavepoint, then this function is a no-op.
47526 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
47527 ** occurs while opening the sub-journal file, then an IO error code is
47528 ** returned. Otherwise, SQLITE_OK.
47530 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
47531 int rc = SQLITE_OK; /* Return code */
47532 int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
47534 assert( pPager->eState>=PAGER_WRITER_LOCKED );
47535 assert( assert_pager_state(pPager) );
47537 if( nSavepoint>nCurrent && pPager->useJournal ){
47538 int ii; /* Iterator variable */
47539 PagerSavepoint *aNew; /* New Pager.aSavepoint array */
47541 /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
47542 ** if the allocation fails. Otherwise, zero the new portion in case a
47543 ** malloc failure occurs while populating it in the for(...) loop below.
47545 aNew = (PagerSavepoint *)sqlite3Realloc(
47546 pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
47548 if( !aNew ){
47549 return SQLITE_NOMEM;
47551 memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
47552 pPager->aSavepoint = aNew;
47554 /* Populate the PagerSavepoint structures just allocated. */
47555 for(ii=nCurrent; ii<nSavepoint; ii++){
47556 aNew[ii].nOrig = pPager->dbSize;
47557 if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
47558 aNew[ii].iOffset = pPager->journalOff;
47559 }else{
47560 aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
47562 aNew[ii].iSubRec = pPager->nSubRec;
47563 aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
47564 if( !aNew[ii].pInSavepoint ){
47565 return SQLITE_NOMEM;
47567 if( pagerUseWal(pPager) ){
47568 sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
47570 pPager->nSavepoint = ii+1;
47572 assert( pPager->nSavepoint==nSavepoint );
47573 assertTruncateConstraint(pPager);
47576 return rc;
47580 ** This function is called to rollback or release (commit) a savepoint.
47581 ** The savepoint to release or rollback need not be the most recently
47582 ** created savepoint.
47584 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
47585 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
47586 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
47587 ** that have occurred since the specified savepoint was created.
47589 ** The savepoint to rollback or release is identified by parameter
47590 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
47591 ** (the first created). A value of (Pager.nSavepoint-1) means operate
47592 ** on the most recently created savepoint. If iSavepoint is greater than
47593 ** (Pager.nSavepoint-1), then this function is a no-op.
47595 ** If a negative value is passed to this function, then the current
47596 ** transaction is rolled back. This is different to calling
47597 ** sqlite3PagerRollback() because this function does not terminate
47598 ** the transaction or unlock the database, it just restores the
47599 ** contents of the database to its original state.
47601 ** In any case, all savepoints with an index greater than iSavepoint
47602 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
47603 ** then savepoint iSavepoint is also destroyed.
47605 ** This function may return SQLITE_NOMEM if a memory allocation fails,
47606 ** or an IO error code if an IO error occurs while rolling back a
47607 ** savepoint. If no errors occur, SQLITE_OK is returned.
47609 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
47610 int rc = pPager->errCode; /* Return code */
47612 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
47613 assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
47615 if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
47616 int ii; /* Iterator variable */
47617 int nNew; /* Number of remaining savepoints after this op. */
47619 /* Figure out how many savepoints will still be active after this
47620 ** operation. Store this value in nNew. Then free resources associated
47621 ** with any savepoints that are destroyed by this operation.
47623 nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
47624 for(ii=nNew; ii<pPager->nSavepoint; ii++){
47625 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
47627 pPager->nSavepoint = nNew;
47629 /* If this is a release of the outermost savepoint, truncate
47630 ** the sub-journal to zero bytes in size. */
47631 if( op==SAVEPOINT_RELEASE ){
47632 if( nNew==0 && isOpen(pPager->sjfd) ){
47633 /* Only truncate if it is an in-memory sub-journal. */
47634 if( sqlite3IsMemJournal(pPager->sjfd) ){
47635 rc = sqlite3OsTruncate(pPager->sjfd, 0);
47636 assert( rc==SQLITE_OK );
47638 pPager->nSubRec = 0;
47641 /* Else this is a rollback operation, playback the specified savepoint.
47642 ** If this is a temp-file, it is possible that the journal file has
47643 ** not yet been opened. In this case there have been no changes to
47644 ** the database file, so the playback operation can be skipped.
47646 else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
47647 PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
47648 rc = pagerPlaybackSavepoint(pPager, pSavepoint);
47649 assert(rc!=SQLITE_DONE);
47653 return rc;
47657 ** Return the full pathname of the database file.
47659 ** Except, if the pager is in-memory only, then return an empty string if
47660 ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
47661 ** used to report the filename to the user, for compatibility with legacy
47662 ** behavior. But when the Btree needs to know the filename for matching to
47663 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
47664 ** participate in shared-cache.
47666 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
47667 return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
47671 ** Return the VFS structure for the pager.
47673 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
47674 return pPager->pVfs;
47678 ** Return the file handle for the database file associated
47679 ** with the pager. This might return NULL if the file has
47680 ** not yet been opened.
47682 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
47683 return pPager->fd;
47687 ** Return the full pathname of the journal file.
47689 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
47690 return pPager->zJournal;
47694 ** Return true if fsync() calls are disabled for this pager. Return FALSE
47695 ** if fsync()s are executed normally.
47697 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
47698 return pPager->noSync;
47701 #ifdef SQLITE_HAS_CODEC
47703 ** Set or retrieve the codec for this pager
47705 SQLITE_PRIVATE void sqlite3PagerSetCodec(
47706 Pager *pPager,
47707 void *(*xCodec)(void*,void*,Pgno,int),
47708 void (*xCodecSizeChng)(void*,int,int),
47709 void (*xCodecFree)(void*),
47710 void *pCodec
47712 if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
47713 pPager->xCodec = pPager->memDb ? 0 : xCodec;
47714 pPager->xCodecSizeChng = xCodecSizeChng;
47715 pPager->xCodecFree = xCodecFree;
47716 pPager->pCodec = pCodec;
47717 pagerReportSize(pPager);
47719 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
47720 return pPager->pCodec;
47724 ** This function is called by the wal module when writing page content
47725 ** into the log file.
47727 ** This function returns a pointer to a buffer containing the encrypted
47728 ** page content. If a malloc fails, this function may return NULL.
47730 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
47731 void *aData = 0;
47732 CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
47733 return aData;
47737 ** Return the current pager state
47739 SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
47740 return pPager->eState;
47742 #endif /* SQLITE_HAS_CODEC */
47744 #ifndef SQLITE_OMIT_AUTOVACUUM
47746 ** Move the page pPg to location pgno in the file.
47748 ** There must be no references to the page previously located at
47749 ** pgno (which we call pPgOld) though that page is allowed to be
47750 ** in cache. If the page previously located at pgno is not already
47751 ** in the rollback journal, it is not put there by by this routine.
47753 ** References to the page pPg remain valid. Updating any
47754 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
47755 ** allocated along with the page) is the responsibility of the caller.
47757 ** A transaction must be active when this routine is called. It used to be
47758 ** required that a statement transaction was not active, but this restriction
47759 ** has been removed (CREATE INDEX needs to move a page when a statement
47760 ** transaction is active).
47762 ** If the fourth argument, isCommit, is non-zero, then this page is being
47763 ** moved as part of a database reorganization just before the transaction
47764 ** is being committed. In this case, it is guaranteed that the database page
47765 ** pPg refers to will not be written to again within this transaction.
47767 ** This function may return SQLITE_NOMEM or an IO error code if an error
47768 ** occurs. Otherwise, it returns SQLITE_OK.
47770 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
47771 PgHdr *pPgOld; /* The page being overwritten. */
47772 Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
47773 int rc; /* Return code */
47774 Pgno origPgno; /* The original page number */
47776 assert( pPg->nRef>0 );
47777 assert( pPager->eState==PAGER_WRITER_CACHEMOD
47778 || pPager->eState==PAGER_WRITER_DBMOD
47780 assert( assert_pager_state(pPager) );
47782 /* In order to be able to rollback, an in-memory database must journal
47783 ** the page we are moving from.
47785 if( MEMDB ){
47786 rc = sqlite3PagerWrite(pPg);
47787 if( rc ) return rc;
47790 /* If the page being moved is dirty and has not been saved by the latest
47791 ** savepoint, then save the current contents of the page into the
47792 ** sub-journal now. This is required to handle the following scenario:
47794 ** BEGIN;
47795 ** <journal page X, then modify it in memory>
47796 ** SAVEPOINT one;
47797 ** <Move page X to location Y>
47798 ** ROLLBACK TO one;
47800 ** If page X were not written to the sub-journal here, it would not
47801 ** be possible to restore its contents when the "ROLLBACK TO one"
47802 ** statement were is processed.
47804 ** subjournalPage() may need to allocate space to store pPg->pgno into
47805 ** one or more savepoint bitvecs. This is the reason this function
47806 ** may return SQLITE_NOMEM.
47808 if( pPg->flags&PGHDR_DIRTY
47809 && subjRequiresPage(pPg)
47810 && SQLITE_OK!=(rc = subjournalPage(pPg))
47812 return rc;
47815 PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
47816 PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
47817 IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
47819 /* If the journal needs to be sync()ed before page pPg->pgno can
47820 ** be written to, store pPg->pgno in local variable needSyncPgno.
47822 ** If the isCommit flag is set, there is no need to remember that
47823 ** the journal needs to be sync()ed before database page pPg->pgno
47824 ** can be written to. The caller has already promised not to write to it.
47826 if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
47827 needSyncPgno = pPg->pgno;
47828 assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
47829 pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
47830 assert( pPg->flags&PGHDR_DIRTY );
47833 /* If the cache contains a page with page-number pgno, remove it
47834 ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
47835 ** page pgno before the 'move' operation, it needs to be retained
47836 ** for the page moved there.
47838 pPg->flags &= ~PGHDR_NEED_SYNC;
47839 pPgOld = sqlite3PagerLookup(pPager, pgno);
47840 assert( !pPgOld || pPgOld->nRef==1 );
47841 if( pPgOld ){
47842 pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
47843 if( MEMDB ){
47844 /* Do not discard pages from an in-memory database since we might
47845 ** need to rollback later. Just move the page out of the way. */
47846 sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
47847 }else{
47848 sqlite3PcacheDrop(pPgOld);
47852 origPgno = pPg->pgno;
47853 sqlite3PcacheMove(pPg, pgno);
47854 sqlite3PcacheMakeDirty(pPg);
47856 /* For an in-memory database, make sure the original page continues
47857 ** to exist, in case the transaction needs to roll back. Use pPgOld
47858 ** as the original page since it has already been allocated.
47860 if( MEMDB ){
47861 assert( pPgOld );
47862 sqlite3PcacheMove(pPgOld, origPgno);
47863 sqlite3PagerUnrefNotNull(pPgOld);
47866 if( needSyncPgno ){
47867 /* If needSyncPgno is non-zero, then the journal file needs to be
47868 ** sync()ed before any data is written to database file page needSyncPgno.
47869 ** Currently, no such page exists in the page-cache and the
47870 ** "is journaled" bitvec flag has been set. This needs to be remedied by
47871 ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
47872 ** flag.
47874 ** If the attempt to load the page into the page-cache fails, (due
47875 ** to a malloc() or IO failure), clear the bit in the pInJournal[]
47876 ** array. Otherwise, if the page is loaded and written again in
47877 ** this transaction, it may be written to the database file before
47878 ** it is synced into the journal file. This way, it may end up in
47879 ** the journal file twice, but that is not a problem.
47881 PgHdr *pPgHdr;
47882 rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
47883 if( rc!=SQLITE_OK ){
47884 if( needSyncPgno<=pPager->dbOrigSize ){
47885 assert( pPager->pTmpSpace!=0 );
47886 sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
47888 return rc;
47890 pPgHdr->flags |= PGHDR_NEED_SYNC;
47891 sqlite3PcacheMakeDirty(pPgHdr);
47892 sqlite3PagerUnrefNotNull(pPgHdr);
47895 return SQLITE_OK;
47897 #endif
47900 ** Return a pointer to the data for the specified page.
47902 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
47903 assert( pPg->nRef>0 || pPg->pPager->memDb );
47904 return pPg->pData;
47908 ** Return a pointer to the Pager.nExtra bytes of "extra" space
47909 ** allocated along with the specified page.
47911 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
47912 return pPg->pExtra;
47916 ** Get/set the locking-mode for this pager. Parameter eMode must be one
47917 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
47918 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
47919 ** the locking-mode is set to the value specified.
47921 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
47922 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
47923 ** locking-mode.
47925 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
47926 assert( eMode==PAGER_LOCKINGMODE_QUERY
47927 || eMode==PAGER_LOCKINGMODE_NORMAL
47928 || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
47929 assert( PAGER_LOCKINGMODE_QUERY<0 );
47930 assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
47931 assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
47932 if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
47933 pPager->exclusiveMode = (u8)eMode;
47935 return (int)pPager->exclusiveMode;
47939 ** Set the journal-mode for this pager. Parameter eMode must be one of:
47941 ** PAGER_JOURNALMODE_DELETE
47942 ** PAGER_JOURNALMODE_TRUNCATE
47943 ** PAGER_JOURNALMODE_PERSIST
47944 ** PAGER_JOURNALMODE_OFF
47945 ** PAGER_JOURNALMODE_MEMORY
47946 ** PAGER_JOURNALMODE_WAL
47948 ** The journalmode is set to the value specified if the change is allowed.
47949 ** The change may be disallowed for the following reasons:
47951 ** * An in-memory database can only have its journal_mode set to _OFF
47952 ** or _MEMORY.
47954 ** * Temporary databases cannot have _WAL journalmode.
47956 ** The returned indicate the current (possibly updated) journal-mode.
47958 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
47959 u8 eOld = pPager->journalMode; /* Prior journalmode */
47961 #ifdef SQLITE_DEBUG
47962 /* The print_pager_state() routine is intended to be used by the debugger
47963 ** only. We invoke it once here to suppress a compiler warning. */
47964 print_pager_state(pPager);
47965 #endif
47968 /* The eMode parameter is always valid */
47969 assert( eMode==PAGER_JOURNALMODE_DELETE
47970 || eMode==PAGER_JOURNALMODE_TRUNCATE
47971 || eMode==PAGER_JOURNALMODE_PERSIST
47972 || eMode==PAGER_JOURNALMODE_OFF
47973 || eMode==PAGER_JOURNALMODE_WAL
47974 || eMode==PAGER_JOURNALMODE_MEMORY );
47976 /* This routine is only called from the OP_JournalMode opcode, and
47977 ** the logic there will never allow a temporary file to be changed
47978 ** to WAL mode.
47980 assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
47982 /* Do allow the journalmode of an in-memory database to be set to
47983 ** anything other than MEMORY or OFF
47985 if( MEMDB ){
47986 assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
47987 if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
47988 eMode = eOld;
47992 if( eMode!=eOld ){
47994 /* Change the journal mode. */
47995 assert( pPager->eState!=PAGER_ERROR );
47996 pPager->journalMode = (u8)eMode;
47998 /* When transistioning from TRUNCATE or PERSIST to any other journal
47999 ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
48000 ** delete the journal file.
48002 assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
48003 assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
48004 assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
48005 assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
48006 assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
48007 assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
48009 assert( isOpen(pPager->fd) || pPager->exclusiveMode );
48010 if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
48012 /* In this case we would like to delete the journal file. If it is
48013 ** not possible, then that is not a problem. Deleting the journal file
48014 ** here is an optimization only.
48016 ** Before deleting the journal file, obtain a RESERVED lock on the
48017 ** database file. This ensures that the journal file is not deleted
48018 ** while it is in use by some other client.
48020 sqlite3OsClose(pPager->jfd);
48021 if( pPager->eLock>=RESERVED_LOCK ){
48022 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
48023 }else{
48024 int rc = SQLITE_OK;
48025 int state = pPager->eState;
48026 assert( state==PAGER_OPEN || state==PAGER_READER );
48027 if( state==PAGER_OPEN ){
48028 rc = sqlite3PagerSharedLock(pPager);
48030 if( pPager->eState==PAGER_READER ){
48031 assert( rc==SQLITE_OK );
48032 rc = pagerLockDb(pPager, RESERVED_LOCK);
48034 if( rc==SQLITE_OK ){
48035 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
48037 if( rc==SQLITE_OK && state==PAGER_READER ){
48038 pagerUnlockDb(pPager, SHARED_LOCK);
48039 }else if( state==PAGER_OPEN ){
48040 pager_unlock(pPager);
48042 assert( state==pPager->eState );
48047 /* Return the new journal mode */
48048 return (int)pPager->journalMode;
48052 ** Return the current journal mode.
48054 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
48055 return (int)pPager->journalMode;
48059 ** Return TRUE if the pager is in a state where it is OK to change the
48060 ** journalmode. Journalmode changes can only happen when the database
48061 ** is unmodified.
48063 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
48064 assert( assert_pager_state(pPager) );
48065 if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
48066 if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
48067 return 1;
48071 ** Get/set the size-limit used for persistent journal files.
48073 ** Setting the size limit to -1 means no limit is enforced.
48074 ** An attempt to set a limit smaller than -1 is a no-op.
48076 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
48077 if( iLimit>=-1 ){
48078 pPager->journalSizeLimit = iLimit;
48079 sqlite3WalLimit(pPager->pWal, iLimit);
48081 return pPager->journalSizeLimit;
48085 ** Return a pointer to the pPager->pBackup variable. The backup module
48086 ** in backup.c maintains the content of this variable. This module
48087 ** uses it opaquely as an argument to sqlite3BackupRestart() and
48088 ** sqlite3BackupUpdate() only.
48090 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
48091 return &pPager->pBackup;
48094 #ifndef SQLITE_OMIT_VACUUM
48096 ** Unless this is an in-memory or temporary database, clear the pager cache.
48098 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
48099 if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
48101 #endif
48103 #ifndef SQLITE_OMIT_WAL
48105 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
48106 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
48107 ** or wal_blocking_checkpoint() API functions.
48109 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
48111 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
48112 int rc = SQLITE_OK;
48113 if( pPager->pWal ){
48114 rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
48115 pPager->xBusyHandler, pPager->pBusyHandlerArg,
48116 pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
48117 pnLog, pnCkpt
48120 return rc;
48123 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
48124 return sqlite3WalCallback(pPager->pWal);
48128 ** Return true if the underlying VFS for the given pager supports the
48129 ** primitives necessary for write-ahead logging.
48131 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
48132 const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
48133 return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
48137 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
48138 ** is obtained instead, immediately release it.
48140 static int pagerExclusiveLock(Pager *pPager){
48141 int rc; /* Return code */
48143 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
48144 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
48145 if( rc!=SQLITE_OK ){
48146 /* If the attempt to grab the exclusive lock failed, release the
48147 ** pending lock that may have been obtained instead. */
48148 pagerUnlockDb(pPager, SHARED_LOCK);
48151 return rc;
48155 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
48156 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
48157 ** lock on the database file and use heap-memory to store the wal-index
48158 ** in. Otherwise, use the normal shared-memory.
48160 static int pagerOpenWal(Pager *pPager){
48161 int rc = SQLITE_OK;
48163 assert( pPager->pWal==0 && pPager->tempFile==0 );
48164 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
48166 /* If the pager is already in exclusive-mode, the WAL module will use
48167 ** heap-memory for the wal-index instead of the VFS shared-memory
48168 ** implementation. Take the exclusive lock now, before opening the WAL
48169 ** file, to make sure this is safe.
48171 if( pPager->exclusiveMode ){
48172 rc = pagerExclusiveLock(pPager);
48175 /* Open the connection to the log file. If this operation fails,
48176 ** (e.g. due to malloc() failure), return an error code.
48178 if( rc==SQLITE_OK ){
48179 rc = sqlite3WalOpen(pPager->pVfs,
48180 pPager->fd, pPager->zWal, pPager->exclusiveMode,
48181 pPager->journalSizeLimit, &pPager->pWal
48184 pagerFixMaplimit(pPager);
48186 return rc;
48191 ** The caller must be holding a SHARED lock on the database file to call
48192 ** this function.
48194 ** If the pager passed as the first argument is open on a real database
48195 ** file (not a temp file or an in-memory database), and the WAL file
48196 ** is not already open, make an attempt to open it now. If successful,
48197 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
48198 ** not support the xShmXXX() methods, return an error code. *pbOpen is
48199 ** not modified in either case.
48201 ** If the pager is open on a temp-file (or in-memory database), or if
48202 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
48203 ** without doing anything.
48205 SQLITE_PRIVATE int sqlite3PagerOpenWal(
48206 Pager *pPager, /* Pager object */
48207 int *pbOpen /* OUT: Set to true if call is a no-op */
48209 int rc = SQLITE_OK; /* Return code */
48211 assert( assert_pager_state(pPager) );
48212 assert( pPager->eState==PAGER_OPEN || pbOpen );
48213 assert( pPager->eState==PAGER_READER || !pbOpen );
48214 assert( pbOpen==0 || *pbOpen==0 );
48215 assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
48217 if( !pPager->tempFile && !pPager->pWal ){
48218 if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
48220 /* Close any rollback journal previously open */
48221 sqlite3OsClose(pPager->jfd);
48223 rc = pagerOpenWal(pPager);
48224 if( rc==SQLITE_OK ){
48225 pPager->journalMode = PAGER_JOURNALMODE_WAL;
48226 pPager->eState = PAGER_OPEN;
48228 }else{
48229 *pbOpen = 1;
48232 return rc;
48236 ** This function is called to close the connection to the log file prior
48237 ** to switching from WAL to rollback mode.
48239 ** Before closing the log file, this function attempts to take an
48240 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
48241 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
48242 ** If successful, the EXCLUSIVE lock is not released before returning.
48244 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
48245 int rc = SQLITE_OK;
48247 assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
48249 /* If the log file is not already open, but does exist in the file-system,
48250 ** it may need to be checkpointed before the connection can switch to
48251 ** rollback mode. Open it now so this can happen.
48253 if( !pPager->pWal ){
48254 int logexists = 0;
48255 rc = pagerLockDb(pPager, SHARED_LOCK);
48256 if( rc==SQLITE_OK ){
48257 rc = sqlite3OsAccess(
48258 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
48261 if( rc==SQLITE_OK && logexists ){
48262 rc = pagerOpenWal(pPager);
48266 /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
48267 ** the database file, the log and log-summary files will be deleted.
48269 if( rc==SQLITE_OK && pPager->pWal ){
48270 rc = pagerExclusiveLock(pPager);
48271 if( rc==SQLITE_OK ){
48272 rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
48273 pPager->pageSize, (u8*)pPager->pTmpSpace);
48274 pPager->pWal = 0;
48275 pagerFixMaplimit(pPager);
48278 return rc;
48281 #endif /* !SQLITE_OMIT_WAL */
48283 #ifdef SQLITE_ENABLE_ZIPVFS
48285 ** A read-lock must be held on the pager when this function is called. If
48286 ** the pager is in WAL mode and the WAL file currently contains one or more
48287 ** frames, return the size in bytes of the page images stored within the
48288 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
48289 ** is empty, return 0.
48291 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
48292 assert( pPager->eState>=PAGER_READER );
48293 return sqlite3WalFramesize(pPager->pWal);
48295 #endif
48297 #endif /* SQLITE_OMIT_DISKIO */
48299 /************** End of pager.c ***********************************************/
48300 /************** Begin file wal.c *********************************************/
48302 ** 2010 February 1
48304 ** The author disclaims copyright to this source code. In place of
48305 ** a legal notice, here is a blessing:
48307 ** May you do good and not evil.
48308 ** May you find forgiveness for yourself and forgive others.
48309 ** May you share freely, never taking more than you give.
48311 *************************************************************************
48313 ** This file contains the implementation of a write-ahead log (WAL) used in
48314 ** "journal_mode=WAL" mode.
48316 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
48318 ** A WAL file consists of a header followed by zero or more "frames".
48319 ** Each frame records the revised content of a single page from the
48320 ** database file. All changes to the database are recorded by writing
48321 ** frames into the WAL. Transactions commit when a frame is written that
48322 ** contains a commit marker. A single WAL can and usually does record
48323 ** multiple transactions. Periodically, the content of the WAL is
48324 ** transferred back into the database file in an operation called a
48325 ** "checkpoint".
48327 ** A single WAL file can be used multiple times. In other words, the
48328 ** WAL can fill up with frames and then be checkpointed and then new
48329 ** frames can overwrite the old ones. A WAL always grows from beginning
48330 ** toward the end. Checksums and counters attached to each frame are
48331 ** used to determine which frames within the WAL are valid and which
48332 ** are leftovers from prior checkpoints.
48334 ** The WAL header is 32 bytes in size and consists of the following eight
48335 ** big-endian 32-bit unsigned integer values:
48337 ** 0: Magic number. 0x377f0682 or 0x377f0683
48338 ** 4: File format version. Currently 3007000
48339 ** 8: Database page size. Example: 1024
48340 ** 12: Checkpoint sequence number
48341 ** 16: Salt-1, random integer incremented with each checkpoint
48342 ** 20: Salt-2, a different random integer changing with each ckpt
48343 ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
48344 ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
48346 ** Immediately following the wal-header are zero or more frames. Each
48347 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
48348 ** of page data. The frame-header is six big-endian 32-bit unsigned
48349 ** integer values, as follows:
48351 ** 0: Page number.
48352 ** 4: For commit records, the size of the database image in pages
48353 ** after the commit. For all other records, zero.
48354 ** 8: Salt-1 (copied from the header)
48355 ** 12: Salt-2 (copied from the header)
48356 ** 16: Checksum-1.
48357 ** 20: Checksum-2.
48359 ** A frame is considered valid if and only if the following conditions are
48360 ** true:
48362 ** (1) The salt-1 and salt-2 values in the frame-header match
48363 ** salt values in the wal-header
48365 ** (2) The checksum values in the final 8 bytes of the frame-header
48366 ** exactly match the checksum computed consecutively on the
48367 ** WAL header and the first 8 bytes and the content of all frames
48368 ** up to and including the current frame.
48370 ** The checksum is computed using 32-bit big-endian integers if the
48371 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
48372 ** is computed using little-endian if the magic number is 0x377f0682.
48373 ** The checksum values are always stored in the frame header in a
48374 ** big-endian format regardless of which byte order is used to compute
48375 ** the checksum. The checksum is computed by interpreting the input as
48376 ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
48377 ** algorithm used for the checksum is as follows:
48379 ** for i from 0 to n-1 step 2:
48380 ** s0 += x[i] + s1;
48381 ** s1 += x[i+1] + s0;
48382 ** endfor
48384 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
48385 ** in reverse order (the largest fibonacci weight occurs on the first element
48386 ** of the sequence being summed.) The s1 value spans all 32-bit
48387 ** terms of the sequence whereas s0 omits the final term.
48389 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
48390 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
48391 ** The VFS.xSync operations serve as write barriers - all writes launched
48392 ** before the xSync must complete before any write that launches after the
48393 ** xSync begins.
48395 ** After each checkpoint, the salt-1 value is incremented and the salt-2
48396 ** value is randomized. This prevents old and new frames in the WAL from
48397 ** being considered valid at the same time and being checkpointing together
48398 ** following a crash.
48400 ** READER ALGORITHM
48402 ** To read a page from the database (call it page number P), a reader
48403 ** first checks the WAL to see if it contains page P. If so, then the
48404 ** last valid instance of page P that is a followed by a commit frame
48405 ** or is a commit frame itself becomes the value read. If the WAL
48406 ** contains no copies of page P that are valid and which are a commit
48407 ** frame or are followed by a commit frame, then page P is read from
48408 ** the database file.
48410 ** To start a read transaction, the reader records the index of the last
48411 ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
48412 ** for all subsequent read operations. New transactions can be appended
48413 ** to the WAL, but as long as the reader uses its original mxFrame value
48414 ** and ignores the newly appended content, it will see a consistent snapshot
48415 ** of the database from a single point in time. This technique allows
48416 ** multiple concurrent readers to view different versions of the database
48417 ** content simultaneously.
48419 ** The reader algorithm in the previous paragraphs works correctly, but
48420 ** because frames for page P can appear anywhere within the WAL, the
48421 ** reader has to scan the entire WAL looking for page P frames. If the
48422 ** WAL is large (multiple megabytes is typical) that scan can be slow,
48423 ** and read performance suffers. To overcome this problem, a separate
48424 ** data structure called the wal-index is maintained to expedite the
48425 ** search for frames of a particular page.
48427 ** WAL-INDEX FORMAT
48429 ** Conceptually, the wal-index is shared memory, though VFS implementations
48430 ** might choose to implement the wal-index using a mmapped file. Because
48431 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
48432 ** on a network filesystem. All users of the database must be able to
48433 ** share memory.
48435 ** The wal-index is transient. After a crash, the wal-index can (and should
48436 ** be) reconstructed from the original WAL file. In fact, the VFS is required
48437 ** to either truncate or zero the header of the wal-index when the last
48438 ** connection to it closes. Because the wal-index is transient, it can
48439 ** use an architecture-specific format; it does not have to be cross-platform.
48440 ** Hence, unlike the database and WAL file formats which store all values
48441 ** as big endian, the wal-index can store multi-byte values in the native
48442 ** byte order of the host computer.
48444 ** The purpose of the wal-index is to answer this question quickly: Given
48445 ** a page number P and a maximum frame index M, return the index of the
48446 ** last frame in the wal before frame M for page P in the WAL, or return
48447 ** NULL if there are no frames for page P in the WAL prior to M.
48449 ** The wal-index consists of a header region, followed by an one or
48450 ** more index blocks.
48452 ** The wal-index header contains the total number of frames within the WAL
48453 ** in the mxFrame field.
48455 ** Each index block except for the first contains information on
48456 ** HASHTABLE_NPAGE frames. The first index block contains information on
48457 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
48458 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
48459 ** first index block are the same size as all other index blocks in the
48460 ** wal-index.
48462 ** Each index block contains two sections, a page-mapping that contains the
48463 ** database page number associated with each wal frame, and a hash-table
48464 ** that allows readers to query an index block for a specific page number.
48465 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
48466 ** for the first index block) 32-bit page numbers. The first entry in the
48467 ** first index-block contains the database page number corresponding to the
48468 ** first frame in the WAL file. The first entry in the second index block
48469 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
48470 ** the log, and so on.
48472 ** The last index block in a wal-index usually contains less than the full
48473 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
48474 ** depending on the contents of the WAL file. This does not change the
48475 ** allocated size of the page-mapping array - the page-mapping array merely
48476 ** contains unused entries.
48478 ** Even without using the hash table, the last frame for page P
48479 ** can be found by scanning the page-mapping sections of each index block
48480 ** starting with the last index block and moving toward the first, and
48481 ** within each index block, starting at the end and moving toward the
48482 ** beginning. The first entry that equals P corresponds to the frame
48483 ** holding the content for that page.
48485 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
48486 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
48487 ** hash table for each page number in the mapping section, so the hash
48488 ** table is never more than half full. The expected number of collisions
48489 ** prior to finding a match is 1. Each entry of the hash table is an
48490 ** 1-based index of an entry in the mapping section of the same
48491 ** index block. Let K be the 1-based index of the largest entry in
48492 ** the mapping section. (For index blocks other than the last, K will
48493 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
48494 ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
48495 ** contain a value of 0.
48497 ** To look for page P in the hash table, first compute a hash iKey on
48498 ** P as follows:
48500 ** iKey = (P * 383) % HASHTABLE_NSLOT
48502 ** Then start scanning entries of the hash table, starting with iKey
48503 ** (wrapping around to the beginning when the end of the hash table is
48504 ** reached) until an unused hash slot is found. Let the first unused slot
48505 ** be at index iUnused. (iUnused might be less than iKey if there was
48506 ** wrap-around.) Because the hash table is never more than half full,
48507 ** the search is guaranteed to eventually hit an unused entry. Let
48508 ** iMax be the value between iKey and iUnused, closest to iUnused,
48509 ** where aHash[iMax]==P. If there is no iMax entry (if there exists
48510 ** no hash slot such that aHash[i]==p) then page P is not in the
48511 ** current index block. Otherwise the iMax-th mapping entry of the
48512 ** current index block corresponds to the last entry that references
48513 ** page P.
48515 ** A hash search begins with the last index block and moves toward the
48516 ** first index block, looking for entries corresponding to page P. On
48517 ** average, only two or three slots in each index block need to be
48518 ** examined in order to either find the last entry for page P, or to
48519 ** establish that no such entry exists in the block. Each index block
48520 ** holds over 4000 entries. So two or three index blocks are sufficient
48521 ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
48522 ** comparisons (on average) suffice to either locate a frame in the
48523 ** WAL or to establish that the frame does not exist in the WAL. This
48524 ** is much faster than scanning the entire 10MB WAL.
48526 ** Note that entries are added in order of increasing K. Hence, one
48527 ** reader might be using some value K0 and a second reader that started
48528 ** at a later time (after additional transactions were added to the WAL
48529 ** and to the wal-index) might be using a different value K1, where K1>K0.
48530 ** Both readers can use the same hash table and mapping section to get
48531 ** the correct result. There may be entries in the hash table with
48532 ** K>K0 but to the first reader, those entries will appear to be unused
48533 ** slots in the hash table and so the first reader will get an answer as
48534 ** if no values greater than K0 had ever been inserted into the hash table
48535 ** in the first place - which is what reader one wants. Meanwhile, the
48536 ** second reader using K1 will see additional values that were inserted
48537 ** later, which is exactly what reader two wants.
48539 ** When a rollback occurs, the value of K is decreased. Hash table entries
48540 ** that correspond to frames greater than the new K value are removed
48541 ** from the hash table at this point.
48543 #ifndef SQLITE_OMIT_WAL
48547 ** Trace output macros
48549 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
48550 SQLITE_PRIVATE int sqlite3WalTrace = 0;
48551 # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
48552 #else
48553 # define WALTRACE(X)
48554 #endif
48557 ** The maximum (and only) versions of the wal and wal-index formats
48558 ** that may be interpreted by this version of SQLite.
48560 ** If a client begins recovering a WAL file and finds that (a) the checksum
48561 ** values in the wal-header are correct and (b) the version field is not
48562 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
48564 ** Similarly, if a client successfully reads a wal-index header (i.e. the
48565 ** checksum test is successful) and finds that the version field is not
48566 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
48567 ** returns SQLITE_CANTOPEN.
48569 #define WAL_MAX_VERSION 3007000
48570 #define WALINDEX_MAX_VERSION 3007000
48573 ** Indices of various locking bytes. WAL_NREADER is the number
48574 ** of available reader locks and should be at least 3.
48576 #define WAL_WRITE_LOCK 0
48577 #define WAL_ALL_BUT_WRITE 1
48578 #define WAL_CKPT_LOCK 1
48579 #define WAL_RECOVER_LOCK 2
48580 #define WAL_READ_LOCK(I) (3+(I))
48581 #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
48584 /* Object declarations */
48585 typedef struct WalIndexHdr WalIndexHdr;
48586 typedef struct WalIterator WalIterator;
48587 typedef struct WalCkptInfo WalCkptInfo;
48591 ** The following object holds a copy of the wal-index header content.
48593 ** The actual header in the wal-index consists of two copies of this
48594 ** object.
48596 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
48597 ** Or it can be 1 to represent a 65536-byte page. The latter case was
48598 ** added in 3.7.1 when support for 64K pages was added.
48600 struct WalIndexHdr {
48601 u32 iVersion; /* Wal-index version */
48602 u32 unused; /* Unused (padding) field */
48603 u32 iChange; /* Counter incremented each transaction */
48604 u8 isInit; /* 1 when initialized */
48605 u8 bigEndCksum; /* True if checksums in WAL are big-endian */
48606 u16 szPage; /* Database page size in bytes. 1==64K */
48607 u32 mxFrame; /* Index of last valid frame in the WAL */
48608 u32 nPage; /* Size of database in pages */
48609 u32 aFrameCksum[2]; /* Checksum of last frame in log */
48610 u32 aSalt[2]; /* Two salt values copied from WAL header */
48611 u32 aCksum[2]; /* Checksum over all prior fields */
48615 ** A copy of the following object occurs in the wal-index immediately
48616 ** following the second copy of the WalIndexHdr. This object stores
48617 ** information used by checkpoint.
48619 ** nBackfill is the number of frames in the WAL that have been written
48620 ** back into the database. (We call the act of moving content from WAL to
48621 ** database "backfilling".) The nBackfill number is never greater than
48622 ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
48623 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
48624 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
48625 ** mxFrame back to zero when the WAL is reset.
48627 ** There is one entry in aReadMark[] for each reader lock. If a reader
48628 ** holds read-lock K, then the value in aReadMark[K] is no greater than
48629 ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
48630 ** for any aReadMark[] means that entry is unused. aReadMark[0] is
48631 ** a special case; its value is never used and it exists as a place-holder
48632 ** to avoid having to offset aReadMark[] indexs by one. Readers holding
48633 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
48634 ** directly from the database.
48636 ** The value of aReadMark[K] may only be changed by a thread that
48637 ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
48638 ** aReadMark[K] cannot changed while there is a reader is using that mark
48639 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
48641 ** The checkpointer may only transfer frames from WAL to database where
48642 ** the frame numbers are less than or equal to every aReadMark[] that is
48643 ** in use (that is, every aReadMark[j] for which there is a corresponding
48644 ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
48645 ** largest value and will increase an unused aReadMark[] to mxFrame if there
48646 ** is not already an aReadMark[] equal to mxFrame. The exception to the
48647 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
48648 ** in the WAL has been backfilled into the database) then new readers
48649 ** will choose aReadMark[0] which has value 0 and hence such reader will
48650 ** get all their all content directly from the database file and ignore
48651 ** the WAL.
48653 ** Writers normally append new frames to the end of the WAL. However,
48654 ** if nBackfill equals mxFrame (meaning that all WAL content has been
48655 ** written back into the database) and if no readers are using the WAL
48656 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
48657 ** the writer will first "reset" the WAL back to the beginning and start
48658 ** writing new content beginning at frame 1.
48660 ** We assume that 32-bit loads are atomic and so no locks are needed in
48661 ** order to read from any aReadMark[] entries.
48663 struct WalCkptInfo {
48664 u32 nBackfill; /* Number of WAL frames backfilled into DB */
48665 u32 aReadMark[WAL_NREADER]; /* Reader marks */
48667 #define READMARK_NOT_USED 0xffffffff
48670 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
48671 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
48672 ** only support mandatory file-locks, we do not read or write data
48673 ** from the region of the file on which locks are applied.
48675 #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
48676 #define WALINDEX_LOCK_RESERVED 16
48677 #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
48679 /* Size of header before each frame in wal */
48680 #define WAL_FRAME_HDRSIZE 24
48682 /* Size of write ahead log header, including checksum. */
48683 /* #define WAL_HDRSIZE 24 */
48684 #define WAL_HDRSIZE 32
48686 /* WAL magic value. Either this value, or the same value with the least
48687 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
48688 ** big-endian format in the first 4 bytes of a WAL file.
48690 ** If the LSB is set, then the checksums for each frame within the WAL
48691 ** file are calculated by treating all data as an array of 32-bit
48692 ** big-endian words. Otherwise, they are calculated by interpreting
48693 ** all data as 32-bit little-endian words.
48695 #define WAL_MAGIC 0x377f0682
48698 ** Return the offset of frame iFrame in the write-ahead log file,
48699 ** assuming a database page size of szPage bytes. The offset returned
48700 ** is to the start of the write-ahead log frame-header.
48702 #define walFrameOffset(iFrame, szPage) ( \
48703 WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
48707 ** An open write-ahead log file is represented by an instance of the
48708 ** following object.
48710 struct Wal {
48711 sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
48712 sqlite3_file *pDbFd; /* File handle for the database file */
48713 sqlite3_file *pWalFd; /* File handle for WAL file */
48714 u32 iCallback; /* Value to pass to log callback (or 0) */
48715 i64 mxWalSize; /* Truncate WAL to this size upon reset */
48716 int nWiData; /* Size of array apWiData */
48717 int szFirstBlock; /* Size of first block written to WAL file */
48718 volatile u32 **apWiData; /* Pointer to wal-index content in memory */
48719 u32 szPage; /* Database page size */
48720 i16 readLock; /* Which read lock is being held. -1 for none */
48721 u8 syncFlags; /* Flags to use to sync header writes */
48722 u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
48723 u8 writeLock; /* True if in a write transaction */
48724 u8 ckptLock; /* True if holding a checkpoint lock */
48725 u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
48726 u8 truncateOnCommit; /* True to truncate WAL file on commit */
48727 u8 syncHeader; /* Fsync the WAL header if true */
48728 u8 padToSectorBoundary; /* Pad transactions out to the next sector */
48729 WalIndexHdr hdr; /* Wal-index header for current transaction */
48730 const char *zWalName; /* Name of WAL file */
48731 u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
48732 #ifdef SQLITE_DEBUG
48733 u8 lockError; /* True if a locking error has occurred */
48734 #endif
48738 ** Candidate values for Wal.exclusiveMode.
48740 #define WAL_NORMAL_MODE 0
48741 #define WAL_EXCLUSIVE_MODE 1
48742 #define WAL_HEAPMEMORY_MODE 2
48745 ** Possible values for WAL.readOnly
48747 #define WAL_RDWR 0 /* Normal read/write connection */
48748 #define WAL_RDONLY 1 /* The WAL file is readonly */
48749 #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
48752 ** Each page of the wal-index mapping contains a hash-table made up of
48753 ** an array of HASHTABLE_NSLOT elements of the following type.
48755 typedef u16 ht_slot;
48758 ** This structure is used to implement an iterator that loops through
48759 ** all frames in the WAL in database page order. Where two or more frames
48760 ** correspond to the same database page, the iterator visits only the
48761 ** frame most recently written to the WAL (in other words, the frame with
48762 ** the largest index).
48764 ** The internals of this structure are only accessed by:
48766 ** walIteratorInit() - Create a new iterator,
48767 ** walIteratorNext() - Step an iterator,
48768 ** walIteratorFree() - Free an iterator.
48770 ** This functionality is used by the checkpoint code (see walCheckpoint()).
48772 struct WalIterator {
48773 int iPrior; /* Last result returned from the iterator */
48774 int nSegment; /* Number of entries in aSegment[] */
48775 struct WalSegment {
48776 int iNext; /* Next slot in aIndex[] not yet returned */
48777 ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
48778 u32 *aPgno; /* Array of page numbers. */
48779 int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
48780 int iZero; /* Frame number associated with aPgno[0] */
48781 } aSegment[1]; /* One for every 32KB page in the wal-index */
48785 ** Define the parameters of the hash tables in the wal-index file. There
48786 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
48787 ** wal-index.
48789 ** Changing any of these constants will alter the wal-index format and
48790 ** create incompatibilities.
48792 #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
48793 #define HASHTABLE_HASH_1 383 /* Should be prime */
48794 #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
48797 ** The block of page numbers associated with the first hash-table in a
48798 ** wal-index is smaller than usual. This is so that there is a complete
48799 ** hash-table on each aligned 32KB page of the wal-index.
48801 #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
48803 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
48804 #define WALINDEX_PGSZ ( \
48805 sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
48809 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
48810 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
48811 ** numbered from zero.
48813 ** If this call is successful, *ppPage is set to point to the wal-index
48814 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
48815 ** then an SQLite error code is returned and *ppPage is set to 0.
48817 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
48818 int rc = SQLITE_OK;
48820 /* Enlarge the pWal->apWiData[] array if required */
48821 if( pWal->nWiData<=iPage ){
48822 int nByte = sizeof(u32*)*(iPage+1);
48823 volatile u32 **apNew;
48824 apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
48825 if( !apNew ){
48826 *ppPage = 0;
48827 return SQLITE_NOMEM;
48829 memset((void*)&apNew[pWal->nWiData], 0,
48830 sizeof(u32*)*(iPage+1-pWal->nWiData));
48831 pWal->apWiData = apNew;
48832 pWal->nWiData = iPage+1;
48835 /* Request a pointer to the required page from the VFS */
48836 if( pWal->apWiData[iPage]==0 ){
48837 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
48838 pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
48839 if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
48840 }else{
48841 rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
48842 pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
48844 if( rc==SQLITE_READONLY ){
48845 pWal->readOnly |= WAL_SHM_RDONLY;
48846 rc = SQLITE_OK;
48851 *ppPage = pWal->apWiData[iPage];
48852 assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
48853 return rc;
48857 ** Return a pointer to the WalCkptInfo structure in the wal-index.
48859 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
48860 assert( pWal->nWiData>0 && pWal->apWiData[0] );
48861 return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
48865 ** Return a pointer to the WalIndexHdr structure in the wal-index.
48867 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
48868 assert( pWal->nWiData>0 && pWal->apWiData[0] );
48869 return (volatile WalIndexHdr*)pWal->apWiData[0];
48873 ** The argument to this macro must be of type u32. On a little-endian
48874 ** architecture, it returns the u32 value that results from interpreting
48875 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
48876 ** returns the value that would be produced by interpreting the 4 bytes
48877 ** of the input value as a little-endian integer.
48879 #define BYTESWAP32(x) ( \
48880 (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
48881 + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
48885 ** Generate or extend an 8 byte checksum based on the data in
48886 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
48887 ** initial values of 0 and 0 if aIn==NULL).
48889 ** The checksum is written back into aOut[] before returning.
48891 ** nByte must be a positive multiple of 8.
48893 static void walChecksumBytes(
48894 int nativeCksum, /* True for native byte-order, false for non-native */
48895 u8 *a, /* Content to be checksummed */
48896 int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
48897 const u32 *aIn, /* Initial checksum value input */
48898 u32 *aOut /* OUT: Final checksum value output */
48900 u32 s1, s2;
48901 u32 *aData = (u32 *)a;
48902 u32 *aEnd = (u32 *)&a[nByte];
48904 if( aIn ){
48905 s1 = aIn[0];
48906 s2 = aIn[1];
48907 }else{
48908 s1 = s2 = 0;
48911 assert( nByte>=8 );
48912 assert( (nByte&0x00000007)==0 );
48914 if( nativeCksum ){
48915 do {
48916 s1 += *aData++ + s2;
48917 s2 += *aData++ + s1;
48918 }while( aData<aEnd );
48919 }else{
48920 do {
48921 s1 += BYTESWAP32(aData[0]) + s2;
48922 s2 += BYTESWAP32(aData[1]) + s1;
48923 aData += 2;
48924 }while( aData<aEnd );
48927 aOut[0] = s1;
48928 aOut[1] = s2;
48931 static void walShmBarrier(Wal *pWal){
48932 if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
48933 sqlite3OsShmBarrier(pWal->pDbFd);
48938 ** Write the header information in pWal->hdr into the wal-index.
48940 ** The checksum on pWal->hdr is updated before it is written.
48942 static void walIndexWriteHdr(Wal *pWal){
48943 volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
48944 const int nCksum = offsetof(WalIndexHdr, aCksum);
48946 assert( pWal->writeLock );
48947 pWal->hdr.isInit = 1;
48948 pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
48949 walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
48950 memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
48951 walShmBarrier(pWal);
48952 memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
48956 ** This function encodes a single frame header and writes it to a buffer
48957 ** supplied by the caller. A frame-header is made up of a series of
48958 ** 4-byte big-endian integers, as follows:
48960 ** 0: Page number.
48961 ** 4: For commit records, the size of the database image in pages
48962 ** after the commit. For all other records, zero.
48963 ** 8: Salt-1 (copied from the wal-header)
48964 ** 12: Salt-2 (copied from the wal-header)
48965 ** 16: Checksum-1.
48966 ** 20: Checksum-2.
48968 static void walEncodeFrame(
48969 Wal *pWal, /* The write-ahead log */
48970 u32 iPage, /* Database page number for frame */
48971 u32 nTruncate, /* New db size (or 0 for non-commit frames) */
48972 u8 *aData, /* Pointer to page data */
48973 u8 *aFrame /* OUT: Write encoded frame here */
48975 int nativeCksum; /* True for native byte-order checksums */
48976 u32 *aCksum = pWal->hdr.aFrameCksum;
48977 assert( WAL_FRAME_HDRSIZE==24 );
48978 sqlite3Put4byte(&aFrame[0], iPage);
48979 sqlite3Put4byte(&aFrame[4], nTruncate);
48980 memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
48982 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
48983 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
48984 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
48986 sqlite3Put4byte(&aFrame[16], aCksum[0]);
48987 sqlite3Put4byte(&aFrame[20], aCksum[1]);
48991 ** Check to see if the frame with header in aFrame[] and content
48992 ** in aData[] is valid. If it is a valid frame, fill *piPage and
48993 ** *pnTruncate and return true. Return if the frame is not valid.
48995 static int walDecodeFrame(
48996 Wal *pWal, /* The write-ahead log */
48997 u32 *piPage, /* OUT: Database page number for frame */
48998 u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
48999 u8 *aData, /* Pointer to page data (for checksum) */
49000 u8 *aFrame /* Frame data */
49002 int nativeCksum; /* True for native byte-order checksums */
49003 u32 *aCksum = pWal->hdr.aFrameCksum;
49004 u32 pgno; /* Page number of the frame */
49005 assert( WAL_FRAME_HDRSIZE==24 );
49007 /* A frame is only valid if the salt values in the frame-header
49008 ** match the salt values in the wal-header.
49010 if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
49011 return 0;
49014 /* A frame is only valid if the page number is creater than zero.
49016 pgno = sqlite3Get4byte(&aFrame[0]);
49017 if( pgno==0 ){
49018 return 0;
49021 /* A frame is only valid if a checksum of the WAL header,
49022 ** all prior frams, the first 16 bytes of this frame-header,
49023 ** and the frame-data matches the checksum in the last 8
49024 ** bytes of this frame-header.
49026 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
49027 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
49028 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
49029 if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
49030 || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
49032 /* Checksum failed. */
49033 return 0;
49036 /* If we reach this point, the frame is valid. Return the page number
49037 ** and the new database size.
49039 *piPage = pgno;
49040 *pnTruncate = sqlite3Get4byte(&aFrame[4]);
49041 return 1;
49045 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
49047 ** Names of locks. This routine is used to provide debugging output and is not
49048 ** a part of an ordinary build.
49050 static const char *walLockName(int lockIdx){
49051 if( lockIdx==WAL_WRITE_LOCK ){
49052 return "WRITE-LOCK";
49053 }else if( lockIdx==WAL_CKPT_LOCK ){
49054 return "CKPT-LOCK";
49055 }else if( lockIdx==WAL_RECOVER_LOCK ){
49056 return "RECOVER-LOCK";
49057 }else{
49058 static char zName[15];
49059 sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
49060 lockIdx-WAL_READ_LOCK(0));
49061 return zName;
49064 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
49068 ** Set or release locks on the WAL. Locks are either shared or exclusive.
49069 ** A lock cannot be moved directly between shared and exclusive - it must go
49070 ** through the unlocked state first.
49072 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
49074 static int walLockShared(Wal *pWal, int lockIdx){
49075 int rc;
49076 if( pWal->exclusiveMode ) return SQLITE_OK;
49077 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
49078 SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
49079 WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
49080 walLockName(lockIdx), rc ? "failed" : "ok"));
49081 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
49082 return rc;
49084 static void walUnlockShared(Wal *pWal, int lockIdx){
49085 if( pWal->exclusiveMode ) return;
49086 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
49087 SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
49088 WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
49090 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
49091 int rc;
49092 if( pWal->exclusiveMode ) return SQLITE_OK;
49093 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
49094 SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
49095 WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
49096 walLockName(lockIdx), n, rc ? "failed" : "ok"));
49097 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
49098 return rc;
49100 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
49101 if( pWal->exclusiveMode ) return;
49102 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
49103 SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
49104 WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
49105 walLockName(lockIdx), n));
49109 ** Compute a hash on a page number. The resulting hash value must land
49110 ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
49111 ** the hash to the next value in the event of a collision.
49113 static int walHash(u32 iPage){
49114 assert( iPage>0 );
49115 assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
49116 return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
49118 static int walNextHash(int iPriorHash){
49119 return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
49123 ** Return pointers to the hash table and page number array stored on
49124 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
49125 ** numbered starting from 0.
49127 ** Set output variable *paHash to point to the start of the hash table
49128 ** in the wal-index file. Set *piZero to one less than the frame
49129 ** number of the first frame indexed by this hash table. If a
49130 ** slot in the hash table is set to N, it refers to frame number
49131 ** (*piZero+N) in the log.
49133 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
49134 ** first frame indexed by the hash table, frame (*piZero+1).
49136 static int walHashGet(
49137 Wal *pWal, /* WAL handle */
49138 int iHash, /* Find the iHash'th table */
49139 volatile ht_slot **paHash, /* OUT: Pointer to hash index */
49140 volatile u32 **paPgno, /* OUT: Pointer to page number array */
49141 u32 *piZero /* OUT: Frame associated with *paPgno[0] */
49143 int rc; /* Return code */
49144 volatile u32 *aPgno;
49146 rc = walIndexPage(pWal, iHash, &aPgno);
49147 assert( rc==SQLITE_OK || iHash>0 );
49149 if( rc==SQLITE_OK ){
49150 u32 iZero;
49151 volatile ht_slot *aHash;
49153 aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
49154 if( iHash==0 ){
49155 aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
49156 iZero = 0;
49157 }else{
49158 iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
49161 *paPgno = &aPgno[-1];
49162 *paHash = aHash;
49163 *piZero = iZero;
49165 return rc;
49169 ** Return the number of the wal-index page that contains the hash-table
49170 ** and page-number array that contain entries corresponding to WAL frame
49171 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
49172 ** are numbered starting from 0.
49174 static int walFramePage(u32 iFrame){
49175 int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
49176 assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
49177 && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
49178 && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
49179 && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
49180 && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
49182 return iHash;
49186 ** Return the page number associated with frame iFrame in this WAL.
49188 static u32 walFramePgno(Wal *pWal, u32 iFrame){
49189 int iHash = walFramePage(iFrame);
49190 if( iHash==0 ){
49191 return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
49193 return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
49197 ** Remove entries from the hash table that point to WAL slots greater
49198 ** than pWal->hdr.mxFrame.
49200 ** This function is called whenever pWal->hdr.mxFrame is decreased due
49201 ** to a rollback or savepoint.
49203 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
49204 ** updated. Any later hash tables will be automatically cleared when
49205 ** pWal->hdr.mxFrame advances to the point where those hash tables are
49206 ** actually needed.
49208 static void walCleanupHash(Wal *pWal){
49209 volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
49210 volatile u32 *aPgno = 0; /* Page number array for hash table */
49211 u32 iZero = 0; /* frame == (aHash[x]+iZero) */
49212 int iLimit = 0; /* Zero values greater than this */
49213 int nByte; /* Number of bytes to zero in aPgno[] */
49214 int i; /* Used to iterate through aHash[] */
49216 assert( pWal->writeLock );
49217 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
49218 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
49219 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
49221 if( pWal->hdr.mxFrame==0 ) return;
49223 /* Obtain pointers to the hash-table and page-number array containing
49224 ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
49225 ** that the page said hash-table and array reside on is already mapped.
49227 assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
49228 assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
49229 walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
49231 /* Zero all hash-table entries that correspond to frame numbers greater
49232 ** than pWal->hdr.mxFrame.
49234 iLimit = pWal->hdr.mxFrame - iZero;
49235 assert( iLimit>0 );
49236 for(i=0; i<HASHTABLE_NSLOT; i++){
49237 if( aHash[i]>iLimit ){
49238 aHash[i] = 0;
49242 /* Zero the entries in the aPgno array that correspond to frames with
49243 ** frame numbers greater than pWal->hdr.mxFrame.
49245 nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
49246 memset((void *)&aPgno[iLimit+1], 0, nByte);
49248 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
49249 /* Verify that the every entry in the mapping region is still reachable
49250 ** via the hash table even after the cleanup.
49252 if( iLimit ){
49253 int i; /* Loop counter */
49254 int iKey; /* Hash key */
49255 for(i=1; i<=iLimit; i++){
49256 for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
49257 if( aHash[iKey]==i ) break;
49259 assert( aHash[iKey]==i );
49262 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
49267 ** Set an entry in the wal-index that will map database page number
49268 ** pPage into WAL frame iFrame.
49270 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
49271 int rc; /* Return code */
49272 u32 iZero = 0; /* One less than frame number of aPgno[1] */
49273 volatile u32 *aPgno = 0; /* Page number array */
49274 volatile ht_slot *aHash = 0; /* Hash table */
49276 rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
49278 /* Assuming the wal-index file was successfully mapped, populate the
49279 ** page number array and hash table entry.
49281 if( rc==SQLITE_OK ){
49282 int iKey; /* Hash table key */
49283 int idx; /* Value to write to hash-table slot */
49284 int nCollide; /* Number of hash collisions */
49286 idx = iFrame - iZero;
49287 assert( idx <= HASHTABLE_NSLOT/2 + 1 );
49289 /* If this is the first entry to be added to this hash-table, zero the
49290 ** entire hash table and aPgno[] array before proceeding.
49292 if( idx==1 ){
49293 int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
49294 memset((void*)&aPgno[1], 0, nByte);
49297 /* If the entry in aPgno[] is already set, then the previous writer
49298 ** must have exited unexpectedly in the middle of a transaction (after
49299 ** writing one or more dirty pages to the WAL to free up memory).
49300 ** Remove the remnants of that writers uncommitted transaction from
49301 ** the hash-table before writing any new entries.
49303 if( aPgno[idx] ){
49304 walCleanupHash(pWal);
49305 assert( !aPgno[idx] );
49308 /* Write the aPgno[] array entry and the hash-table slot. */
49309 nCollide = idx;
49310 for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
49311 if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
49313 aPgno[idx] = iPage;
49314 aHash[iKey] = (ht_slot)idx;
49316 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
49317 /* Verify that the number of entries in the hash table exactly equals
49318 ** the number of entries in the mapping region.
49321 int i; /* Loop counter */
49322 int nEntry = 0; /* Number of entries in the hash table */
49323 for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
49324 assert( nEntry==idx );
49327 /* Verify that the every entry in the mapping region is reachable
49328 ** via the hash table. This turns out to be a really, really expensive
49329 ** thing to check, so only do this occasionally - not on every
49330 ** iteration.
49332 if( (idx&0x3ff)==0 ){
49333 int i; /* Loop counter */
49334 for(i=1; i<=idx; i++){
49335 for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
49336 if( aHash[iKey]==i ) break;
49338 assert( aHash[iKey]==i );
49341 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
49345 return rc;
49350 ** Recover the wal-index by reading the write-ahead log file.
49352 ** This routine first tries to establish an exclusive lock on the
49353 ** wal-index to prevent other threads/processes from doing anything
49354 ** with the WAL or wal-index while recovery is running. The
49355 ** WAL_RECOVER_LOCK is also held so that other threads will know
49356 ** that this thread is running recovery. If unable to establish
49357 ** the necessary locks, this routine returns SQLITE_BUSY.
49359 static int walIndexRecover(Wal *pWal){
49360 int rc; /* Return Code */
49361 i64 nSize; /* Size of log file */
49362 u32 aFrameCksum[2] = {0, 0};
49363 int iLock; /* Lock offset to lock for checkpoint */
49364 int nLock; /* Number of locks to hold */
49366 /* Obtain an exclusive lock on all byte in the locking range not already
49367 ** locked by the caller. The caller is guaranteed to have locked the
49368 ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
49369 ** If successful, the same bytes that are locked here are unlocked before
49370 ** this function returns.
49372 assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
49373 assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
49374 assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
49375 assert( pWal->writeLock );
49376 iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
49377 nLock = SQLITE_SHM_NLOCK - iLock;
49378 rc = walLockExclusive(pWal, iLock, nLock);
49379 if( rc ){
49380 return rc;
49382 WALTRACE(("WAL%p: recovery begin...\n", pWal));
49384 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
49386 rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
49387 if( rc!=SQLITE_OK ){
49388 goto recovery_error;
49391 if( nSize>WAL_HDRSIZE ){
49392 u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
49393 u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
49394 int szFrame; /* Number of bytes in buffer aFrame[] */
49395 u8 *aData; /* Pointer to data part of aFrame buffer */
49396 int iFrame; /* Index of last frame read */
49397 i64 iOffset; /* Next offset to read from log file */
49398 int szPage; /* Page size according to the log */
49399 u32 magic; /* Magic value read from WAL header */
49400 u32 version; /* Magic value read from WAL header */
49401 int isValid; /* True if this frame is valid */
49403 /* Read in the WAL header. */
49404 rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
49405 if( rc!=SQLITE_OK ){
49406 goto recovery_error;
49409 /* If the database page size is not a power of two, or is greater than
49410 ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
49411 ** data. Similarly, if the 'magic' value is invalid, ignore the whole
49412 ** WAL file.
49414 magic = sqlite3Get4byte(&aBuf[0]);
49415 szPage = sqlite3Get4byte(&aBuf[8]);
49416 if( (magic&0xFFFFFFFE)!=WAL_MAGIC
49417 || szPage&(szPage-1)
49418 || szPage>SQLITE_MAX_PAGE_SIZE
49419 || szPage<512
49421 goto finished;
49423 pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
49424 pWal->szPage = szPage;
49425 pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
49426 memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
49428 /* Verify that the WAL header checksum is correct */
49429 walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
49430 aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
49432 if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
49433 || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
49435 goto finished;
49438 /* Verify that the version number on the WAL format is one that
49439 ** are able to understand */
49440 version = sqlite3Get4byte(&aBuf[4]);
49441 if( version!=WAL_MAX_VERSION ){
49442 rc = SQLITE_CANTOPEN_BKPT;
49443 goto finished;
49446 /* Malloc a buffer to read frames into. */
49447 szFrame = szPage + WAL_FRAME_HDRSIZE;
49448 aFrame = (u8 *)sqlite3_malloc(szFrame);
49449 if( !aFrame ){
49450 rc = SQLITE_NOMEM;
49451 goto recovery_error;
49453 aData = &aFrame[WAL_FRAME_HDRSIZE];
49455 /* Read all frames from the log file. */
49456 iFrame = 0;
49457 for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
49458 u32 pgno; /* Database page number for frame */
49459 u32 nTruncate; /* dbsize field from frame header */
49461 /* Read and decode the next log frame. */
49462 iFrame++;
49463 rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
49464 if( rc!=SQLITE_OK ) break;
49465 isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
49466 if( !isValid ) break;
49467 rc = walIndexAppend(pWal, iFrame, pgno);
49468 if( rc!=SQLITE_OK ) break;
49470 /* If nTruncate is non-zero, this is a commit record. */
49471 if( nTruncate ){
49472 pWal->hdr.mxFrame = iFrame;
49473 pWal->hdr.nPage = nTruncate;
49474 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
49475 testcase( szPage<=32768 );
49476 testcase( szPage>=65536 );
49477 aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
49478 aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
49482 sqlite3_free(aFrame);
49485 finished:
49486 if( rc==SQLITE_OK ){
49487 volatile WalCkptInfo *pInfo;
49488 int i;
49489 pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
49490 pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
49491 walIndexWriteHdr(pWal);
49493 /* Reset the checkpoint-header. This is safe because this thread is
49494 ** currently holding locks that exclude all other readers, writers and
49495 ** checkpointers.
49497 pInfo = walCkptInfo(pWal);
49498 pInfo->nBackfill = 0;
49499 pInfo->aReadMark[0] = 0;
49500 for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
49501 if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
49503 /* If more than one frame was recovered from the log file, report an
49504 ** event via sqlite3_log(). This is to help with identifying performance
49505 ** problems caused by applications routinely shutting down without
49506 ** checkpointing the log file.
49508 if( pWal->hdr.nPage ){
49509 sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
49510 "recovered %d frames from WAL file %s",
49511 pWal->hdr.mxFrame, pWal->zWalName
49516 recovery_error:
49517 WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
49518 walUnlockExclusive(pWal, iLock, nLock);
49519 return rc;
49523 ** Close an open wal-index.
49525 static void walIndexClose(Wal *pWal, int isDelete){
49526 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
49527 int i;
49528 for(i=0; i<pWal->nWiData; i++){
49529 sqlite3_free((void *)pWal->apWiData[i]);
49530 pWal->apWiData[i] = 0;
49532 }else{
49533 sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
49538 ** Open a connection to the WAL file zWalName. The database file must
49539 ** already be opened on connection pDbFd. The buffer that zWalName points
49540 ** to must remain valid for the lifetime of the returned Wal* handle.
49542 ** A SHARED lock should be held on the database file when this function
49543 ** is called. The purpose of this SHARED lock is to prevent any other
49544 ** client from unlinking the WAL or wal-index file. If another process
49545 ** were to do this just after this client opened one of these files, the
49546 ** system would be badly broken.
49548 ** If the log file is successfully opened, SQLITE_OK is returned and
49549 ** *ppWal is set to point to a new WAL handle. If an error occurs,
49550 ** an SQLite error code is returned and *ppWal is left unmodified.
49552 SQLITE_PRIVATE int sqlite3WalOpen(
49553 sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
49554 sqlite3_file *pDbFd, /* The open database file */
49555 const char *zWalName, /* Name of the WAL file */
49556 int bNoShm, /* True to run in heap-memory mode */
49557 i64 mxWalSize, /* Truncate WAL to this size on reset */
49558 Wal **ppWal /* OUT: Allocated Wal handle */
49560 int rc; /* Return Code */
49561 Wal *pRet; /* Object to allocate and return */
49562 int flags; /* Flags passed to OsOpen() */
49564 assert( zWalName && zWalName[0] );
49565 assert( pDbFd );
49567 /* In the amalgamation, the os_unix.c and os_win.c source files come before
49568 ** this source file. Verify that the #defines of the locking byte offsets
49569 ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
49571 #ifdef WIN_SHM_BASE
49572 assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
49573 #endif
49574 #ifdef UNIX_SHM_BASE
49575 assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
49576 #endif
49579 /* Allocate an instance of struct Wal to return. */
49580 *ppWal = 0;
49581 pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
49582 if( !pRet ){
49583 return SQLITE_NOMEM;
49586 pRet->pVfs = pVfs;
49587 pRet->pWalFd = (sqlite3_file *)&pRet[1];
49588 pRet->pDbFd = pDbFd;
49589 pRet->readLock = -1;
49590 pRet->mxWalSize = mxWalSize;
49591 pRet->zWalName = zWalName;
49592 pRet->syncHeader = 1;
49593 pRet->padToSectorBoundary = 1;
49594 pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
49596 /* Open file handle on the write-ahead log file. */
49597 flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
49598 rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
49599 if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
49600 pRet->readOnly = WAL_RDONLY;
49603 if( rc!=SQLITE_OK ){
49604 walIndexClose(pRet, 0);
49605 sqlite3OsClose(pRet->pWalFd);
49606 sqlite3_free(pRet);
49607 }else{
49608 int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
49609 if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
49610 if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
49611 pRet->padToSectorBoundary = 0;
49613 *ppWal = pRet;
49614 WALTRACE(("WAL%d: opened\n", pRet));
49616 return rc;
49620 ** Change the size to which the WAL file is trucated on each reset.
49622 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
49623 if( pWal ) pWal->mxWalSize = iLimit;
49627 ** Find the smallest page number out of all pages held in the WAL that
49628 ** has not been returned by any prior invocation of this method on the
49629 ** same WalIterator object. Write into *piFrame the frame index where
49630 ** that page was last written into the WAL. Write into *piPage the page
49631 ** number.
49633 ** Return 0 on success. If there are no pages in the WAL with a page
49634 ** number larger than *piPage, then return 1.
49636 static int walIteratorNext(
49637 WalIterator *p, /* Iterator */
49638 u32 *piPage, /* OUT: The page number of the next page */
49639 u32 *piFrame /* OUT: Wal frame index of next page */
49641 u32 iMin; /* Result pgno must be greater than iMin */
49642 u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
49643 int i; /* For looping through segments */
49645 iMin = p->iPrior;
49646 assert( iMin<0xffffffff );
49647 for(i=p->nSegment-1; i>=0; i--){
49648 struct WalSegment *pSegment = &p->aSegment[i];
49649 while( pSegment->iNext<pSegment->nEntry ){
49650 u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
49651 if( iPg>iMin ){
49652 if( iPg<iRet ){
49653 iRet = iPg;
49654 *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
49656 break;
49658 pSegment->iNext++;
49662 *piPage = p->iPrior = iRet;
49663 return (iRet==0xFFFFFFFF);
49667 ** This function merges two sorted lists into a single sorted list.
49669 ** aLeft[] and aRight[] are arrays of indices. The sort key is
49670 ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
49671 ** is guaranteed for all J<K:
49673 ** aContent[aLeft[J]] < aContent[aLeft[K]]
49674 ** aContent[aRight[J]] < aContent[aRight[K]]
49676 ** This routine overwrites aRight[] with a new (probably longer) sequence
49677 ** of indices such that the aRight[] contains every index that appears in
49678 ** either aLeft[] or the old aRight[] and such that the second condition
49679 ** above is still met.
49681 ** The aContent[aLeft[X]] values will be unique for all X. And the
49682 ** aContent[aRight[X]] values will be unique too. But there might be
49683 ** one or more combinations of X and Y such that
49685 ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
49687 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
49689 static void walMerge(
49690 const u32 *aContent, /* Pages in wal - keys for the sort */
49691 ht_slot *aLeft, /* IN: Left hand input list */
49692 int nLeft, /* IN: Elements in array *paLeft */
49693 ht_slot **paRight, /* IN/OUT: Right hand input list */
49694 int *pnRight, /* IN/OUT: Elements in *paRight */
49695 ht_slot *aTmp /* Temporary buffer */
49697 int iLeft = 0; /* Current index in aLeft */
49698 int iRight = 0; /* Current index in aRight */
49699 int iOut = 0; /* Current index in output buffer */
49700 int nRight = *pnRight;
49701 ht_slot *aRight = *paRight;
49703 assert( nLeft>0 && nRight>0 );
49704 while( iRight<nRight || iLeft<nLeft ){
49705 ht_slot logpage;
49706 Pgno dbpage;
49708 if( (iLeft<nLeft)
49709 && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
49711 logpage = aLeft[iLeft++];
49712 }else{
49713 logpage = aRight[iRight++];
49715 dbpage = aContent[logpage];
49717 aTmp[iOut++] = logpage;
49718 if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
49720 assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
49721 assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
49724 *paRight = aLeft;
49725 *pnRight = iOut;
49726 memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
49730 ** Sort the elements in list aList using aContent[] as the sort key.
49731 ** Remove elements with duplicate keys, preferring to keep the
49732 ** larger aList[] values.
49734 ** The aList[] entries are indices into aContent[]. The values in
49735 ** aList[] are to be sorted so that for all J<K:
49737 ** aContent[aList[J]] < aContent[aList[K]]
49739 ** For any X and Y such that
49741 ** aContent[aList[X]] == aContent[aList[Y]]
49743 ** Keep the larger of the two values aList[X] and aList[Y] and discard
49744 ** the smaller.
49746 static void walMergesort(
49747 const u32 *aContent, /* Pages in wal */
49748 ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
49749 ht_slot *aList, /* IN/OUT: List to sort */
49750 int *pnList /* IN/OUT: Number of elements in aList[] */
49752 struct Sublist {
49753 int nList; /* Number of elements in aList */
49754 ht_slot *aList; /* Pointer to sub-list content */
49757 const int nList = *pnList; /* Size of input list */
49758 int nMerge = 0; /* Number of elements in list aMerge */
49759 ht_slot *aMerge = 0; /* List to be merged */
49760 int iList; /* Index into input list */
49761 int iSub = 0; /* Index into aSub array */
49762 struct Sublist aSub[13]; /* Array of sub-lists */
49764 memset(aSub, 0, sizeof(aSub));
49765 assert( nList<=HASHTABLE_NPAGE && nList>0 );
49766 assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
49768 for(iList=0; iList<nList; iList++){
49769 nMerge = 1;
49770 aMerge = &aList[iList];
49771 for(iSub=0; iList & (1<<iSub); iSub++){
49772 struct Sublist *p = &aSub[iSub];
49773 assert( p->aList && p->nList<=(1<<iSub) );
49774 assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
49775 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
49777 aSub[iSub].aList = aMerge;
49778 aSub[iSub].nList = nMerge;
49781 for(iSub++; iSub<ArraySize(aSub); iSub++){
49782 if( nList & (1<<iSub) ){
49783 struct Sublist *p = &aSub[iSub];
49784 assert( p->nList<=(1<<iSub) );
49785 assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
49786 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
49789 assert( aMerge==aList );
49790 *pnList = nMerge;
49792 #ifdef SQLITE_DEBUG
49794 int i;
49795 for(i=1; i<*pnList; i++){
49796 assert( aContent[aList[i]] > aContent[aList[i-1]] );
49799 #endif
49803 ** Free an iterator allocated by walIteratorInit().
49805 static void walIteratorFree(WalIterator *p){
49806 sqlite3ScratchFree(p);
49810 ** Construct a WalInterator object that can be used to loop over all
49811 ** pages in the WAL in ascending order. The caller must hold the checkpoint
49812 ** lock.
49814 ** On success, make *pp point to the newly allocated WalInterator object
49815 ** return SQLITE_OK. Otherwise, return an error code. If this routine
49816 ** returns an error, the value of *pp is undefined.
49818 ** The calling routine should invoke walIteratorFree() to destroy the
49819 ** WalIterator object when it has finished with it.
49821 static int walIteratorInit(Wal *pWal, WalIterator **pp){
49822 WalIterator *p; /* Return value */
49823 int nSegment; /* Number of segments to merge */
49824 u32 iLast; /* Last frame in log */
49825 int nByte; /* Number of bytes to allocate */
49826 int i; /* Iterator variable */
49827 ht_slot *aTmp; /* Temp space used by merge-sort */
49828 int rc = SQLITE_OK; /* Return Code */
49830 /* This routine only runs while holding the checkpoint lock. And
49831 ** it only runs if there is actually content in the log (mxFrame>0).
49833 assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
49834 iLast = pWal->hdr.mxFrame;
49836 /* Allocate space for the WalIterator object. */
49837 nSegment = walFramePage(iLast) + 1;
49838 nByte = sizeof(WalIterator)
49839 + (nSegment-1)*sizeof(struct WalSegment)
49840 + iLast*sizeof(ht_slot);
49841 p = (WalIterator *)sqlite3ScratchMalloc(nByte);
49842 if( !p ){
49843 return SQLITE_NOMEM;
49845 memset(p, 0, nByte);
49846 p->nSegment = nSegment;
49848 /* Allocate temporary space used by the merge-sort routine. This block
49849 ** of memory will be freed before this function returns.
49851 aTmp = (ht_slot *)sqlite3ScratchMalloc(
49852 sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
49854 if( !aTmp ){
49855 rc = SQLITE_NOMEM;
49858 for(i=0; rc==SQLITE_OK && i<nSegment; i++){
49859 volatile ht_slot *aHash;
49860 u32 iZero;
49861 volatile u32 *aPgno;
49863 rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
49864 if( rc==SQLITE_OK ){
49865 int j; /* Counter variable */
49866 int nEntry; /* Number of entries in this segment */
49867 ht_slot *aIndex; /* Sorted index for this segment */
49869 aPgno++;
49870 if( (i+1)==nSegment ){
49871 nEntry = (int)(iLast - iZero);
49872 }else{
49873 nEntry = (int)((u32*)aHash - (u32*)aPgno);
49875 aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
49876 iZero++;
49878 for(j=0; j<nEntry; j++){
49879 aIndex[j] = (ht_slot)j;
49881 walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
49882 p->aSegment[i].iZero = iZero;
49883 p->aSegment[i].nEntry = nEntry;
49884 p->aSegment[i].aIndex = aIndex;
49885 p->aSegment[i].aPgno = (u32 *)aPgno;
49888 sqlite3ScratchFree(aTmp);
49890 if( rc!=SQLITE_OK ){
49891 walIteratorFree(p);
49893 *pp = p;
49894 return rc;
49898 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
49899 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
49900 ** busy-handler function. Invoke it and retry the lock until either the
49901 ** lock is successfully obtained or the busy-handler returns 0.
49903 static int walBusyLock(
49904 Wal *pWal, /* WAL connection */
49905 int (*xBusy)(void*), /* Function to call when busy */
49906 void *pBusyArg, /* Context argument for xBusyHandler */
49907 int lockIdx, /* Offset of first byte to lock */
49908 int n /* Number of bytes to lock */
49910 int rc;
49911 do {
49912 rc = walLockExclusive(pWal, lockIdx, n);
49913 }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
49914 return rc;
49918 ** The cache of the wal-index header must be valid to call this function.
49919 ** Return the page-size in bytes used by the database.
49921 static int walPagesize(Wal *pWal){
49922 return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
49926 ** Copy as much content as we can from the WAL back into the database file
49927 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
49929 ** The amount of information copies from WAL to database might be limited
49930 ** by active readers. This routine will never overwrite a database page
49931 ** that a concurrent reader might be using.
49933 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
49934 ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
49935 ** checkpoints are always run by a background thread or background
49936 ** process, foreground threads will never block on a lengthy fsync call.
49938 ** Fsync is called on the WAL before writing content out of the WAL and
49939 ** into the database. This ensures that if the new content is persistent
49940 ** in the WAL and can be recovered following a power-loss or hard reset.
49942 ** Fsync is also called on the database file if (and only if) the entire
49943 ** WAL content is copied into the database file. This second fsync makes
49944 ** it safe to delete the WAL since the new content will persist in the
49945 ** database file.
49947 ** This routine uses and updates the nBackfill field of the wal-index header.
49948 ** This is the only routine that will increase the value of nBackfill.
49949 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
49950 ** its value.)
49952 ** The caller must be holding sufficient locks to ensure that no other
49953 ** checkpoint is running (in any other thread or process) at the same
49954 ** time.
49956 static int walCheckpoint(
49957 Wal *pWal, /* Wal connection */
49958 int eMode, /* One of PASSIVE, FULL or RESTART */
49959 int (*xBusyCall)(void*), /* Function to call when busy */
49960 void *pBusyArg, /* Context argument for xBusyHandler */
49961 int sync_flags, /* Flags for OsSync() (or 0) */
49962 u8 *zBuf /* Temporary buffer to use */
49964 int rc; /* Return code */
49965 int szPage; /* Database page-size */
49966 WalIterator *pIter = 0; /* Wal iterator context */
49967 u32 iDbpage = 0; /* Next database page to write */
49968 u32 iFrame = 0; /* Wal frame containing data for iDbpage */
49969 u32 mxSafeFrame; /* Max frame that can be backfilled */
49970 u32 mxPage; /* Max database page to write */
49971 int i; /* Loop counter */
49972 volatile WalCkptInfo *pInfo; /* The checkpoint status information */
49973 int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */
49975 szPage = walPagesize(pWal);
49976 testcase( szPage<=32768 );
49977 testcase( szPage>=65536 );
49978 pInfo = walCkptInfo(pWal);
49979 if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
49981 /* Allocate the iterator */
49982 rc = walIteratorInit(pWal, &pIter);
49983 if( rc!=SQLITE_OK ){
49984 return rc;
49986 assert( pIter );
49988 if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
49990 /* Compute in mxSafeFrame the index of the last frame of the WAL that is
49991 ** safe to write into the database. Frames beyond mxSafeFrame might
49992 ** overwrite database pages that are in use by active readers and thus
49993 ** cannot be backfilled from the WAL.
49995 mxSafeFrame = pWal->hdr.mxFrame;
49996 mxPage = pWal->hdr.nPage;
49997 for(i=1; i<WAL_NREADER; i++){
49998 u32 y = pInfo->aReadMark[i];
49999 if( mxSafeFrame>y ){
50000 assert( y<=pWal->hdr.mxFrame );
50001 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
50002 if( rc==SQLITE_OK ){
50003 pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
50004 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
50005 }else if( rc==SQLITE_BUSY ){
50006 mxSafeFrame = y;
50007 xBusy = 0;
50008 }else{
50009 goto walcheckpoint_out;
50014 if( pInfo->nBackfill<mxSafeFrame
50015 && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
50017 i64 nSize; /* Current size of database file */
50018 u32 nBackfill = pInfo->nBackfill;
50020 /* Sync the WAL to disk */
50021 if( sync_flags ){
50022 rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
50025 /* If the database may grow as a result of this checkpoint, hint
50026 ** about the eventual size of the db file to the VFS layer.
50028 if( rc==SQLITE_OK ){
50029 i64 nReq = ((i64)mxPage * szPage);
50030 rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
50031 if( rc==SQLITE_OK && nSize<nReq ){
50032 sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
50037 /* Iterate through the contents of the WAL, copying data to the db file. */
50038 while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
50039 i64 iOffset;
50040 assert( walFramePgno(pWal, iFrame)==iDbpage );
50041 if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
50042 iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
50043 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
50044 rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
50045 if( rc!=SQLITE_OK ) break;
50046 iOffset = (iDbpage-1)*(i64)szPage;
50047 testcase( IS_BIG_INT(iOffset) );
50048 rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
50049 if( rc!=SQLITE_OK ) break;
50052 /* If work was actually accomplished... */
50053 if( rc==SQLITE_OK ){
50054 if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
50055 i64 szDb = pWal->hdr.nPage*(i64)szPage;
50056 testcase( IS_BIG_INT(szDb) );
50057 rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
50058 if( rc==SQLITE_OK && sync_flags ){
50059 rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
50062 if( rc==SQLITE_OK ){
50063 pInfo->nBackfill = mxSafeFrame;
50067 /* Release the reader lock held while backfilling */
50068 walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
50071 if( rc==SQLITE_BUSY ){
50072 /* Reset the return code so as not to report a checkpoint failure
50073 ** just because there are active readers. */
50074 rc = SQLITE_OK;
50077 /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
50078 ** file has been copied into the database file, then block until all
50079 ** readers have finished using the wal file. This ensures that the next
50080 ** process to write to the database restarts the wal file.
50082 if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
50083 assert( pWal->writeLock );
50084 if( pInfo->nBackfill<pWal->hdr.mxFrame ){
50085 rc = SQLITE_BUSY;
50086 }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
50087 assert( mxSafeFrame==pWal->hdr.mxFrame );
50088 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
50089 if( rc==SQLITE_OK ){
50090 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
50095 walcheckpoint_out:
50096 walIteratorFree(pIter);
50097 return rc;
50101 ** If the WAL file is currently larger than nMax bytes in size, truncate
50102 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
50104 static void walLimitSize(Wal *pWal, i64 nMax){
50105 i64 sz;
50106 int rx;
50107 sqlite3BeginBenignMalloc();
50108 rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
50109 if( rx==SQLITE_OK && (sz > nMax ) ){
50110 rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
50112 sqlite3EndBenignMalloc();
50113 if( rx ){
50114 sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
50119 ** Close a connection to a log file.
50121 SQLITE_PRIVATE int sqlite3WalClose(
50122 Wal *pWal, /* Wal to close */
50123 int sync_flags, /* Flags to pass to OsSync() (or 0) */
50124 int nBuf,
50125 u8 *zBuf /* Buffer of at least nBuf bytes */
50127 int rc = SQLITE_OK;
50128 if( pWal ){
50129 int isDelete = 0; /* True to unlink wal and wal-index files */
50131 /* If an EXCLUSIVE lock can be obtained on the database file (using the
50132 ** ordinary, rollback-mode locking methods, this guarantees that the
50133 ** connection associated with this log file is the only connection to
50134 ** the database. In this case checkpoint the database and unlink both
50135 ** the wal and wal-index files.
50137 ** The EXCLUSIVE lock is not released before returning.
50139 rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
50140 if( rc==SQLITE_OK ){
50141 if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
50142 pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
50144 rc = sqlite3WalCheckpoint(
50145 pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
50147 if( rc==SQLITE_OK ){
50148 int bPersist = -1;
50149 sqlite3OsFileControlHint(
50150 pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
50152 if( bPersist!=1 ){
50153 /* Try to delete the WAL file if the checkpoint completed and
50154 ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
50155 ** mode (!bPersist) */
50156 isDelete = 1;
50157 }else if( pWal->mxWalSize>=0 ){
50158 /* Try to truncate the WAL file to zero bytes if the checkpoint
50159 ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
50160 ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
50161 ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
50162 ** to zero bytes as truncating to the journal_size_limit might
50163 ** leave a corrupt WAL file on disk. */
50164 walLimitSize(pWal, 0);
50169 walIndexClose(pWal, isDelete);
50170 sqlite3OsClose(pWal->pWalFd);
50171 if( isDelete ){
50172 sqlite3BeginBenignMalloc();
50173 sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
50174 sqlite3EndBenignMalloc();
50176 WALTRACE(("WAL%p: closed\n", pWal));
50177 sqlite3_free((void *)pWal->apWiData);
50178 sqlite3_free(pWal);
50180 return rc;
50184 ** Try to read the wal-index header. Return 0 on success and 1 if
50185 ** there is a problem.
50187 ** The wal-index is in shared memory. Another thread or process might
50188 ** be writing the header at the same time this procedure is trying to
50189 ** read it, which might result in inconsistency. A dirty read is detected
50190 ** by verifying that both copies of the header are the same and also by
50191 ** a checksum on the header.
50193 ** If and only if the read is consistent and the header is different from
50194 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
50195 ** and *pChanged is set to 1.
50197 ** If the checksum cannot be verified return non-zero. If the header
50198 ** is read successfully and the checksum verified, return zero.
50200 static int walIndexTryHdr(Wal *pWal, int *pChanged){
50201 u32 aCksum[2]; /* Checksum on the header content */
50202 WalIndexHdr h1, h2; /* Two copies of the header content */
50203 WalIndexHdr volatile *aHdr; /* Header in shared memory */
50205 /* The first page of the wal-index must be mapped at this point. */
50206 assert( pWal->nWiData>0 && pWal->apWiData[0] );
50208 /* Read the header. This might happen concurrently with a write to the
50209 ** same area of shared memory on a different CPU in a SMP,
50210 ** meaning it is possible that an inconsistent snapshot is read
50211 ** from the file. If this happens, return non-zero.
50213 ** There are two copies of the header at the beginning of the wal-index.
50214 ** When reading, read [0] first then [1]. Writes are in the reverse order.
50215 ** Memory barriers are used to prevent the compiler or the hardware from
50216 ** reordering the reads and writes.
50218 aHdr = walIndexHdr(pWal);
50219 memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
50220 walShmBarrier(pWal);
50221 memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
50223 if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
50224 return 1; /* Dirty read */
50226 if( h1.isInit==0 ){
50227 return 1; /* Malformed header - probably all zeros */
50229 walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
50230 if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
50231 return 1; /* Checksum does not match */
50234 if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
50235 *pChanged = 1;
50236 memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
50237 pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
50238 testcase( pWal->szPage<=32768 );
50239 testcase( pWal->szPage>=65536 );
50242 /* The header was successfully read. Return zero. */
50243 return 0;
50247 ** Read the wal-index header from the wal-index and into pWal->hdr.
50248 ** If the wal-header appears to be corrupt, try to reconstruct the
50249 ** wal-index from the WAL before returning.
50251 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
50252 ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
50253 ** to 0.
50255 ** If the wal-index header is successfully read, return SQLITE_OK.
50256 ** Otherwise an SQLite error code.
50258 static int walIndexReadHdr(Wal *pWal, int *pChanged){
50259 int rc; /* Return code */
50260 int badHdr; /* True if a header read failed */
50261 volatile u32 *page0; /* Chunk of wal-index containing header */
50263 /* Ensure that page 0 of the wal-index (the page that contains the
50264 ** wal-index header) is mapped. Return early if an error occurs here.
50266 assert( pChanged );
50267 rc = walIndexPage(pWal, 0, &page0);
50268 if( rc!=SQLITE_OK ){
50269 return rc;
50271 assert( page0 || pWal->writeLock==0 );
50273 /* If the first page of the wal-index has been mapped, try to read the
50274 ** wal-index header immediately, without holding any lock. This usually
50275 ** works, but may fail if the wal-index header is corrupt or currently
50276 ** being modified by another thread or process.
50278 badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
50280 /* If the first attempt failed, it might have been due to a race
50281 ** with a writer. So get a WRITE lock and try again.
50283 assert( badHdr==0 || pWal->writeLock==0 );
50284 if( badHdr ){
50285 if( pWal->readOnly & WAL_SHM_RDONLY ){
50286 if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
50287 walUnlockShared(pWal, WAL_WRITE_LOCK);
50288 rc = SQLITE_READONLY_RECOVERY;
50290 }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
50291 pWal->writeLock = 1;
50292 if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
50293 badHdr = walIndexTryHdr(pWal, pChanged);
50294 if( badHdr ){
50295 /* If the wal-index header is still malformed even while holding
50296 ** a WRITE lock, it can only mean that the header is corrupted and
50297 ** needs to be reconstructed. So run recovery to do exactly that.
50299 rc = walIndexRecover(pWal);
50300 *pChanged = 1;
50303 pWal->writeLock = 0;
50304 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
50308 /* If the header is read successfully, check the version number to make
50309 ** sure the wal-index was not constructed with some future format that
50310 ** this version of SQLite cannot understand.
50312 if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
50313 rc = SQLITE_CANTOPEN_BKPT;
50316 return rc;
50320 ** This is the value that walTryBeginRead returns when it needs to
50321 ** be retried.
50323 #define WAL_RETRY (-1)
50326 ** Attempt to start a read transaction. This might fail due to a race or
50327 ** other transient condition. When that happens, it returns WAL_RETRY to
50328 ** indicate to the caller that it is safe to retry immediately.
50330 ** On success return SQLITE_OK. On a permanent failure (such an
50331 ** I/O error or an SQLITE_BUSY because another process is running
50332 ** recovery) return a positive error code.
50334 ** The useWal parameter is true to force the use of the WAL and disable
50335 ** the case where the WAL is bypassed because it has been completely
50336 ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
50337 ** to make a copy of the wal-index header into pWal->hdr. If the
50338 ** wal-index header has changed, *pChanged is set to 1 (as an indication
50339 ** to the caller that the local paget cache is obsolete and needs to be
50340 ** flushed.) When useWal==1, the wal-index header is assumed to already
50341 ** be loaded and the pChanged parameter is unused.
50343 ** The caller must set the cnt parameter to the number of prior calls to
50344 ** this routine during the current read attempt that returned WAL_RETRY.
50345 ** This routine will start taking more aggressive measures to clear the
50346 ** race conditions after multiple WAL_RETRY returns, and after an excessive
50347 ** number of errors will ultimately return SQLITE_PROTOCOL. The
50348 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
50349 ** and is not honoring the locking protocol. There is a vanishingly small
50350 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
50351 ** bad luck when there is lots of contention for the wal-index, but that
50352 ** possibility is so small that it can be safely neglected, we believe.
50354 ** On success, this routine obtains a read lock on
50355 ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
50356 ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
50357 ** that means the Wal does not hold any read lock. The reader must not
50358 ** access any database page that is modified by a WAL frame up to and
50359 ** including frame number aReadMark[pWal->readLock]. The reader will
50360 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
50361 ** Or if pWal->readLock==0, then the reader will ignore the WAL
50362 ** completely and get all content directly from the database file.
50363 ** If the useWal parameter is 1 then the WAL will never be ignored and
50364 ** this routine will always set pWal->readLock>0 on success.
50365 ** When the read transaction is completed, the caller must release the
50366 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
50368 ** This routine uses the nBackfill and aReadMark[] fields of the header
50369 ** to select a particular WAL_READ_LOCK() that strives to let the
50370 ** checkpoint process do as much work as possible. This routine might
50371 ** update values of the aReadMark[] array in the header, but if it does
50372 ** so it takes care to hold an exclusive lock on the corresponding
50373 ** WAL_READ_LOCK() while changing values.
50375 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
50376 volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
50377 u32 mxReadMark; /* Largest aReadMark[] value */
50378 int mxI; /* Index of largest aReadMark[] value */
50379 int i; /* Loop counter */
50380 int rc = SQLITE_OK; /* Return code */
50382 assert( pWal->readLock<0 ); /* Not currently locked */
50384 /* Take steps to avoid spinning forever if there is a protocol error.
50386 ** Circumstances that cause a RETRY should only last for the briefest
50387 ** instances of time. No I/O or other system calls are done while the
50388 ** locks are held, so the locks should not be held for very long. But
50389 ** if we are unlucky, another process that is holding a lock might get
50390 ** paged out or take a page-fault that is time-consuming to resolve,
50391 ** during the few nanoseconds that it is holding the lock. In that case,
50392 ** it might take longer than normal for the lock to free.
50394 ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
50395 ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
50396 ** is more of a scheduler yield than an actual delay. But on the 10th
50397 ** an subsequent retries, the delays start becoming longer and longer,
50398 ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
50399 ** The total delay time before giving up is less than 10 seconds.
50401 if( cnt>5 ){
50402 int nDelay = 1; /* Pause time in microseconds */
50403 if( cnt>100 ){
50404 VVA_ONLY( pWal->lockError = 1; )
50405 return SQLITE_PROTOCOL;
50407 if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
50408 sqlite3OsSleep(pWal->pVfs, nDelay);
50411 if( !useWal ){
50412 rc = walIndexReadHdr(pWal, pChanged);
50413 if( rc==SQLITE_BUSY ){
50414 /* If there is not a recovery running in another thread or process
50415 ** then convert BUSY errors to WAL_RETRY. If recovery is known to
50416 ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
50417 ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
50418 ** would be technically correct. But the race is benign since with
50419 ** WAL_RETRY this routine will be called again and will probably be
50420 ** right on the second iteration.
50422 if( pWal->apWiData[0]==0 ){
50423 /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
50424 ** We assume this is a transient condition, so return WAL_RETRY. The
50425 ** xShmMap() implementation used by the default unix and win32 VFS
50426 ** modules may return SQLITE_BUSY due to a race condition in the
50427 ** code that determines whether or not the shared-memory region
50428 ** must be zeroed before the requested page is returned.
50430 rc = WAL_RETRY;
50431 }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
50432 walUnlockShared(pWal, WAL_RECOVER_LOCK);
50433 rc = WAL_RETRY;
50434 }else if( rc==SQLITE_BUSY ){
50435 rc = SQLITE_BUSY_RECOVERY;
50438 if( rc!=SQLITE_OK ){
50439 return rc;
50443 pInfo = walCkptInfo(pWal);
50444 if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
50445 /* The WAL has been completely backfilled (or it is empty).
50446 ** and can be safely ignored.
50448 rc = walLockShared(pWal, WAL_READ_LOCK(0));
50449 walShmBarrier(pWal);
50450 if( rc==SQLITE_OK ){
50451 if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
50452 /* It is not safe to allow the reader to continue here if frames
50453 ** may have been appended to the log before READ_LOCK(0) was obtained.
50454 ** When holding READ_LOCK(0), the reader ignores the entire log file,
50455 ** which implies that the database file contains a trustworthy
50456 ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
50457 ** happening, this is usually correct.
50459 ** However, if frames have been appended to the log (or if the log
50460 ** is wrapped and written for that matter) before the READ_LOCK(0)
50461 ** is obtained, that is not necessarily true. A checkpointer may
50462 ** have started to backfill the appended frames but crashed before
50463 ** it finished. Leaving a corrupt image in the database file.
50465 walUnlockShared(pWal, WAL_READ_LOCK(0));
50466 return WAL_RETRY;
50468 pWal->readLock = 0;
50469 return SQLITE_OK;
50470 }else if( rc!=SQLITE_BUSY ){
50471 return rc;
50475 /* If we get this far, it means that the reader will want to use
50476 ** the WAL to get at content from recent commits. The job now is
50477 ** to select one of the aReadMark[] entries that is closest to
50478 ** but not exceeding pWal->hdr.mxFrame and lock that entry.
50480 mxReadMark = 0;
50481 mxI = 0;
50482 for(i=1; i<WAL_NREADER; i++){
50483 u32 thisMark = pInfo->aReadMark[i];
50484 if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
50485 assert( thisMark!=READMARK_NOT_USED );
50486 mxReadMark = thisMark;
50487 mxI = i;
50490 /* There was once an "if" here. The extra "{" is to preserve indentation. */
50492 if( (pWal->readOnly & WAL_SHM_RDONLY)==0
50493 && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
50495 for(i=1; i<WAL_NREADER; i++){
50496 rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
50497 if( rc==SQLITE_OK ){
50498 mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
50499 mxI = i;
50500 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
50501 break;
50502 }else if( rc!=SQLITE_BUSY ){
50503 return rc;
50507 if( mxI==0 ){
50508 assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
50509 return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
50512 rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
50513 if( rc ){
50514 return rc==SQLITE_BUSY ? WAL_RETRY : rc;
50516 /* Now that the read-lock has been obtained, check that neither the
50517 ** value in the aReadMark[] array or the contents of the wal-index
50518 ** header have changed.
50520 ** It is necessary to check that the wal-index header did not change
50521 ** between the time it was read and when the shared-lock was obtained
50522 ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
50523 ** that the log file may have been wrapped by a writer, or that frames
50524 ** that occur later in the log than pWal->hdr.mxFrame may have been
50525 ** copied into the database by a checkpointer. If either of these things
50526 ** happened, then reading the database with the current value of
50527 ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
50528 ** instead.
50530 ** This does not guarantee that the copy of the wal-index header is up to
50531 ** date before proceeding. That would not be possible without somehow
50532 ** blocking writers. It only guarantees that a dangerous checkpoint or
50533 ** log-wrap (either of which would require an exclusive lock on
50534 ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
50536 walShmBarrier(pWal);
50537 if( pInfo->aReadMark[mxI]!=mxReadMark
50538 || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
50540 walUnlockShared(pWal, WAL_READ_LOCK(mxI));
50541 return WAL_RETRY;
50542 }else{
50543 assert( mxReadMark<=pWal->hdr.mxFrame );
50544 pWal->readLock = (i16)mxI;
50547 return rc;
50551 ** Begin a read transaction on the database.
50553 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
50554 ** it takes a snapshot of the state of the WAL and wal-index for the current
50555 ** instant in time. The current thread will continue to use this snapshot.
50556 ** Other threads might append new content to the WAL and wal-index but
50557 ** that extra content is ignored by the current thread.
50559 ** If the database contents have changes since the previous read
50560 ** transaction, then *pChanged is set to 1 before returning. The
50561 ** Pager layer will use this to know that is cache is stale and
50562 ** needs to be flushed.
50564 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
50565 int rc; /* Return code */
50566 int cnt = 0; /* Number of TryBeginRead attempts */
50569 rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
50570 }while( rc==WAL_RETRY );
50571 testcase( (rc&0xff)==SQLITE_BUSY );
50572 testcase( (rc&0xff)==SQLITE_IOERR );
50573 testcase( rc==SQLITE_PROTOCOL );
50574 testcase( rc==SQLITE_OK );
50575 return rc;
50579 ** Finish with a read transaction. All this does is release the
50580 ** read-lock.
50582 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
50583 sqlite3WalEndWriteTransaction(pWal);
50584 if( pWal->readLock>=0 ){
50585 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
50586 pWal->readLock = -1;
50591 ** Search the wal file for page pgno. If found, set *piRead to the frame that
50592 ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
50593 ** to zero.
50595 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
50596 ** error does occur, the final value of *piRead is undefined.
50598 SQLITE_PRIVATE int sqlite3WalFindFrame(
50599 Wal *pWal, /* WAL handle */
50600 Pgno pgno, /* Database page number to read data for */
50601 u32 *piRead /* OUT: Frame number (or zero) */
50603 u32 iRead = 0; /* If !=0, WAL frame to return data from */
50604 u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
50605 int iHash; /* Used to loop through N hash tables */
50607 /* This routine is only be called from within a read transaction. */
50608 assert( pWal->readLock>=0 || pWal->lockError );
50610 /* If the "last page" field of the wal-index header snapshot is 0, then
50611 ** no data will be read from the wal under any circumstances. Return early
50612 ** in this case as an optimization. Likewise, if pWal->readLock==0,
50613 ** then the WAL is ignored by the reader so return early, as if the
50614 ** WAL were empty.
50616 if( iLast==0 || pWal->readLock==0 ){
50617 *piRead = 0;
50618 return SQLITE_OK;
50621 /* Search the hash table or tables for an entry matching page number
50622 ** pgno. Each iteration of the following for() loop searches one
50623 ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
50625 ** This code might run concurrently to the code in walIndexAppend()
50626 ** that adds entries to the wal-index (and possibly to this hash
50627 ** table). This means the value just read from the hash
50628 ** slot (aHash[iKey]) may have been added before or after the
50629 ** current read transaction was opened. Values added after the
50630 ** read transaction was opened may have been written incorrectly -
50631 ** i.e. these slots may contain garbage data. However, we assume
50632 ** that any slots written before the current read transaction was
50633 ** opened remain unmodified.
50635 ** For the reasons above, the if(...) condition featured in the inner
50636 ** loop of the following block is more stringent that would be required
50637 ** if we had exclusive access to the hash-table:
50639 ** (aPgno[iFrame]==pgno):
50640 ** This condition filters out normal hash-table collisions.
50642 ** (iFrame<=iLast):
50643 ** This condition filters out entries that were added to the hash
50644 ** table after the current read-transaction had started.
50646 for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
50647 volatile ht_slot *aHash; /* Pointer to hash table */
50648 volatile u32 *aPgno; /* Pointer to array of page numbers */
50649 u32 iZero; /* Frame number corresponding to aPgno[0] */
50650 int iKey; /* Hash slot index */
50651 int nCollide; /* Number of hash collisions remaining */
50652 int rc; /* Error code */
50654 rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
50655 if( rc!=SQLITE_OK ){
50656 return rc;
50658 nCollide = HASHTABLE_NSLOT;
50659 for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
50660 u32 iFrame = aHash[iKey] + iZero;
50661 if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
50662 /* assert( iFrame>iRead ); -- not true if there is corruption */
50663 iRead = iFrame;
50665 if( (nCollide--)==0 ){
50666 return SQLITE_CORRUPT_BKPT;
50671 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
50672 /* If expensive assert() statements are available, do a linear search
50673 ** of the wal-index file content. Make sure the results agree with the
50674 ** result obtained using the hash indexes above. */
50676 u32 iRead2 = 0;
50677 u32 iTest;
50678 for(iTest=iLast; iTest>0; iTest--){
50679 if( walFramePgno(pWal, iTest)==pgno ){
50680 iRead2 = iTest;
50681 break;
50684 assert( iRead==iRead2 );
50686 #endif
50688 *piRead = iRead;
50689 return SQLITE_OK;
50693 ** Read the contents of frame iRead from the wal file into buffer pOut
50694 ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
50695 ** error code otherwise.
50697 SQLITE_PRIVATE int sqlite3WalReadFrame(
50698 Wal *pWal, /* WAL handle */
50699 u32 iRead, /* Frame to read */
50700 int nOut, /* Size of buffer pOut in bytes */
50701 u8 *pOut /* Buffer to write page data to */
50703 int sz;
50704 i64 iOffset;
50705 sz = pWal->hdr.szPage;
50706 sz = (sz&0xfe00) + ((sz&0x0001)<<16);
50707 testcase( sz<=32768 );
50708 testcase( sz>=65536 );
50709 iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
50710 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
50711 return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
50715 ** Return the size of the database in pages (or zero, if unknown).
50717 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
50718 if( pWal && ALWAYS(pWal->readLock>=0) ){
50719 return pWal->hdr.nPage;
50721 return 0;
50726 ** This function starts a write transaction on the WAL.
50728 ** A read transaction must have already been started by a prior call
50729 ** to sqlite3WalBeginReadTransaction().
50731 ** If another thread or process has written into the database since
50732 ** the read transaction was started, then it is not possible for this
50733 ** thread to write as doing so would cause a fork. So this routine
50734 ** returns SQLITE_BUSY in that case and no write transaction is started.
50736 ** There can only be a single writer active at a time.
50738 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
50739 int rc;
50741 /* Cannot start a write transaction without first holding a read
50742 ** transaction. */
50743 assert( pWal->readLock>=0 );
50745 if( pWal->readOnly ){
50746 return SQLITE_READONLY;
50749 /* Only one writer allowed at a time. Get the write lock. Return
50750 ** SQLITE_BUSY if unable.
50752 rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
50753 if( rc ){
50754 return rc;
50756 pWal->writeLock = 1;
50758 /* If another connection has written to the database file since the
50759 ** time the read transaction on this connection was started, then
50760 ** the write is disallowed.
50762 if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
50763 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
50764 pWal->writeLock = 0;
50765 rc = SQLITE_BUSY_SNAPSHOT;
50768 return rc;
50772 ** End a write transaction. The commit has already been done. This
50773 ** routine merely releases the lock.
50775 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
50776 if( pWal->writeLock ){
50777 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
50778 pWal->writeLock = 0;
50779 pWal->truncateOnCommit = 0;
50781 return SQLITE_OK;
50785 ** If any data has been written (but not committed) to the log file, this
50786 ** function moves the write-pointer back to the start of the transaction.
50788 ** Additionally, the callback function is invoked for each frame written
50789 ** to the WAL since the start of the transaction. If the callback returns
50790 ** other than SQLITE_OK, it is not invoked again and the error code is
50791 ** returned to the caller.
50793 ** Otherwise, if the callback function does not return an error, this
50794 ** function returns SQLITE_OK.
50796 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
50797 int rc = SQLITE_OK;
50798 if( ALWAYS(pWal->writeLock) ){
50799 Pgno iMax = pWal->hdr.mxFrame;
50800 Pgno iFrame;
50802 /* Restore the clients cache of the wal-index header to the state it
50803 ** was in before the client began writing to the database.
50805 memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
50807 for(iFrame=pWal->hdr.mxFrame+1;
50808 ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
50809 iFrame++
50811 /* This call cannot fail. Unless the page for which the page number
50812 ** is passed as the second argument is (a) in the cache and
50813 ** (b) has an outstanding reference, then xUndo is either a no-op
50814 ** (if (a) is false) or simply expels the page from the cache (if (b)
50815 ** is false).
50817 ** If the upper layer is doing a rollback, it is guaranteed that there
50818 ** are no outstanding references to any page other than page 1. And
50819 ** page 1 is never written to the log until the transaction is
50820 ** committed. As a result, the call to xUndo may not fail.
50822 assert( walFramePgno(pWal, iFrame)!=1 );
50823 rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
50825 if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
50827 return rc;
50831 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
50832 ** values. This function populates the array with values required to
50833 ** "rollback" the write position of the WAL handle back to the current
50834 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
50836 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
50837 assert( pWal->writeLock );
50838 aWalData[0] = pWal->hdr.mxFrame;
50839 aWalData[1] = pWal->hdr.aFrameCksum[0];
50840 aWalData[2] = pWal->hdr.aFrameCksum[1];
50841 aWalData[3] = pWal->nCkpt;
50845 ** Move the write position of the WAL back to the point identified by
50846 ** the values in the aWalData[] array. aWalData must point to an array
50847 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
50848 ** by a call to WalSavepoint().
50850 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
50851 int rc = SQLITE_OK;
50853 assert( pWal->writeLock );
50854 assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
50856 if( aWalData[3]!=pWal->nCkpt ){
50857 /* This savepoint was opened immediately after the write-transaction
50858 ** was started. Right after that, the writer decided to wrap around
50859 ** to the start of the log. Update the savepoint values to match.
50861 aWalData[0] = 0;
50862 aWalData[3] = pWal->nCkpt;
50865 if( aWalData[0]<pWal->hdr.mxFrame ){
50866 pWal->hdr.mxFrame = aWalData[0];
50867 pWal->hdr.aFrameCksum[0] = aWalData[1];
50868 pWal->hdr.aFrameCksum[1] = aWalData[2];
50869 walCleanupHash(pWal);
50872 return rc;
50877 ** This function is called just before writing a set of frames to the log
50878 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
50879 ** to the current log file, it is possible to overwrite the start of the
50880 ** existing log file with the new frames (i.e. "reset" the log). If so,
50881 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
50882 ** unchanged.
50884 ** SQLITE_OK is returned if no error is encountered (regardless of whether
50885 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
50886 ** if an error occurs.
50888 static int walRestartLog(Wal *pWal){
50889 int rc = SQLITE_OK;
50890 int cnt;
50892 if( pWal->readLock==0 ){
50893 volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
50894 assert( pInfo->nBackfill==pWal->hdr.mxFrame );
50895 if( pInfo->nBackfill>0 ){
50896 u32 salt1;
50897 sqlite3_randomness(4, &salt1);
50898 rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
50899 if( rc==SQLITE_OK ){
50900 /* If all readers are using WAL_READ_LOCK(0) (in other words if no
50901 ** readers are currently using the WAL), then the transactions
50902 ** frames will overwrite the start of the existing log. Update the
50903 ** wal-index header to reflect this.
50905 ** In theory it would be Ok to update the cache of the header only
50906 ** at this point. But updating the actual wal-index header is also
50907 ** safe and means there is no special case for sqlite3WalUndo()
50908 ** to handle if this transaction is rolled back.
50910 int i; /* Loop counter */
50911 u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
50913 pWal->nCkpt++;
50914 pWal->hdr.mxFrame = 0;
50915 sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
50916 aSalt[1] = salt1;
50917 walIndexWriteHdr(pWal);
50918 pInfo->nBackfill = 0;
50919 pInfo->aReadMark[1] = 0;
50920 for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
50921 assert( pInfo->aReadMark[0]==0 );
50922 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
50923 }else if( rc!=SQLITE_BUSY ){
50924 return rc;
50927 walUnlockShared(pWal, WAL_READ_LOCK(0));
50928 pWal->readLock = -1;
50929 cnt = 0;
50931 int notUsed;
50932 rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
50933 }while( rc==WAL_RETRY );
50934 assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
50935 testcase( (rc&0xff)==SQLITE_IOERR );
50936 testcase( rc==SQLITE_PROTOCOL );
50937 testcase( rc==SQLITE_OK );
50939 return rc;
50943 ** Information about the current state of the WAL file and where
50944 ** the next fsync should occur - passed from sqlite3WalFrames() into
50945 ** walWriteToLog().
50947 typedef struct WalWriter {
50948 Wal *pWal; /* The complete WAL information */
50949 sqlite3_file *pFd; /* The WAL file to which we write */
50950 sqlite3_int64 iSyncPoint; /* Fsync at this offset */
50951 int syncFlags; /* Flags for the fsync */
50952 int szPage; /* Size of one page */
50953 } WalWriter;
50956 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
50957 ** Do a sync when crossing the p->iSyncPoint boundary.
50959 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
50960 ** first write the part before iSyncPoint, then sync, then write the
50961 ** rest.
50963 static int walWriteToLog(
50964 WalWriter *p, /* WAL to write to */
50965 void *pContent, /* Content to be written */
50966 int iAmt, /* Number of bytes to write */
50967 sqlite3_int64 iOffset /* Start writing at this offset */
50969 int rc;
50970 if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
50971 int iFirstAmt = (int)(p->iSyncPoint - iOffset);
50972 rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
50973 if( rc ) return rc;
50974 iOffset += iFirstAmt;
50975 iAmt -= iFirstAmt;
50976 pContent = (void*)(iFirstAmt + (char*)pContent);
50977 assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
50978 rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
50979 if( iAmt==0 || rc ) return rc;
50981 rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
50982 return rc;
50986 ** Write out a single frame of the WAL
50988 static int walWriteOneFrame(
50989 WalWriter *p, /* Where to write the frame */
50990 PgHdr *pPage, /* The page of the frame to be written */
50991 int nTruncate, /* The commit flag. Usually 0. >0 for commit */
50992 sqlite3_int64 iOffset /* Byte offset at which to write */
50994 int rc; /* Result code from subfunctions */
50995 void *pData; /* Data actually written */
50996 u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
50997 #if defined(SQLITE_HAS_CODEC)
50998 if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
50999 #else
51000 pData = pPage->pData;
51001 #endif
51002 walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
51003 rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
51004 if( rc ) return rc;
51005 /* Write the page data */
51006 rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
51007 return rc;
51011 ** Write a set of frames to the log. The caller must hold the write-lock
51012 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
51014 SQLITE_PRIVATE int sqlite3WalFrames(
51015 Wal *pWal, /* Wal handle to write to */
51016 int szPage, /* Database page-size in bytes */
51017 PgHdr *pList, /* List of dirty pages to write */
51018 Pgno nTruncate, /* Database size after this commit */
51019 int isCommit, /* True if this is a commit */
51020 int sync_flags /* Flags to pass to OsSync() (or 0) */
51022 int rc; /* Used to catch return codes */
51023 u32 iFrame; /* Next frame address */
51024 PgHdr *p; /* Iterator to run through pList with. */
51025 PgHdr *pLast = 0; /* Last frame in list */
51026 int nExtra = 0; /* Number of extra copies of last page */
51027 int szFrame; /* The size of a single frame */
51028 i64 iOffset; /* Next byte to write in WAL file */
51029 WalWriter w; /* The writer */
51031 assert( pList );
51032 assert( pWal->writeLock );
51034 /* If this frame set completes a transaction, then nTruncate>0. If
51035 ** nTruncate==0 then this frame set does not complete the transaction. */
51036 assert( (isCommit!=0)==(nTruncate!=0) );
51038 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
51039 { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
51040 WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
51041 pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
51043 #endif
51045 /* See if it is possible to write these frames into the start of the
51046 ** log file, instead of appending to it at pWal->hdr.mxFrame.
51048 if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
51049 return rc;
51052 /* If this is the first frame written into the log, write the WAL
51053 ** header to the start of the WAL file. See comments at the top of
51054 ** this source file for a description of the WAL header format.
51056 iFrame = pWal->hdr.mxFrame;
51057 if( iFrame==0 ){
51058 u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
51059 u32 aCksum[2]; /* Checksum for wal-header */
51061 sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
51062 sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
51063 sqlite3Put4byte(&aWalHdr[8], szPage);
51064 sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
51065 if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
51066 memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
51067 walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
51068 sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
51069 sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
51071 pWal->szPage = szPage;
51072 pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
51073 pWal->hdr.aFrameCksum[0] = aCksum[0];
51074 pWal->hdr.aFrameCksum[1] = aCksum[1];
51075 pWal->truncateOnCommit = 1;
51077 rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
51078 WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
51079 if( rc!=SQLITE_OK ){
51080 return rc;
51083 /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
51084 ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
51085 ** an out-of-order write following a WAL restart could result in
51086 ** database corruption. See the ticket:
51088 ** http://localhost:591/sqlite/info/ff5be73dee
51090 if( pWal->syncHeader && sync_flags ){
51091 rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
51092 if( rc ) return rc;
51095 assert( (int)pWal->szPage==szPage );
51097 /* Setup information needed to write frames into the WAL */
51098 w.pWal = pWal;
51099 w.pFd = pWal->pWalFd;
51100 w.iSyncPoint = 0;
51101 w.syncFlags = sync_flags;
51102 w.szPage = szPage;
51103 iOffset = walFrameOffset(iFrame+1, szPage);
51104 szFrame = szPage + WAL_FRAME_HDRSIZE;
51106 /* Write all frames into the log file exactly once */
51107 for(p=pList; p; p=p->pDirty){
51108 int nDbSize; /* 0 normally. Positive == commit flag */
51109 iFrame++;
51110 assert( iOffset==walFrameOffset(iFrame, szPage) );
51111 nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
51112 rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
51113 if( rc ) return rc;
51114 pLast = p;
51115 iOffset += szFrame;
51118 /* If this is the end of a transaction, then we might need to pad
51119 ** the transaction and/or sync the WAL file.
51121 ** Padding and syncing only occur if this set of frames complete a
51122 ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
51123 ** or synchronous==OFF, then no padding or syncing are needed.
51125 ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
51126 ** needed and only the sync is done. If padding is needed, then the
51127 ** final frame is repeated (with its commit mark) until the next sector
51128 ** boundary is crossed. Only the part of the WAL prior to the last
51129 ** sector boundary is synced; the part of the last frame that extends
51130 ** past the sector boundary is written after the sync.
51132 if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
51133 if( pWal->padToSectorBoundary ){
51134 int sectorSize = sqlite3SectorSize(pWal->pWalFd);
51135 w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
51136 while( iOffset<w.iSyncPoint ){
51137 rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
51138 if( rc ) return rc;
51139 iOffset += szFrame;
51140 nExtra++;
51142 }else{
51143 rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
51147 /* If this frame set completes the first transaction in the WAL and
51148 ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
51149 ** journal size limit, if possible.
51151 if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
51152 i64 sz = pWal->mxWalSize;
51153 if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
51154 sz = walFrameOffset(iFrame+nExtra+1, szPage);
51156 walLimitSize(pWal, sz);
51157 pWal->truncateOnCommit = 0;
51160 /* Append data to the wal-index. It is not necessary to lock the
51161 ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
51162 ** guarantees that there are no other writers, and no data that may
51163 ** be in use by existing readers is being overwritten.
51165 iFrame = pWal->hdr.mxFrame;
51166 for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
51167 iFrame++;
51168 rc = walIndexAppend(pWal, iFrame, p->pgno);
51170 while( rc==SQLITE_OK && nExtra>0 ){
51171 iFrame++;
51172 nExtra--;
51173 rc = walIndexAppend(pWal, iFrame, pLast->pgno);
51176 if( rc==SQLITE_OK ){
51177 /* Update the private copy of the header. */
51178 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
51179 testcase( szPage<=32768 );
51180 testcase( szPage>=65536 );
51181 pWal->hdr.mxFrame = iFrame;
51182 if( isCommit ){
51183 pWal->hdr.iChange++;
51184 pWal->hdr.nPage = nTruncate;
51186 /* If this is a commit, update the wal-index header too. */
51187 if( isCommit ){
51188 walIndexWriteHdr(pWal);
51189 pWal->iCallback = iFrame;
51193 WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
51194 return rc;
51198 ** This routine is called to implement sqlite3_wal_checkpoint() and
51199 ** related interfaces.
51201 ** Obtain a CHECKPOINT lock and then backfill as much information as
51202 ** we can from WAL into the database.
51204 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
51205 ** callback. In this case this function runs a blocking checkpoint.
51207 SQLITE_PRIVATE int sqlite3WalCheckpoint(
51208 Wal *pWal, /* Wal connection */
51209 int eMode, /* PASSIVE, FULL or RESTART */
51210 int (*xBusy)(void*), /* Function to call when busy */
51211 void *pBusyArg, /* Context argument for xBusyHandler */
51212 int sync_flags, /* Flags to sync db file with (or 0) */
51213 int nBuf, /* Size of temporary buffer */
51214 u8 *zBuf, /* Temporary buffer to use */
51215 int *pnLog, /* OUT: Number of frames in WAL */
51216 int *pnCkpt /* OUT: Number of backfilled frames in WAL */
51218 int rc; /* Return code */
51219 int isChanged = 0; /* True if a new wal-index header is loaded */
51220 int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
51222 assert( pWal->ckptLock==0 );
51223 assert( pWal->writeLock==0 );
51225 if( pWal->readOnly ) return SQLITE_READONLY;
51226 WALTRACE(("WAL%p: checkpoint begins\n", pWal));
51227 rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
51228 if( rc ){
51229 /* Usually this is SQLITE_BUSY meaning that another thread or process
51230 ** is already running a checkpoint, or maybe a recovery. But it might
51231 ** also be SQLITE_IOERR. */
51232 return rc;
51234 pWal->ckptLock = 1;
51236 /* If this is a blocking-checkpoint, then obtain the write-lock as well
51237 ** to prevent any writers from running while the checkpoint is underway.
51238 ** This has to be done before the call to walIndexReadHdr() below.
51240 ** If the writer lock cannot be obtained, then a passive checkpoint is
51241 ** run instead. Since the checkpointer is not holding the writer lock,
51242 ** there is no point in blocking waiting for any readers. Assuming no
51243 ** other error occurs, this function will return SQLITE_BUSY to the caller.
51245 if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
51246 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
51247 if( rc==SQLITE_OK ){
51248 pWal->writeLock = 1;
51249 }else if( rc==SQLITE_BUSY ){
51250 eMode2 = SQLITE_CHECKPOINT_PASSIVE;
51251 rc = SQLITE_OK;
51255 /* Read the wal-index header. */
51256 if( rc==SQLITE_OK ){
51257 rc = walIndexReadHdr(pWal, &isChanged);
51258 if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
51259 sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
51263 /* Copy data from the log to the database file. */
51264 if( rc==SQLITE_OK ){
51265 if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
51266 rc = SQLITE_CORRUPT_BKPT;
51267 }else{
51268 rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
51271 /* If no error occurred, set the output variables. */
51272 if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
51273 if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
51274 if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
51278 if( isChanged ){
51279 /* If a new wal-index header was loaded before the checkpoint was
51280 ** performed, then the pager-cache associated with pWal is now
51281 ** out of date. So zero the cached wal-index header to ensure that
51282 ** next time the pager opens a snapshot on this database it knows that
51283 ** the cache needs to be reset.
51285 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
51288 /* Release the locks. */
51289 sqlite3WalEndWriteTransaction(pWal);
51290 walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
51291 pWal->ckptLock = 0;
51292 WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
51293 return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
51296 /* Return the value to pass to a sqlite3_wal_hook callback, the
51297 ** number of frames in the WAL at the point of the last commit since
51298 ** sqlite3WalCallback() was called. If no commits have occurred since
51299 ** the last call, then return 0.
51301 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
51302 u32 ret = 0;
51303 if( pWal ){
51304 ret = pWal->iCallback;
51305 pWal->iCallback = 0;
51307 return (int)ret;
51311 ** This function is called to change the WAL subsystem into or out
51312 ** of locking_mode=EXCLUSIVE.
51314 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
51315 ** into locking_mode=NORMAL. This means that we must acquire a lock
51316 ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
51317 ** or if the acquisition of the lock fails, then return 0. If the
51318 ** transition out of exclusive-mode is successful, return 1. This
51319 ** operation must occur while the pager is still holding the exclusive
51320 ** lock on the main database file.
51322 ** If op is one, then change from locking_mode=NORMAL into
51323 ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
51324 ** be released. Return 1 if the transition is made and 0 if the
51325 ** WAL is already in exclusive-locking mode - meaning that this
51326 ** routine is a no-op. The pager must already hold the exclusive lock
51327 ** on the main database file before invoking this operation.
51329 ** If op is negative, then do a dry-run of the op==1 case but do
51330 ** not actually change anything. The pager uses this to see if it
51331 ** should acquire the database exclusive lock prior to invoking
51332 ** the op==1 case.
51334 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
51335 int rc;
51336 assert( pWal->writeLock==0 );
51337 assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
51339 /* pWal->readLock is usually set, but might be -1 if there was a
51340 ** prior error while attempting to acquire are read-lock. This cannot
51341 ** happen if the connection is actually in exclusive mode (as no xShmLock
51342 ** locks are taken in this case). Nor should the pager attempt to
51343 ** upgrade to exclusive-mode following such an error.
51345 assert( pWal->readLock>=0 || pWal->lockError );
51346 assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
51348 if( op==0 ){
51349 if( pWal->exclusiveMode ){
51350 pWal->exclusiveMode = 0;
51351 if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
51352 pWal->exclusiveMode = 1;
51354 rc = pWal->exclusiveMode==0;
51355 }else{
51356 /* Already in locking_mode=NORMAL */
51357 rc = 0;
51359 }else if( op>0 ){
51360 assert( pWal->exclusiveMode==0 );
51361 assert( pWal->readLock>=0 );
51362 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
51363 pWal->exclusiveMode = 1;
51364 rc = 1;
51365 }else{
51366 rc = pWal->exclusiveMode==0;
51368 return rc;
51372 ** Return true if the argument is non-NULL and the WAL module is using
51373 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
51374 ** WAL module is using shared-memory, return false.
51376 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
51377 return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
51380 #ifdef SQLITE_ENABLE_ZIPVFS
51382 ** If the argument is not NULL, it points to a Wal object that holds a
51383 ** read-lock. This function returns the database page-size if it is known,
51384 ** or zero if it is not (or if pWal is NULL).
51386 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
51387 assert( pWal==0 || pWal->readLock>=0 );
51388 return (pWal ? pWal->szPage : 0);
51390 #endif
51392 #endif /* #ifndef SQLITE_OMIT_WAL */
51394 /************** End of wal.c *************************************************/
51395 /************** Begin file btmutex.c *****************************************/
51397 ** 2007 August 27
51399 ** The author disclaims copyright to this source code. In place of
51400 ** a legal notice, here is a blessing:
51402 ** May you do good and not evil.
51403 ** May you find forgiveness for yourself and forgive others.
51404 ** May you share freely, never taking more than you give.
51406 *************************************************************************
51408 ** This file contains code used to implement mutexes on Btree objects.
51409 ** This code really belongs in btree.c. But btree.c is getting too
51410 ** big and we want to break it down some. This packaged seemed like
51411 ** a good breakout.
51413 /************** Include btreeInt.h in the middle of btmutex.c ****************/
51414 /************** Begin file btreeInt.h ****************************************/
51416 ** 2004 April 6
51418 ** The author disclaims copyright to this source code. In place of
51419 ** a legal notice, here is a blessing:
51421 ** May you do good and not evil.
51422 ** May you find forgiveness for yourself and forgive others.
51423 ** May you share freely, never taking more than you give.
51425 *************************************************************************
51426 ** This file implements an external (disk-based) database using BTrees.
51427 ** For a detailed discussion of BTrees, refer to
51429 ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
51430 ** "Sorting And Searching", pages 473-480. Addison-Wesley
51431 ** Publishing Company, Reading, Massachusetts.
51433 ** The basic idea is that each page of the file contains N database
51434 ** entries and N+1 pointers to subpages.
51436 ** ----------------------------------------------------------------
51437 ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
51438 ** ----------------------------------------------------------------
51440 ** All of the keys on the page that Ptr(0) points to have values less
51441 ** than Key(0). All of the keys on page Ptr(1) and its subpages have
51442 ** values greater than Key(0) and less than Key(1). All of the keys
51443 ** on Ptr(N) and its subpages have values greater than Key(N-1). And
51444 ** so forth.
51446 ** Finding a particular key requires reading O(log(M)) pages from the
51447 ** disk where M is the number of entries in the tree.
51449 ** In this implementation, a single file can hold one or more separate
51450 ** BTrees. Each BTree is identified by the index of its root page. The
51451 ** key and data for any entry are combined to form the "payload". A
51452 ** fixed amount of payload can be carried directly on the database
51453 ** page. If the payload is larger than the preset amount then surplus
51454 ** bytes are stored on overflow pages. The payload for an entry
51455 ** and the preceding pointer are combined to form a "Cell". Each
51456 ** page has a small header which contains the Ptr(N) pointer and other
51457 ** information such as the size of key and data.
51459 ** FORMAT DETAILS
51461 ** The file is divided into pages. The first page is called page 1,
51462 ** the second is page 2, and so forth. A page number of zero indicates
51463 ** "no such page". The page size can be any power of 2 between 512 and 65536.
51464 ** Each page can be either a btree page, a freelist page, an overflow
51465 ** page, or a pointer-map page.
51467 ** The first page is always a btree page. The first 100 bytes of the first
51468 ** page contain a special header (the "file header") that describes the file.
51469 ** The format of the file header is as follows:
51471 ** OFFSET SIZE DESCRIPTION
51472 ** 0 16 Header string: "SQLite format 3\000"
51473 ** 16 2 Page size in bytes. (1 means 65536)
51474 ** 18 1 File format write version
51475 ** 19 1 File format read version
51476 ** 20 1 Bytes of unused space at the end of each page
51477 ** 21 1 Max embedded payload fraction (must be 64)
51478 ** 22 1 Min embedded payload fraction (must be 32)
51479 ** 23 1 Min leaf payload fraction (must be 32)
51480 ** 24 4 File change counter
51481 ** 28 4 Reserved for future use
51482 ** 32 4 First freelist page
51483 ** 36 4 Number of freelist pages in the file
51484 ** 40 60 15 4-byte meta values passed to higher layers
51486 ** 40 4 Schema cookie
51487 ** 44 4 File format of schema layer
51488 ** 48 4 Size of page cache
51489 ** 52 4 Largest root-page (auto/incr_vacuum)
51490 ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
51491 ** 60 4 User version
51492 ** 64 4 Incremental vacuum mode
51493 ** 68 4 Application-ID
51494 ** 72 20 unused
51495 ** 92 4 The version-valid-for number
51496 ** 96 4 SQLITE_VERSION_NUMBER
51498 ** All of the integer values are big-endian (most significant byte first).
51500 ** The file change counter is incremented when the database is changed
51501 ** This counter allows other processes to know when the file has changed
51502 ** and thus when they need to flush their cache.
51504 ** The max embedded payload fraction is the amount of the total usable
51505 ** space in a page that can be consumed by a single cell for standard
51506 ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
51507 ** is to limit the maximum cell size so that at least 4 cells will fit
51508 ** on one page. Thus the default max embedded payload fraction is 64.
51510 ** If the payload for a cell is larger than the max payload, then extra
51511 ** payload is spilled to overflow pages. Once an overflow page is allocated,
51512 ** as many bytes as possible are moved into the overflow pages without letting
51513 ** the cell size drop below the min embedded payload fraction.
51515 ** The min leaf payload fraction is like the min embedded payload fraction
51516 ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
51517 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
51518 ** not specified in the header.
51520 ** Each btree pages is divided into three sections: The header, the
51521 ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
51522 ** file header that occurs before the page header.
51524 ** |----------------|
51525 ** | file header | 100 bytes. Page 1 only.
51526 ** |----------------|
51527 ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
51528 ** |----------------|
51529 ** | cell pointer | | 2 bytes per cell. Sorted order.
51530 ** | array | | Grows downward
51531 ** | | v
51532 ** |----------------|
51533 ** | unallocated |
51534 ** | space |
51535 ** |----------------| ^ Grows upwards
51536 ** | cell content | | Arbitrary order interspersed with freeblocks.
51537 ** | area | | and free space fragments.
51538 ** |----------------|
51540 ** The page headers looks like this:
51542 ** OFFSET SIZE DESCRIPTION
51543 ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
51544 ** 1 2 byte offset to the first freeblock
51545 ** 3 2 number of cells on this page
51546 ** 5 2 first byte of the cell content area
51547 ** 7 1 number of fragmented free bytes
51548 ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
51550 ** The flags define the format of this btree page. The leaf flag means that
51551 ** this page has no children. The zerodata flag means that this page carries
51552 ** only keys and no data. The intkey flag means that the key is an integer
51553 ** which is stored in the key size entry of the cell header rather than in
51554 ** the payload area.
51556 ** The cell pointer array begins on the first byte after the page header.
51557 ** The cell pointer array contains zero or more 2-byte numbers which are
51558 ** offsets from the beginning of the page to the cell content in the cell
51559 ** content area. The cell pointers occur in sorted order. The system strives
51560 ** to keep free space after the last cell pointer so that new cells can
51561 ** be easily added without having to defragment the page.
51563 ** Cell content is stored at the very end of the page and grows toward the
51564 ** beginning of the page.
51566 ** Unused space within the cell content area is collected into a linked list of
51567 ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
51568 ** to the first freeblock is given in the header. Freeblocks occur in
51569 ** increasing order. Because a freeblock must be at least 4 bytes in size,
51570 ** any group of 3 or fewer unused bytes in the cell content area cannot
51571 ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
51572 ** a fragment. The total number of bytes in all fragments is recorded.
51573 ** in the page header at offset 7.
51575 ** SIZE DESCRIPTION
51576 ** 2 Byte offset of the next freeblock
51577 ** 2 Bytes in this freeblock
51579 ** Cells are of variable length. Cells are stored in the cell content area at
51580 ** the end of the page. Pointers to the cells are in the cell pointer array
51581 ** that immediately follows the page header. Cells is not necessarily
51582 ** contiguous or in order, but cell pointers are contiguous and in order.
51584 ** Cell content makes use of variable length integers. A variable
51585 ** length integer is 1 to 9 bytes where the lower 7 bits of each
51586 ** byte are used. The integer consists of all bytes that have bit 8 set and
51587 ** the first byte with bit 8 clear. The most significant byte of the integer
51588 ** appears first. A variable-length integer may not be more than 9 bytes long.
51589 ** As a special case, all 8 bytes of the 9th byte are used as data. This
51590 ** allows a 64-bit integer to be encoded in 9 bytes.
51592 ** 0x00 becomes 0x00000000
51593 ** 0x7f becomes 0x0000007f
51594 ** 0x81 0x00 becomes 0x00000080
51595 ** 0x82 0x00 becomes 0x00000100
51596 ** 0x80 0x7f becomes 0x0000007f
51597 ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
51598 ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
51600 ** Variable length integers are used for rowids and to hold the number of
51601 ** bytes of key and data in a btree cell.
51603 ** The content of a cell looks like this:
51605 ** SIZE DESCRIPTION
51606 ** 4 Page number of the left child. Omitted if leaf flag is set.
51607 ** var Number of bytes of data. Omitted if the zerodata flag is set.
51608 ** var Number of bytes of key. Or the key itself if intkey flag is set.
51609 ** * Payload
51610 ** 4 First page of the overflow chain. Omitted if no overflow
51612 ** Overflow pages form a linked list. Each page except the last is completely
51613 ** filled with data (pagesize - 4 bytes). The last page can have as little
51614 ** as 1 byte of data.
51616 ** SIZE DESCRIPTION
51617 ** 4 Page number of next overflow page
51618 ** * Data
51620 ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
51621 ** file header points to the first in a linked list of trunk page. Each trunk
51622 ** page points to multiple leaf pages. The content of a leaf page is
51623 ** unspecified. A trunk page looks like this:
51625 ** SIZE DESCRIPTION
51626 ** 4 Page number of next trunk page
51627 ** 4 Number of leaf pointers on this page
51628 ** * zero or more pages numbers of leaves
51632 /* The following value is the maximum cell size assuming a maximum page
51633 ** size give above.
51635 #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
51637 /* The maximum number of cells on a single page of the database. This
51638 ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
51639 ** plus 2 bytes for the index to the cell in the page header). Such
51640 ** small cells will be rare, but they are possible.
51642 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
51644 /* Forward declarations */
51645 typedef struct MemPage MemPage;
51646 typedef struct BtLock BtLock;
51649 ** This is a magic string that appears at the beginning of every
51650 ** SQLite database in order to identify the file as a real database.
51652 ** You can change this value at compile-time by specifying a
51653 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
51654 ** header must be exactly 16 bytes including the zero-terminator so
51655 ** the string itself should be 15 characters long. If you change
51656 ** the header, then your custom library will not be able to read
51657 ** databases generated by the standard tools and the standard tools
51658 ** will not be able to read databases created by your custom library.
51660 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
51661 # define SQLITE_FILE_HEADER "SQLite format 3"
51662 #endif
51665 ** Page type flags. An ORed combination of these flags appear as the
51666 ** first byte of on-disk image of every BTree page.
51668 #define PTF_INTKEY 0x01
51669 #define PTF_ZERODATA 0x02
51670 #define PTF_LEAFDATA 0x04
51671 #define PTF_LEAF 0x08
51674 ** As each page of the file is loaded into memory, an instance of the following
51675 ** structure is appended and initialized to zero. This structure stores
51676 ** information about the page that is decoded from the raw file page.
51678 ** The pParent field points back to the parent page. This allows us to
51679 ** walk up the BTree from any leaf to the root. Care must be taken to
51680 ** unref() the parent page pointer when this page is no longer referenced.
51681 ** The pageDestructor() routine handles that chore.
51683 ** Access to all fields of this structure is controlled by the mutex
51684 ** stored in MemPage.pBt->mutex.
51686 struct MemPage {
51687 u8 isInit; /* True if previously initialized. MUST BE FIRST! */
51688 u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
51689 u8 intKey; /* True if table b-trees. False for index b-trees */
51690 u8 intKeyLeaf; /* True if the leaf of an intKey table */
51691 u8 noPayload; /* True if internal intKey page (thus w/o data) */
51692 u8 leaf; /* True if a leaf page */
51693 u8 hdrOffset; /* 100 for page 1. 0 otherwise */
51694 u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
51695 u8 max1bytePayload; /* min(maxLocal,127) */
51696 u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
51697 u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
51698 u16 cellOffset; /* Index in aData of first cell pointer */
51699 u16 nFree; /* Number of free bytes on the page */
51700 u16 nCell; /* Number of cells on this page, local and ovfl */
51701 u16 maskPage; /* Mask for page offset */
51702 u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
51703 ** non-overflow cell */
51704 u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
51705 BtShared *pBt; /* Pointer to BtShared that this page is part of */
51706 u8 *aData; /* Pointer to disk image of the page data */
51707 u8 *aDataEnd; /* One byte past the end of usable data */
51708 u8 *aCellIdx; /* The cell index area */
51709 DbPage *pDbPage; /* Pager page handle */
51710 Pgno pgno; /* Page number for this page */
51714 ** The in-memory image of a disk page has the auxiliary information appended
51715 ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
51716 ** that extra information.
51718 #define EXTRA_SIZE sizeof(MemPage)
51721 ** A linked list of the following structures is stored at BtShared.pLock.
51722 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
51723 ** is opened on the table with root page BtShared.iTable. Locks are removed
51724 ** from this list when a transaction is committed or rolled back, or when
51725 ** a btree handle is closed.
51727 struct BtLock {
51728 Btree *pBtree; /* Btree handle holding this lock */
51729 Pgno iTable; /* Root page of table */
51730 u8 eLock; /* READ_LOCK or WRITE_LOCK */
51731 BtLock *pNext; /* Next in BtShared.pLock list */
51734 /* Candidate values for BtLock.eLock */
51735 #define READ_LOCK 1
51736 #define WRITE_LOCK 2
51738 /* A Btree handle
51740 ** A database connection contains a pointer to an instance of
51741 ** this object for every database file that it has open. This structure
51742 ** is opaque to the database connection. The database connection cannot
51743 ** see the internals of this structure and only deals with pointers to
51744 ** this structure.
51746 ** For some database files, the same underlying database cache might be
51747 ** shared between multiple connections. In that case, each connection
51748 ** has it own instance of this object. But each instance of this object
51749 ** points to the same BtShared object. The database cache and the
51750 ** schema associated with the database file are all contained within
51751 ** the BtShared object.
51753 ** All fields in this structure are accessed under sqlite3.mutex.
51754 ** The pBt pointer itself may not be changed while there exists cursors
51755 ** in the referenced BtShared that point back to this Btree since those
51756 ** cursors have to go through this Btree to find their BtShared and
51757 ** they often do so without holding sqlite3.mutex.
51759 struct Btree {
51760 sqlite3 *db; /* The database connection holding this btree */
51761 BtShared *pBt; /* Sharable content of this btree */
51762 u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
51763 u8 sharable; /* True if we can share pBt with another db */
51764 u8 locked; /* True if db currently has pBt locked */
51765 int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
51766 int nBackup; /* Number of backup operations reading this btree */
51767 Btree *pNext; /* List of other sharable Btrees from the same db */
51768 Btree *pPrev; /* Back pointer of the same list */
51769 #ifndef SQLITE_OMIT_SHARED_CACHE
51770 BtLock lock; /* Object used to lock page 1 */
51771 #endif
51775 ** Btree.inTrans may take one of the following values.
51777 ** If the shared-data extension is enabled, there may be multiple users
51778 ** of the Btree structure. At most one of these may open a write transaction,
51779 ** but any number may have active read transactions.
51781 #define TRANS_NONE 0
51782 #define TRANS_READ 1
51783 #define TRANS_WRITE 2
51786 ** An instance of this object represents a single database file.
51788 ** A single database file can be in use at the same time by two
51789 ** or more database connections. When two or more connections are
51790 ** sharing the same database file, each connection has it own
51791 ** private Btree object for the file and each of those Btrees points
51792 ** to this one BtShared object. BtShared.nRef is the number of
51793 ** connections currently sharing this database file.
51795 ** Fields in this structure are accessed under the BtShared.mutex
51796 ** mutex, except for nRef and pNext which are accessed under the
51797 ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
51798 ** may not be modified once it is initially set as long as nRef>0.
51799 ** The pSchema field may be set once under BtShared.mutex and
51800 ** thereafter is unchanged as long as nRef>0.
51802 ** isPending:
51804 ** If a BtShared client fails to obtain a write-lock on a database
51805 ** table (because there exists one or more read-locks on the table),
51806 ** the shared-cache enters 'pending-lock' state and isPending is
51807 ** set to true.
51809 ** The shared-cache leaves the 'pending lock' state when either of
51810 ** the following occur:
51812 ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
51813 ** 2) The number of locks held by other connections drops to zero.
51815 ** while in the 'pending-lock' state, no connection may start a new
51816 ** transaction.
51818 ** This feature is included to help prevent writer-starvation.
51820 struct BtShared {
51821 Pager *pPager; /* The page cache */
51822 sqlite3 *db; /* Database connection currently using this Btree */
51823 BtCursor *pCursor; /* A list of all open cursors */
51824 MemPage *pPage1; /* First page of the database */
51825 u8 openFlags; /* Flags to sqlite3BtreeOpen() */
51826 #ifndef SQLITE_OMIT_AUTOVACUUM
51827 u8 autoVacuum; /* True if auto-vacuum is enabled */
51828 u8 incrVacuum; /* True if incr-vacuum is enabled */
51829 u8 bDoTruncate; /* True to truncate db on commit */
51830 #endif
51831 u8 inTransaction; /* Transaction state */
51832 u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
51833 u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
51834 u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
51835 u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
51836 u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
51837 u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
51838 u32 pageSize; /* Total number of bytes on a page */
51839 u32 usableSize; /* Number of usable bytes on each page */
51840 int nTransaction; /* Number of open transactions (read + write) */
51841 u32 nPage; /* Number of pages in the database */
51842 void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
51843 void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
51844 sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
51845 Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
51846 #ifndef SQLITE_OMIT_SHARED_CACHE
51847 int nRef; /* Number of references to this structure */
51848 BtShared *pNext; /* Next on a list of sharable BtShared structs */
51849 BtLock *pLock; /* List of locks held on this shared-btree struct */
51850 Btree *pWriter; /* Btree with currently open write transaction */
51851 #endif
51852 u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
51856 ** Allowed values for BtShared.btsFlags
51858 #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
51859 #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
51860 #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
51861 #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
51862 #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
51863 #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
51864 #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
51867 ** An instance of the following structure is used to hold information
51868 ** about a cell. The parseCellPtr() function fills in this structure
51869 ** based on information extract from the raw disk page.
51871 typedef struct CellInfo CellInfo;
51872 struct CellInfo {
51873 i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
51874 u8 *pPayload; /* Pointer to the start of payload */
51875 u32 nPayload; /* Bytes of payload */
51876 u16 nLocal; /* Amount of payload held locally, not on overflow */
51877 u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
51878 u16 nSize; /* Size of the cell content on the main b-tree page */
51882 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
51883 ** this will be declared corrupt. This value is calculated based on a
51884 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
51885 ** root-node and 3 for all other internal nodes.
51887 ** If a tree that appears to be taller than this is encountered, it is
51888 ** assumed that the database is corrupt.
51890 #define BTCURSOR_MAX_DEPTH 20
51893 ** A cursor is a pointer to a particular entry within a particular
51894 ** b-tree within a database file.
51896 ** The entry is identified by its MemPage and the index in
51897 ** MemPage.aCell[] of the entry.
51899 ** A single database file can be shared by two more database connections,
51900 ** but cursors cannot be shared. Each cursor is associated with a
51901 ** particular database connection identified BtCursor.pBtree.db.
51903 ** Fields in this structure are accessed under the BtShared.mutex
51904 ** found at self->pBt->mutex.
51906 ** skipNext meaning:
51907 ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op.
51908 ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op.
51909 ** eState==FAULT: Cursor fault with skipNext as error code.
51911 struct BtCursor {
51912 Btree *pBtree; /* The Btree to which this cursor belongs */
51913 BtShared *pBt; /* The BtShared this cursor points to */
51914 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
51915 struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
51916 Pgno *aOverflow; /* Cache of overflow page locations */
51917 CellInfo info; /* A parse of the cell we are pointing at */
51918 i64 nKey; /* Size of pKey, or last integer key */
51919 void *pKey; /* Saved key that was cursor last known position */
51920 Pgno pgnoRoot; /* The root page of this tree */
51921 int nOvflAlloc; /* Allocated size of aOverflow[] array */
51922 int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
51923 ** Error code if eState==CURSOR_FAULT */
51924 u8 curFlags; /* zero or more BTCF_* flags defined below */
51925 u8 eState; /* One of the CURSOR_XXX constants (see below) */
51926 u8 hints; /* As configured by CursorSetHints() */
51927 i16 iPage; /* Index of current page in apPage */
51928 u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
51929 MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
51933 ** Legal values for BtCursor.curFlags
51935 #define BTCF_WriteFlag 0x01 /* True if a write cursor */
51936 #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
51937 #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
51938 #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
51939 #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
51942 ** Potential values for BtCursor.eState.
51944 ** CURSOR_INVALID:
51945 ** Cursor does not point to a valid entry. This can happen (for example)
51946 ** because the table is empty or because BtreeCursorFirst() has not been
51947 ** called.
51949 ** CURSOR_VALID:
51950 ** Cursor points to a valid entry. getPayload() etc. may be called.
51952 ** CURSOR_SKIPNEXT:
51953 ** Cursor is valid except that the Cursor.skipNext field is non-zero
51954 ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
51955 ** operation should be a no-op.
51957 ** CURSOR_REQUIRESEEK:
51958 ** The table that this cursor was opened on still exists, but has been
51959 ** modified since the cursor was last used. The cursor position is saved
51960 ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
51961 ** this state, restoreCursorPosition() can be called to attempt to
51962 ** seek the cursor to the saved position.
51964 ** CURSOR_FAULT:
51965 ** An unrecoverable error (an I/O error or a malloc failure) has occurred
51966 ** on a different connection that shares the BtShared cache with this
51967 ** cursor. The error has left the cache in an inconsistent state.
51968 ** Do nothing else with this cursor. Any attempt to use the cursor
51969 ** should return the error code stored in BtCursor.skipNext
51971 #define CURSOR_INVALID 0
51972 #define CURSOR_VALID 1
51973 #define CURSOR_SKIPNEXT 2
51974 #define CURSOR_REQUIRESEEK 3
51975 #define CURSOR_FAULT 4
51978 ** The database page the PENDING_BYTE occupies. This page is never used.
51980 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
51983 ** These macros define the location of the pointer-map entry for a
51984 ** database page. The first argument to each is the number of usable
51985 ** bytes on each page of the database (often 1024). The second is the
51986 ** page number to look up in the pointer map.
51988 ** PTRMAP_PAGENO returns the database page number of the pointer-map
51989 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
51990 ** the offset of the requested map entry.
51992 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
51993 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
51994 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
51995 ** this test.
51997 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
51998 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
51999 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
52002 ** The pointer map is a lookup table that identifies the parent page for
52003 ** each child page in the database file. The parent page is the page that
52004 ** contains a pointer to the child. Every page in the database contains
52005 ** 0 or 1 parent pages. (In this context 'database page' refers
52006 ** to any page that is not part of the pointer map itself.) Each pointer map
52007 ** entry consists of a single byte 'type' and a 4 byte parent page number.
52008 ** The PTRMAP_XXX identifiers below are the valid types.
52010 ** The purpose of the pointer map is to facility moving pages from one
52011 ** position in the file to another as part of autovacuum. When a page
52012 ** is moved, the pointer in its parent must be updated to point to the
52013 ** new location. The pointer map is used to locate the parent page quickly.
52015 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
52016 ** used in this case.
52018 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
52019 ** is not used in this case.
52021 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
52022 ** overflow pages. The page number identifies the page that
52023 ** contains the cell with a pointer to this overflow page.
52025 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
52026 ** overflow pages. The page-number identifies the previous
52027 ** page in the overflow page list.
52029 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
52030 ** identifies the parent page in the btree.
52032 #define PTRMAP_ROOTPAGE 1
52033 #define PTRMAP_FREEPAGE 2
52034 #define PTRMAP_OVERFLOW1 3
52035 #define PTRMAP_OVERFLOW2 4
52036 #define PTRMAP_BTREE 5
52038 /* A bunch of assert() statements to check the transaction state variables
52039 ** of handle p (type Btree*) are internally consistent.
52041 #define btreeIntegrity(p) \
52042 assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
52043 assert( p->pBt->inTransaction>=p->inTrans );
52047 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
52048 ** if the database supports auto-vacuum or not. Because it is used
52049 ** within an expression that is an argument to another macro
52050 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
52051 ** So, this macro is defined instead.
52053 #ifndef SQLITE_OMIT_AUTOVACUUM
52054 #define ISAUTOVACUUM (pBt->autoVacuum)
52055 #else
52056 #define ISAUTOVACUUM 0
52057 #endif
52061 ** This structure is passed around through all the sanity checking routines
52062 ** in order to keep track of some global state information.
52064 ** The aRef[] array is allocated so that there is 1 bit for each page in
52065 ** the database. As the integrity-check proceeds, for each page used in
52066 ** the database the corresponding bit is set. This allows integrity-check to
52067 ** detect pages that are used twice and orphaned pages (both of which
52068 ** indicate corruption).
52070 typedef struct IntegrityCk IntegrityCk;
52071 struct IntegrityCk {
52072 BtShared *pBt; /* The tree being checked out */
52073 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
52074 u8 *aPgRef; /* 1 bit per page in the db (see above) */
52075 Pgno nPage; /* Number of pages in the database */
52076 int mxErr; /* Stop accumulating errors when this reaches zero */
52077 int nErr; /* Number of messages written to zErrMsg so far */
52078 int mallocFailed; /* A memory allocation error has occurred */
52079 const char *zPfx; /* Error message prefix */
52080 int v1, v2; /* Values for up to two %d fields in zPfx */
52081 StrAccum errMsg; /* Accumulate the error message text here */
52085 ** Routines to read or write a two- and four-byte big-endian integer values.
52087 #define get2byte(x) ((x)[0]<<8 | (x)[1])
52088 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
52089 #define get4byte sqlite3Get4byte
52090 #define put4byte sqlite3Put4byte
52092 /************** End of btreeInt.h ********************************************/
52093 /************** Continuing where we left off in btmutex.c ********************/
52094 #ifndef SQLITE_OMIT_SHARED_CACHE
52095 #if SQLITE_THREADSAFE
52098 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
52099 ** set BtShared.db to the database handle associated with p and the
52100 ** p->locked boolean to true.
52102 static void lockBtreeMutex(Btree *p){
52103 assert( p->locked==0 );
52104 assert( sqlite3_mutex_notheld(p->pBt->mutex) );
52105 assert( sqlite3_mutex_held(p->db->mutex) );
52107 sqlite3_mutex_enter(p->pBt->mutex);
52108 p->pBt->db = p->db;
52109 p->locked = 1;
52113 ** Release the BtShared mutex associated with B-Tree handle p and
52114 ** clear the p->locked boolean.
52116 static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
52117 BtShared *pBt = p->pBt;
52118 assert( p->locked==1 );
52119 assert( sqlite3_mutex_held(pBt->mutex) );
52120 assert( sqlite3_mutex_held(p->db->mutex) );
52121 assert( p->db==pBt->db );
52123 sqlite3_mutex_leave(pBt->mutex);
52124 p->locked = 0;
52127 /* Forward reference */
52128 static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
52131 ** Enter a mutex on the given BTree object.
52133 ** If the object is not sharable, then no mutex is ever required
52134 ** and this routine is a no-op. The underlying mutex is non-recursive.
52135 ** But we keep a reference count in Btree.wantToLock so the behavior
52136 ** of this interface is recursive.
52138 ** To avoid deadlocks, multiple Btrees are locked in the same order
52139 ** by all database connections. The p->pNext is a list of other
52140 ** Btrees belonging to the same database connection as the p Btree
52141 ** which need to be locked after p. If we cannot get a lock on
52142 ** p, then first unlock all of the others on p->pNext, then wait
52143 ** for the lock to become available on p, then relock all of the
52144 ** subsequent Btrees that desire a lock.
52146 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
52147 /* Some basic sanity checking on the Btree. The list of Btrees
52148 ** connected by pNext and pPrev should be in sorted order by
52149 ** Btree.pBt value. All elements of the list should belong to
52150 ** the same connection. Only shared Btrees are on the list. */
52151 assert( p->pNext==0 || p->pNext->pBt>p->pBt );
52152 assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
52153 assert( p->pNext==0 || p->pNext->db==p->db );
52154 assert( p->pPrev==0 || p->pPrev->db==p->db );
52155 assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
52157 /* Check for locking consistency */
52158 assert( !p->locked || p->wantToLock>0 );
52159 assert( p->sharable || p->wantToLock==0 );
52161 /* We should already hold a lock on the database connection */
52162 assert( sqlite3_mutex_held(p->db->mutex) );
52164 /* Unless the database is sharable and unlocked, then BtShared.db
52165 ** should already be set correctly. */
52166 assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
52168 if( !p->sharable ) return;
52169 p->wantToLock++;
52170 if( p->locked ) return;
52171 btreeLockCarefully(p);
52174 /* This is a helper function for sqlite3BtreeLock(). By moving
52175 ** complex, but seldom used logic, out of sqlite3BtreeLock() and
52176 ** into this routine, we avoid unnecessary stack pointer changes
52177 ** and thus help the sqlite3BtreeLock() routine to run much faster
52178 ** in the common case.
52180 static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
52181 Btree *pLater;
52183 /* In most cases, we should be able to acquire the lock we
52184 ** want without having to go through the ascending lock
52185 ** procedure that follows. Just be sure not to block.
52187 if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
52188 p->pBt->db = p->db;
52189 p->locked = 1;
52190 return;
52193 /* To avoid deadlock, first release all locks with a larger
52194 ** BtShared address. Then acquire our lock. Then reacquire
52195 ** the other BtShared locks that we used to hold in ascending
52196 ** order.
52198 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
52199 assert( pLater->sharable );
52200 assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
52201 assert( !pLater->locked || pLater->wantToLock>0 );
52202 if( pLater->locked ){
52203 unlockBtreeMutex(pLater);
52206 lockBtreeMutex(p);
52207 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
52208 if( pLater->wantToLock ){
52209 lockBtreeMutex(pLater);
52216 ** Exit the recursive mutex on a Btree.
52218 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
52219 if( p->sharable ){
52220 assert( p->wantToLock>0 );
52221 p->wantToLock--;
52222 if( p->wantToLock==0 ){
52223 unlockBtreeMutex(p);
52228 #ifndef NDEBUG
52230 ** Return true if the BtShared mutex is held on the btree, or if the
52231 ** B-Tree is not marked as sharable.
52233 ** This routine is used only from within assert() statements.
52235 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
52236 assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
52237 assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
52238 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
52239 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
52241 return (p->sharable==0 || p->locked);
52243 #endif
52246 #ifndef SQLITE_OMIT_INCRBLOB
52248 ** Enter and leave a mutex on a Btree given a cursor owned by that
52249 ** Btree. These entry points are used by incremental I/O and can be
52250 ** omitted if that module is not used.
52252 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
52253 sqlite3BtreeEnter(pCur->pBtree);
52255 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
52256 sqlite3BtreeLeave(pCur->pBtree);
52258 #endif /* SQLITE_OMIT_INCRBLOB */
52262 ** Enter the mutex on every Btree associated with a database
52263 ** connection. This is needed (for example) prior to parsing
52264 ** a statement since we will be comparing table and column names
52265 ** against all schemas and we do not want those schemas being
52266 ** reset out from under us.
52268 ** There is a corresponding leave-all procedures.
52270 ** Enter the mutexes in accending order by BtShared pointer address
52271 ** to avoid the possibility of deadlock when two threads with
52272 ** two or more btrees in common both try to lock all their btrees
52273 ** at the same instant.
52275 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
52276 int i;
52277 Btree *p;
52278 assert( sqlite3_mutex_held(db->mutex) );
52279 for(i=0; i<db->nDb; i++){
52280 p = db->aDb[i].pBt;
52281 if( p ) sqlite3BtreeEnter(p);
52284 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
52285 int i;
52286 Btree *p;
52287 assert( sqlite3_mutex_held(db->mutex) );
52288 for(i=0; i<db->nDb; i++){
52289 p = db->aDb[i].pBt;
52290 if( p ) sqlite3BtreeLeave(p);
52295 ** Return true if a particular Btree requires a lock. Return FALSE if
52296 ** no lock is ever required since it is not sharable.
52298 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
52299 return p->sharable;
52302 #ifndef NDEBUG
52304 ** Return true if the current thread holds the database connection
52305 ** mutex and all required BtShared mutexes.
52307 ** This routine is used inside assert() statements only.
52309 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
52310 int i;
52311 if( !sqlite3_mutex_held(db->mutex) ){
52312 return 0;
52314 for(i=0; i<db->nDb; i++){
52315 Btree *p;
52316 p = db->aDb[i].pBt;
52317 if( p && p->sharable &&
52318 (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
52319 return 0;
52322 return 1;
52324 #endif /* NDEBUG */
52326 #ifndef NDEBUG
52328 ** Return true if the correct mutexes are held for accessing the
52329 ** db->aDb[iDb].pSchema structure. The mutexes required for schema
52330 ** access are:
52332 ** (1) The mutex on db
52333 ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
52335 ** If pSchema is not NULL, then iDb is computed from pSchema and
52336 ** db using sqlite3SchemaToIndex().
52338 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
52339 Btree *p;
52340 assert( db!=0 );
52341 if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
52342 assert( iDb>=0 && iDb<db->nDb );
52343 if( !sqlite3_mutex_held(db->mutex) ) return 0;
52344 if( iDb==1 ) return 1;
52345 p = db->aDb[iDb].pBt;
52346 assert( p!=0 );
52347 return p->sharable==0 || p->locked==1;
52349 #endif /* NDEBUG */
52351 #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
52353 ** The following are special cases for mutex enter routines for use
52354 ** in single threaded applications that use shared cache. Except for
52355 ** these two routines, all mutex operations are no-ops in that case and
52356 ** are null #defines in btree.h.
52358 ** If shared cache is disabled, then all btree mutex routines, including
52359 ** the ones below, are no-ops and are null #defines in btree.h.
52362 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
52363 p->pBt->db = p->db;
52365 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
52366 int i;
52367 for(i=0; i<db->nDb; i++){
52368 Btree *p = db->aDb[i].pBt;
52369 if( p ){
52370 p->pBt->db = p->db;
52374 #endif /* if SQLITE_THREADSAFE */
52375 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
52377 /************** End of btmutex.c *********************************************/
52378 /************** Begin file btree.c *******************************************/
52380 ** 2004 April 6
52382 ** The author disclaims copyright to this source code. In place of
52383 ** a legal notice, here is a blessing:
52385 ** May you do good and not evil.
52386 ** May you find forgiveness for yourself and forgive others.
52387 ** May you share freely, never taking more than you give.
52389 *************************************************************************
52390 ** This file implements an external (disk-based) database using BTrees.
52391 ** See the header comment on "btreeInt.h" for additional information.
52392 ** Including a description of file format and an overview of operation.
52396 ** The header string that appears at the beginning of every
52397 ** SQLite database.
52399 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
52402 ** Set this global variable to 1 to enable tracing using the TRACE
52403 ** macro.
52405 #if 0
52406 int sqlite3BtreeTrace=1; /* True to enable tracing */
52407 # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
52408 #else
52409 # define TRACE(X)
52410 #endif
52413 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
52414 ** But if the value is zero, make it 65536.
52416 ** This routine is used to extract the "offset to cell content area" value
52417 ** from the header of a btree page. If the page size is 65536 and the page
52418 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
52419 ** This routine makes the necessary adjustment to 65536.
52421 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
52424 ** Values passed as the 5th argument to allocateBtreePage()
52426 #define BTALLOC_ANY 0 /* Allocate any page */
52427 #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
52428 #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
52431 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
52432 ** defined, or 0 if it is. For example:
52434 ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
52436 #ifndef SQLITE_OMIT_AUTOVACUUM
52437 #define IfNotOmitAV(expr) (expr)
52438 #else
52439 #define IfNotOmitAV(expr) 0
52440 #endif
52442 #ifndef SQLITE_OMIT_SHARED_CACHE
52444 ** A list of BtShared objects that are eligible for participation
52445 ** in shared cache. This variable has file scope during normal builds,
52446 ** but the test harness needs to access it so we make it global for
52447 ** test builds.
52449 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
52451 #ifdef SQLITE_TEST
52452 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
52453 #else
52454 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
52455 #endif
52456 #endif /* SQLITE_OMIT_SHARED_CACHE */
52458 #ifndef SQLITE_OMIT_SHARED_CACHE
52460 ** Enable or disable the shared pager and schema features.
52462 ** This routine has no effect on existing database connections.
52463 ** The shared cache setting effects only future calls to
52464 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
52466 SQLITE_API int sqlite3_enable_shared_cache(int enable){
52467 sqlite3GlobalConfig.sharedCacheEnabled = enable;
52468 return SQLITE_OK;
52470 #endif
52474 #ifdef SQLITE_OMIT_SHARED_CACHE
52476 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
52477 ** and clearAllSharedCacheTableLocks()
52478 ** manipulate entries in the BtShared.pLock linked list used to store
52479 ** shared-cache table level locks. If the library is compiled with the
52480 ** shared-cache feature disabled, then there is only ever one user
52481 ** of each BtShared structure and so this locking is not necessary.
52482 ** So define the lock related functions as no-ops.
52484 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
52485 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
52486 #define clearAllSharedCacheTableLocks(a)
52487 #define downgradeAllSharedCacheTableLocks(a)
52488 #define hasSharedCacheTableLock(a,b,c,d) 1
52489 #define hasReadConflicts(a, b) 0
52490 #endif
52492 #ifndef SQLITE_OMIT_SHARED_CACHE
52494 #ifdef SQLITE_DEBUG
52496 **** This function is only used as part of an assert() statement. ***
52498 ** Check to see if pBtree holds the required locks to read or write to the
52499 ** table with root page iRoot. Return 1 if it does and 0 if not.
52501 ** For example, when writing to a table with root-page iRoot via
52502 ** Btree connection pBtree:
52504 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
52506 ** When writing to an index that resides in a sharable database, the
52507 ** caller should have first obtained a lock specifying the root page of
52508 ** the corresponding table. This makes things a bit more complicated,
52509 ** as this module treats each table as a separate structure. To determine
52510 ** the table corresponding to the index being written, this
52511 ** function has to search through the database schema.
52513 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
52514 ** hold a write-lock on the schema table (root page 1). This is also
52515 ** acceptable.
52517 static int hasSharedCacheTableLock(
52518 Btree *pBtree, /* Handle that must hold lock */
52519 Pgno iRoot, /* Root page of b-tree */
52520 int isIndex, /* True if iRoot is the root of an index b-tree */
52521 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
52523 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
52524 Pgno iTab = 0;
52525 BtLock *pLock;
52527 /* If this database is not shareable, or if the client is reading
52528 ** and has the read-uncommitted flag set, then no lock is required.
52529 ** Return true immediately.
52531 if( (pBtree->sharable==0)
52532 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
52534 return 1;
52537 /* If the client is reading or writing an index and the schema is
52538 ** not loaded, then it is too difficult to actually check to see if
52539 ** the correct locks are held. So do not bother - just return true.
52540 ** This case does not come up very often anyhow.
52542 if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
52543 return 1;
52546 /* Figure out the root-page that the lock should be held on. For table
52547 ** b-trees, this is just the root page of the b-tree being read or
52548 ** written. For index b-trees, it is the root page of the associated
52549 ** table. */
52550 if( isIndex ){
52551 HashElem *p;
52552 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
52553 Index *pIdx = (Index *)sqliteHashData(p);
52554 if( pIdx->tnum==(int)iRoot ){
52555 iTab = pIdx->pTable->tnum;
52558 }else{
52559 iTab = iRoot;
52562 /* Search for the required lock. Either a write-lock on root-page iTab, a
52563 ** write-lock on the schema table, or (if the client is reading) a
52564 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
52565 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
52566 if( pLock->pBtree==pBtree
52567 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
52568 && pLock->eLock>=eLockType
52570 return 1;
52574 /* Failed to find the required lock. */
52575 return 0;
52577 #endif /* SQLITE_DEBUG */
52579 #ifdef SQLITE_DEBUG
52581 **** This function may be used as part of assert() statements only. ****
52583 ** Return true if it would be illegal for pBtree to write into the
52584 ** table or index rooted at iRoot because other shared connections are
52585 ** simultaneously reading that same table or index.
52587 ** It is illegal for pBtree to write if some other Btree object that
52588 ** shares the same BtShared object is currently reading or writing
52589 ** the iRoot table. Except, if the other Btree object has the
52590 ** read-uncommitted flag set, then it is OK for the other object to
52591 ** have a read cursor.
52593 ** For example, before writing to any part of the table or index
52594 ** rooted at page iRoot, one should call:
52596 ** assert( !hasReadConflicts(pBtree, iRoot) );
52598 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
52599 BtCursor *p;
52600 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
52601 if( p->pgnoRoot==iRoot
52602 && p->pBtree!=pBtree
52603 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
52605 return 1;
52608 return 0;
52610 #endif /* #ifdef SQLITE_DEBUG */
52613 ** Query to see if Btree handle p may obtain a lock of type eLock
52614 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
52615 ** SQLITE_OK if the lock may be obtained (by calling
52616 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
52618 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
52619 BtShared *pBt = p->pBt;
52620 BtLock *pIter;
52622 assert( sqlite3BtreeHoldsMutex(p) );
52623 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
52624 assert( p->db!=0 );
52625 assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
52627 /* If requesting a write-lock, then the Btree must have an open write
52628 ** transaction on this file. And, obviously, for this to be so there
52629 ** must be an open write transaction on the file itself.
52631 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
52632 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
52634 /* This routine is a no-op if the shared-cache is not enabled */
52635 if( !p->sharable ){
52636 return SQLITE_OK;
52639 /* If some other connection is holding an exclusive lock, the
52640 ** requested lock may not be obtained.
52642 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
52643 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
52644 return SQLITE_LOCKED_SHAREDCACHE;
52647 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
52648 /* The condition (pIter->eLock!=eLock) in the following if(...)
52649 ** statement is a simplification of:
52651 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
52653 ** since we know that if eLock==WRITE_LOCK, then no other connection
52654 ** may hold a WRITE_LOCK on any table in this file (since there can
52655 ** only be a single writer).
52657 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
52658 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
52659 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
52660 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
52661 if( eLock==WRITE_LOCK ){
52662 assert( p==pBt->pWriter );
52663 pBt->btsFlags |= BTS_PENDING;
52665 return SQLITE_LOCKED_SHAREDCACHE;
52668 return SQLITE_OK;
52670 #endif /* !SQLITE_OMIT_SHARED_CACHE */
52672 #ifndef SQLITE_OMIT_SHARED_CACHE
52674 ** Add a lock on the table with root-page iTable to the shared-btree used
52675 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
52676 ** WRITE_LOCK.
52678 ** This function assumes the following:
52680 ** (a) The specified Btree object p is connected to a sharable
52681 ** database (one with the BtShared.sharable flag set), and
52683 ** (b) No other Btree objects hold a lock that conflicts
52684 ** with the requested lock (i.e. querySharedCacheTableLock() has
52685 ** already been called and returned SQLITE_OK).
52687 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
52688 ** is returned if a malloc attempt fails.
52690 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
52691 BtShared *pBt = p->pBt;
52692 BtLock *pLock = 0;
52693 BtLock *pIter;
52695 assert( sqlite3BtreeHoldsMutex(p) );
52696 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
52697 assert( p->db!=0 );
52699 /* A connection with the read-uncommitted flag set will never try to
52700 ** obtain a read-lock using this function. The only read-lock obtained
52701 ** by a connection in read-uncommitted mode is on the sqlite_master
52702 ** table, and that lock is obtained in BtreeBeginTrans(). */
52703 assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
52705 /* This function should only be called on a sharable b-tree after it
52706 ** has been determined that no other b-tree holds a conflicting lock. */
52707 assert( p->sharable );
52708 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
52710 /* First search the list for an existing lock on this table. */
52711 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
52712 if( pIter->iTable==iTable && pIter->pBtree==p ){
52713 pLock = pIter;
52714 break;
52718 /* If the above search did not find a BtLock struct associating Btree p
52719 ** with table iTable, allocate one and link it into the list.
52721 if( !pLock ){
52722 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
52723 if( !pLock ){
52724 return SQLITE_NOMEM;
52726 pLock->iTable = iTable;
52727 pLock->pBtree = p;
52728 pLock->pNext = pBt->pLock;
52729 pBt->pLock = pLock;
52732 /* Set the BtLock.eLock variable to the maximum of the current lock
52733 ** and the requested lock. This means if a write-lock was already held
52734 ** and a read-lock requested, we don't incorrectly downgrade the lock.
52736 assert( WRITE_LOCK>READ_LOCK );
52737 if( eLock>pLock->eLock ){
52738 pLock->eLock = eLock;
52741 return SQLITE_OK;
52743 #endif /* !SQLITE_OMIT_SHARED_CACHE */
52745 #ifndef SQLITE_OMIT_SHARED_CACHE
52747 ** Release all the table locks (locks obtained via calls to
52748 ** the setSharedCacheTableLock() procedure) held by Btree object p.
52750 ** This function assumes that Btree p has an open read or write
52751 ** transaction. If it does not, then the BTS_PENDING flag
52752 ** may be incorrectly cleared.
52754 static void clearAllSharedCacheTableLocks(Btree *p){
52755 BtShared *pBt = p->pBt;
52756 BtLock **ppIter = &pBt->pLock;
52758 assert( sqlite3BtreeHoldsMutex(p) );
52759 assert( p->sharable || 0==*ppIter );
52760 assert( p->inTrans>0 );
52762 while( *ppIter ){
52763 BtLock *pLock = *ppIter;
52764 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
52765 assert( pLock->pBtree->inTrans>=pLock->eLock );
52766 if( pLock->pBtree==p ){
52767 *ppIter = pLock->pNext;
52768 assert( pLock->iTable!=1 || pLock==&p->lock );
52769 if( pLock->iTable!=1 ){
52770 sqlite3_free(pLock);
52772 }else{
52773 ppIter = &pLock->pNext;
52777 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
52778 if( pBt->pWriter==p ){
52779 pBt->pWriter = 0;
52780 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
52781 }else if( pBt->nTransaction==2 ){
52782 /* This function is called when Btree p is concluding its
52783 ** transaction. If there currently exists a writer, and p is not
52784 ** that writer, then the number of locks held by connections other
52785 ** than the writer must be about to drop to zero. In this case
52786 ** set the BTS_PENDING flag to 0.
52788 ** If there is not currently a writer, then BTS_PENDING must
52789 ** be zero already. So this next line is harmless in that case.
52791 pBt->btsFlags &= ~BTS_PENDING;
52796 ** This function changes all write-locks held by Btree p into read-locks.
52798 static void downgradeAllSharedCacheTableLocks(Btree *p){
52799 BtShared *pBt = p->pBt;
52800 if( pBt->pWriter==p ){
52801 BtLock *pLock;
52802 pBt->pWriter = 0;
52803 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
52804 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
52805 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
52806 pLock->eLock = READ_LOCK;
52811 #endif /* SQLITE_OMIT_SHARED_CACHE */
52813 static void releasePage(MemPage *pPage); /* Forward reference */
52816 ***** This routine is used inside of assert() only ****
52818 ** Verify that the cursor holds the mutex on its BtShared
52820 #ifdef SQLITE_DEBUG
52821 static int cursorHoldsMutex(BtCursor *p){
52822 return sqlite3_mutex_held(p->pBt->mutex);
52824 #endif
52827 ** Invalidate the overflow cache of the cursor passed as the first argument.
52828 ** on the shared btree structure pBt.
52830 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
52833 ** Invalidate the overflow page-list cache for all cursors opened
52834 ** on the shared btree structure pBt.
52836 static void invalidateAllOverflowCache(BtShared *pBt){
52837 BtCursor *p;
52838 assert( sqlite3_mutex_held(pBt->mutex) );
52839 for(p=pBt->pCursor; p; p=p->pNext){
52840 invalidateOverflowCache(p);
52844 #ifndef SQLITE_OMIT_INCRBLOB
52846 ** This function is called before modifying the contents of a table
52847 ** to invalidate any incrblob cursors that are open on the
52848 ** row or one of the rows being modified.
52850 ** If argument isClearTable is true, then the entire contents of the
52851 ** table is about to be deleted. In this case invalidate all incrblob
52852 ** cursors open on any row within the table with root-page pgnoRoot.
52854 ** Otherwise, if argument isClearTable is false, then the row with
52855 ** rowid iRow is being replaced or deleted. In this case invalidate
52856 ** only those incrblob cursors open on that specific row.
52858 static void invalidateIncrblobCursors(
52859 Btree *pBtree, /* The database file to check */
52860 i64 iRow, /* The rowid that might be changing */
52861 int isClearTable /* True if all rows are being deleted */
52863 BtCursor *p;
52864 BtShared *pBt = pBtree->pBt;
52865 assert( sqlite3BtreeHoldsMutex(pBtree) );
52866 for(p=pBt->pCursor; p; p=p->pNext){
52867 if( (p->curFlags & BTCF_Incrblob)!=0
52868 && (isClearTable || p->info.nKey==iRow)
52870 p->eState = CURSOR_INVALID;
52875 #else
52876 /* Stub function when INCRBLOB is omitted */
52877 #define invalidateIncrblobCursors(x,y,z)
52878 #endif /* SQLITE_OMIT_INCRBLOB */
52881 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
52882 ** when a page that previously contained data becomes a free-list leaf
52883 ** page.
52885 ** The BtShared.pHasContent bitvec exists to work around an obscure
52886 ** bug caused by the interaction of two useful IO optimizations surrounding
52887 ** free-list leaf pages:
52889 ** 1) When all data is deleted from a page and the page becomes
52890 ** a free-list leaf page, the page is not written to the database
52891 ** (as free-list leaf pages contain no meaningful data). Sometimes
52892 ** such a page is not even journalled (as it will not be modified,
52893 ** why bother journalling it?).
52895 ** 2) When a free-list leaf page is reused, its content is not read
52896 ** from the database or written to the journal file (why should it
52897 ** be, if it is not at all meaningful?).
52899 ** By themselves, these optimizations work fine and provide a handy
52900 ** performance boost to bulk delete or insert operations. However, if
52901 ** a page is moved to the free-list and then reused within the same
52902 ** transaction, a problem comes up. If the page is not journalled when
52903 ** it is moved to the free-list and it is also not journalled when it
52904 ** is extracted from the free-list and reused, then the original data
52905 ** may be lost. In the event of a rollback, it may not be possible
52906 ** to restore the database to its original configuration.
52908 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
52909 ** moved to become a free-list leaf page, the corresponding bit is
52910 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
52911 ** optimization 2 above is omitted if the corresponding bit is already
52912 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
52913 ** at the end of every transaction.
52915 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
52916 int rc = SQLITE_OK;
52917 if( !pBt->pHasContent ){
52918 assert( pgno<=pBt->nPage );
52919 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
52920 if( !pBt->pHasContent ){
52921 rc = SQLITE_NOMEM;
52924 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
52925 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
52927 return rc;
52931 ** Query the BtShared.pHasContent vector.
52933 ** This function is called when a free-list leaf page is removed from the
52934 ** free-list for reuse. It returns false if it is safe to retrieve the
52935 ** page from the pager layer with the 'no-content' flag set. True otherwise.
52937 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
52938 Bitvec *p = pBt->pHasContent;
52939 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
52943 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
52944 ** invoked at the conclusion of each write-transaction.
52946 static void btreeClearHasContent(BtShared *pBt){
52947 sqlite3BitvecDestroy(pBt->pHasContent);
52948 pBt->pHasContent = 0;
52952 ** Release all of the apPage[] pages for a cursor.
52954 static void btreeReleaseAllCursorPages(BtCursor *pCur){
52955 int i;
52956 for(i=0; i<=pCur->iPage; i++){
52957 releasePage(pCur->apPage[i]);
52958 pCur->apPage[i] = 0;
52960 pCur->iPage = -1;
52965 ** Save the current cursor position in the variables BtCursor.nKey
52966 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
52968 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
52969 ** prior to calling this routine.
52971 static int saveCursorPosition(BtCursor *pCur){
52972 int rc;
52974 assert( CURSOR_VALID==pCur->eState );
52975 assert( 0==pCur->pKey );
52976 assert( cursorHoldsMutex(pCur) );
52978 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
52979 assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
52981 /* If this is an intKey table, then the above call to BtreeKeySize()
52982 ** stores the integer key in pCur->nKey. In this case this value is
52983 ** all that is required. Otherwise, if pCur is not open on an intKey
52984 ** table, then malloc space for and store the pCur->nKey bytes of key
52985 ** data.
52987 if( 0==pCur->apPage[0]->intKey ){
52988 void *pKey = sqlite3Malloc( pCur->nKey );
52989 if( pKey ){
52990 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
52991 if( rc==SQLITE_OK ){
52992 pCur->pKey = pKey;
52993 }else{
52994 sqlite3_free(pKey);
52996 }else{
52997 rc = SQLITE_NOMEM;
53000 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
53002 if( rc==SQLITE_OK ){
53003 btreeReleaseAllCursorPages(pCur);
53004 pCur->eState = CURSOR_REQUIRESEEK;
53007 invalidateOverflowCache(pCur);
53008 return rc;
53011 /* Forward reference */
53012 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
53015 ** Save the positions of all cursors (except pExcept) that are open on
53016 ** the table with root-page iRoot. "Saving the cursor position" means that
53017 ** the location in the btree is remembered in such a way that it can be
53018 ** moved back to the same spot after the btree has been modified. This
53019 ** routine is called just before cursor pExcept is used to modify the
53020 ** table, for example in BtreeDelete() or BtreeInsert().
53022 ** Implementation note: This routine merely checks to see if any cursors
53023 ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
53024 ** event that cursors are in need to being saved.
53026 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
53027 BtCursor *p;
53028 assert( sqlite3_mutex_held(pBt->mutex) );
53029 assert( pExcept==0 || pExcept->pBt==pBt );
53030 for(p=pBt->pCursor; p; p=p->pNext){
53031 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
53033 return p ? saveCursorsOnList(p, iRoot, pExcept) : SQLITE_OK;
53036 /* This helper routine to saveAllCursors does the actual work of saving
53037 ** the cursors if and when a cursor is found that actually requires saving.
53038 ** The common case is that no cursors need to be saved, so this routine is
53039 ** broken out from its caller to avoid unnecessary stack pointer movement.
53041 static int SQLITE_NOINLINE saveCursorsOnList(
53042 BtCursor *p, /* The first cursor that needs saving */
53043 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
53044 BtCursor *pExcept /* Do not save this cursor */
53047 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
53048 if( p->eState==CURSOR_VALID ){
53049 int rc = saveCursorPosition(p);
53050 if( SQLITE_OK!=rc ){
53051 return rc;
53053 }else{
53054 testcase( p->iPage>0 );
53055 btreeReleaseAllCursorPages(p);
53058 p = p->pNext;
53059 }while( p );
53060 return SQLITE_OK;
53064 ** Clear the current cursor position.
53066 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
53067 assert( cursorHoldsMutex(pCur) );
53068 sqlite3_free(pCur->pKey);
53069 pCur->pKey = 0;
53070 pCur->eState = CURSOR_INVALID;
53074 ** In this version of BtreeMoveto, pKey is a packed index record
53075 ** such as is generated by the OP_MakeRecord opcode. Unpack the
53076 ** record and then call BtreeMovetoUnpacked() to do the work.
53078 static int btreeMoveto(
53079 BtCursor *pCur, /* Cursor open on the btree to be searched */
53080 const void *pKey, /* Packed key if the btree is an index */
53081 i64 nKey, /* Integer key for tables. Size of pKey for indices */
53082 int bias, /* Bias search to the high end */
53083 int *pRes /* Write search results here */
53085 int rc; /* Status code */
53086 UnpackedRecord *pIdxKey; /* Unpacked index key */
53087 char aSpace[200]; /* Temp space for pIdxKey - to avoid a malloc */
53088 char *pFree = 0;
53090 if( pKey ){
53091 assert( nKey==(i64)(int)nKey );
53092 pIdxKey = sqlite3VdbeAllocUnpackedRecord(
53093 pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
53095 if( pIdxKey==0 ) return SQLITE_NOMEM;
53096 sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
53097 if( pIdxKey->nField==0 ){
53098 sqlite3DbFree(pCur->pKeyInfo->db, pFree);
53099 return SQLITE_CORRUPT_BKPT;
53101 }else{
53102 pIdxKey = 0;
53104 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
53105 if( pFree ){
53106 sqlite3DbFree(pCur->pKeyInfo->db, pFree);
53108 return rc;
53112 ** Restore the cursor to the position it was in (or as close to as possible)
53113 ** when saveCursorPosition() was called. Note that this call deletes the
53114 ** saved position info stored by saveCursorPosition(), so there can be
53115 ** at most one effective restoreCursorPosition() call after each
53116 ** saveCursorPosition().
53118 static int btreeRestoreCursorPosition(BtCursor *pCur){
53119 int rc;
53120 assert( cursorHoldsMutex(pCur) );
53121 assert( pCur->eState>=CURSOR_REQUIRESEEK );
53122 if( pCur->eState==CURSOR_FAULT ){
53123 return pCur->skipNext;
53125 pCur->eState = CURSOR_INVALID;
53126 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
53127 if( rc==SQLITE_OK ){
53128 sqlite3_free(pCur->pKey);
53129 pCur->pKey = 0;
53130 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
53131 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
53132 pCur->eState = CURSOR_SKIPNEXT;
53135 return rc;
53138 #define restoreCursorPosition(p) \
53139 (p->eState>=CURSOR_REQUIRESEEK ? \
53140 btreeRestoreCursorPosition(p) : \
53141 SQLITE_OK)
53144 ** Determine whether or not a cursor has moved from the position where
53145 ** it was last placed, or has been invalidated for any other reason.
53146 ** Cursors can move when the row they are pointing at is deleted out
53147 ** from under them, for example. Cursor might also move if a btree
53148 ** is rebalanced.
53150 ** Calling this routine with a NULL cursor pointer returns false.
53152 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
53153 ** back to where it ought to be if this routine returns true.
53155 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
53156 return pCur->eState!=CURSOR_VALID;
53160 ** This routine restores a cursor back to its original position after it
53161 ** has been moved by some outside activity (such as a btree rebalance or
53162 ** a row having been deleted out from under the cursor).
53164 ** On success, the *pDifferentRow parameter is false if the cursor is left
53165 ** pointing at exactly the same row. *pDifferntRow is the row the cursor
53166 ** was pointing to has been deleted, forcing the cursor to point to some
53167 ** nearby row.
53169 ** This routine should only be called for a cursor that just returned
53170 ** TRUE from sqlite3BtreeCursorHasMoved().
53172 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
53173 int rc;
53175 assert( pCur!=0 );
53176 assert( pCur->eState!=CURSOR_VALID );
53177 rc = restoreCursorPosition(pCur);
53178 if( rc ){
53179 *pDifferentRow = 1;
53180 return rc;
53182 if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
53183 *pDifferentRow = 1;
53184 }else{
53185 *pDifferentRow = 0;
53187 return SQLITE_OK;
53190 #ifndef SQLITE_OMIT_AUTOVACUUM
53192 ** Given a page number of a regular database page, return the page
53193 ** number for the pointer-map page that contains the entry for the
53194 ** input page number.
53196 ** Return 0 (not a valid page) for pgno==1 since there is
53197 ** no pointer map associated with page 1. The integrity_check logic
53198 ** requires that ptrmapPageno(*,1)!=1.
53200 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
53201 int nPagesPerMapPage;
53202 Pgno iPtrMap, ret;
53203 assert( sqlite3_mutex_held(pBt->mutex) );
53204 if( pgno<2 ) return 0;
53205 nPagesPerMapPage = (pBt->usableSize/5)+1;
53206 iPtrMap = (pgno-2)/nPagesPerMapPage;
53207 ret = (iPtrMap*nPagesPerMapPage) + 2;
53208 if( ret==PENDING_BYTE_PAGE(pBt) ){
53209 ret++;
53211 return ret;
53215 ** Write an entry into the pointer map.
53217 ** This routine updates the pointer map entry for page number 'key'
53218 ** so that it maps to type 'eType' and parent page number 'pgno'.
53220 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
53221 ** a no-op. If an error occurs, the appropriate error code is written
53222 ** into *pRC.
53224 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
53225 DbPage *pDbPage; /* The pointer map page */
53226 u8 *pPtrmap; /* The pointer map data */
53227 Pgno iPtrmap; /* The pointer map page number */
53228 int offset; /* Offset in pointer map page */
53229 int rc; /* Return code from subfunctions */
53231 if( *pRC ) return;
53233 assert( sqlite3_mutex_held(pBt->mutex) );
53234 /* The master-journal page number must never be used as a pointer map page */
53235 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
53237 assert( pBt->autoVacuum );
53238 if( key==0 ){
53239 *pRC = SQLITE_CORRUPT_BKPT;
53240 return;
53242 iPtrmap = PTRMAP_PAGENO(pBt, key);
53243 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
53244 if( rc!=SQLITE_OK ){
53245 *pRC = rc;
53246 return;
53248 offset = PTRMAP_PTROFFSET(iPtrmap, key);
53249 if( offset<0 ){
53250 *pRC = SQLITE_CORRUPT_BKPT;
53251 goto ptrmap_exit;
53253 assert( offset <= (int)pBt->usableSize-5 );
53254 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
53256 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
53257 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
53258 *pRC= rc = sqlite3PagerWrite(pDbPage);
53259 if( rc==SQLITE_OK ){
53260 pPtrmap[offset] = eType;
53261 put4byte(&pPtrmap[offset+1], parent);
53265 ptrmap_exit:
53266 sqlite3PagerUnref(pDbPage);
53270 ** Read an entry from the pointer map.
53272 ** This routine retrieves the pointer map entry for page 'key', writing
53273 ** the type and parent page number to *pEType and *pPgno respectively.
53274 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
53276 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
53277 DbPage *pDbPage; /* The pointer map page */
53278 int iPtrmap; /* Pointer map page index */
53279 u8 *pPtrmap; /* Pointer map page data */
53280 int offset; /* Offset of entry in pointer map */
53281 int rc;
53283 assert( sqlite3_mutex_held(pBt->mutex) );
53285 iPtrmap = PTRMAP_PAGENO(pBt, key);
53286 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
53287 if( rc!=0 ){
53288 return rc;
53290 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
53292 offset = PTRMAP_PTROFFSET(iPtrmap, key);
53293 if( offset<0 ){
53294 sqlite3PagerUnref(pDbPage);
53295 return SQLITE_CORRUPT_BKPT;
53297 assert( offset <= (int)pBt->usableSize-5 );
53298 assert( pEType!=0 );
53299 *pEType = pPtrmap[offset];
53300 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
53302 sqlite3PagerUnref(pDbPage);
53303 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
53304 return SQLITE_OK;
53307 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
53308 #define ptrmapPut(w,x,y,z,rc)
53309 #define ptrmapGet(w,x,y,z) SQLITE_OK
53310 #define ptrmapPutOvflPtr(x, y, rc)
53311 #endif
53314 ** Given a btree page and a cell index (0 means the first cell on
53315 ** the page, 1 means the second cell, and so forth) return a pointer
53316 ** to the cell content.
53318 ** This routine works only for pages that do not contain overflow cells.
53320 #define findCell(P,I) \
53321 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
53322 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
53326 ** This a more complex version of findCell() that works for
53327 ** pages that do contain overflow cells.
53329 static u8 *findOverflowCell(MemPage *pPage, int iCell){
53330 int i;
53331 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53332 for(i=pPage->nOverflow-1; i>=0; i--){
53333 int k;
53334 k = pPage->aiOvfl[i];
53335 if( k<=iCell ){
53336 if( k==iCell ){
53337 return pPage->apOvfl[i];
53339 iCell--;
53342 return findCell(pPage, iCell);
53346 ** Parse a cell content block and fill in the CellInfo structure. There
53347 ** are two versions of this function. btreeParseCell() takes a
53348 ** cell index as the second argument and btreeParseCellPtr()
53349 ** takes a pointer to the body of the cell as its second argument.
53351 static void btreeParseCellPtr(
53352 MemPage *pPage, /* Page containing the cell */
53353 u8 *pCell, /* Pointer to the cell text. */
53354 CellInfo *pInfo /* Fill in this structure */
53356 u8 *pIter; /* For scanning through pCell */
53357 u32 nPayload; /* Number of bytes of cell payload */
53359 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53360 assert( pPage->leaf==0 || pPage->leaf==1 );
53361 if( pPage->intKeyLeaf ){
53362 assert( pPage->childPtrSize==0 );
53363 pIter = pCell + getVarint32(pCell, nPayload);
53364 pIter += getVarint(pIter, (u64*)&pInfo->nKey);
53365 }else if( pPage->noPayload ){
53366 assert( pPage->childPtrSize==4 );
53367 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
53368 pInfo->nPayload = 0;
53369 pInfo->nLocal = 0;
53370 pInfo->iOverflow = 0;
53371 pInfo->pPayload = 0;
53372 return;
53373 }else{
53374 pIter = pCell + pPage->childPtrSize;
53375 pIter += getVarint32(pIter, nPayload);
53376 pInfo->nKey = nPayload;
53378 pInfo->nPayload = nPayload;
53379 pInfo->pPayload = pIter;
53380 testcase( nPayload==pPage->maxLocal );
53381 testcase( nPayload==pPage->maxLocal+1 );
53382 if( nPayload<=pPage->maxLocal ){
53383 /* This is the (easy) common case where the entire payload fits
53384 ** on the local page. No overflow is required.
53386 pInfo->nSize = nPayload + (u16)(pIter - pCell);
53387 if( pInfo->nSize<4 ) pInfo->nSize = 4;
53388 pInfo->nLocal = (u16)nPayload;
53389 pInfo->iOverflow = 0;
53390 }else{
53391 /* If the payload will not fit completely on the local page, we have
53392 ** to decide how much to store locally and how much to spill onto
53393 ** overflow pages. The strategy is to minimize the amount of unused
53394 ** space on overflow pages while keeping the amount of local storage
53395 ** in between minLocal and maxLocal.
53397 ** Warning: changing the way overflow payload is distributed in any
53398 ** way will result in an incompatible file format.
53400 int minLocal; /* Minimum amount of payload held locally */
53401 int maxLocal; /* Maximum amount of payload held locally */
53402 int surplus; /* Overflow payload available for local storage */
53404 minLocal = pPage->minLocal;
53405 maxLocal = pPage->maxLocal;
53406 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
53407 testcase( surplus==maxLocal );
53408 testcase( surplus==maxLocal+1 );
53409 if( surplus <= maxLocal ){
53410 pInfo->nLocal = (u16)surplus;
53411 }else{
53412 pInfo->nLocal = (u16)minLocal;
53414 pInfo->iOverflow = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell);
53415 pInfo->nSize = pInfo->iOverflow + 4;
53418 static void btreeParseCell(
53419 MemPage *pPage, /* Page containing the cell */
53420 int iCell, /* The cell index. First cell is 0 */
53421 CellInfo *pInfo /* Fill in this structure */
53423 btreeParseCellPtr(pPage, findCell(pPage, iCell), pInfo);
53427 ** Compute the total number of bytes that a Cell needs in the cell
53428 ** data area of the btree-page. The return number includes the cell
53429 ** data header and the local payload, but not any overflow page or
53430 ** the space used by the cell pointer.
53432 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
53433 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
53434 u8 *pEnd; /* End mark for a varint */
53435 u32 nSize; /* Size value to return */
53437 #ifdef SQLITE_DEBUG
53438 /* The value returned by this function should always be the same as
53439 ** the (CellInfo.nSize) value found by doing a full parse of the
53440 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
53441 ** this function verifies that this invariant is not violated. */
53442 CellInfo debuginfo;
53443 btreeParseCellPtr(pPage, pCell, &debuginfo);
53444 #endif
53446 if( pPage->noPayload ){
53447 pEnd = &pIter[9];
53448 while( (*pIter++)&0x80 && pIter<pEnd );
53449 assert( pPage->childPtrSize==4 );
53450 return (u16)(pIter - pCell);
53452 nSize = *pIter;
53453 if( nSize>=0x80 ){
53454 pEnd = &pIter[9];
53455 nSize &= 0x7f;
53457 nSize = (nSize<<7) | (*++pIter & 0x7f);
53458 }while( *(pIter)>=0x80 && pIter<pEnd );
53460 pIter++;
53461 if( pPage->intKey ){
53462 /* pIter now points at the 64-bit integer key value, a variable length
53463 ** integer. The following block moves pIter to point at the first byte
53464 ** past the end of the key value. */
53465 pEnd = &pIter[9];
53466 while( (*pIter++)&0x80 && pIter<pEnd );
53468 testcase( nSize==pPage->maxLocal );
53469 testcase( nSize==pPage->maxLocal+1 );
53470 if( nSize<=pPage->maxLocal ){
53471 nSize += (u32)(pIter - pCell);
53472 if( nSize<4 ) nSize = 4;
53473 }else{
53474 int minLocal = pPage->minLocal;
53475 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
53476 testcase( nSize==pPage->maxLocal );
53477 testcase( nSize==pPage->maxLocal+1 );
53478 if( nSize>pPage->maxLocal ){
53479 nSize = minLocal;
53481 nSize += 4 + (u16)(pIter - pCell);
53483 assert( nSize==debuginfo.nSize || CORRUPT_DB );
53484 return (u16)nSize;
53487 #ifdef SQLITE_DEBUG
53488 /* This variation on cellSizePtr() is used inside of assert() statements
53489 ** only. */
53490 static u16 cellSize(MemPage *pPage, int iCell){
53491 return cellSizePtr(pPage, findCell(pPage, iCell));
53493 #endif
53495 #ifndef SQLITE_OMIT_AUTOVACUUM
53497 ** If the cell pCell, part of page pPage contains a pointer
53498 ** to an overflow page, insert an entry into the pointer-map
53499 ** for the overflow page.
53501 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
53502 CellInfo info;
53503 if( *pRC ) return;
53504 assert( pCell!=0 );
53505 btreeParseCellPtr(pPage, pCell, &info);
53506 if( info.iOverflow ){
53507 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
53508 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
53511 #endif
53515 ** Defragment the page given. All Cells are moved to the
53516 ** end of the page and all free space is collected into one
53517 ** big FreeBlk that occurs in between the header and cell
53518 ** pointer array and the cell content area.
53520 static int defragmentPage(MemPage *pPage){
53521 int i; /* Loop counter */
53522 int pc; /* Address of the i-th cell */
53523 int hdr; /* Offset to the page header */
53524 int size; /* Size of a cell */
53525 int usableSize; /* Number of usable bytes on a page */
53526 int cellOffset; /* Offset to the cell pointer array */
53527 int cbrk; /* Offset to the cell content area */
53528 int nCell; /* Number of cells on the page */
53529 unsigned char *data; /* The page data */
53530 unsigned char *temp; /* Temp area for cell content */
53531 int iCellFirst; /* First allowable cell index */
53532 int iCellLast; /* Last possible cell index */
53535 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53536 assert( pPage->pBt!=0 );
53537 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
53538 assert( pPage->nOverflow==0 );
53539 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53540 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
53541 data = pPage->aData;
53542 hdr = pPage->hdrOffset;
53543 cellOffset = pPage->cellOffset;
53544 nCell = pPage->nCell;
53545 assert( nCell==get2byte(&data[hdr+3]) );
53546 usableSize = pPage->pBt->usableSize;
53547 cbrk = get2byte(&data[hdr+5]);
53548 memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
53549 cbrk = usableSize;
53550 iCellFirst = cellOffset + 2*nCell;
53551 iCellLast = usableSize - 4;
53552 for(i=0; i<nCell; i++){
53553 u8 *pAddr; /* The i-th cell pointer */
53554 pAddr = &data[cellOffset + i*2];
53555 pc = get2byte(pAddr);
53556 testcase( pc==iCellFirst );
53557 testcase( pc==iCellLast );
53558 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
53559 /* These conditions have already been verified in btreeInitPage()
53560 ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
53562 if( pc<iCellFirst || pc>iCellLast ){
53563 return SQLITE_CORRUPT_BKPT;
53565 #endif
53566 assert( pc>=iCellFirst && pc<=iCellLast );
53567 size = cellSizePtr(pPage, &temp[pc]);
53568 cbrk -= size;
53569 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
53570 if( cbrk<iCellFirst ){
53571 return SQLITE_CORRUPT_BKPT;
53573 #else
53574 if( cbrk<iCellFirst || pc+size>usableSize ){
53575 return SQLITE_CORRUPT_BKPT;
53577 #endif
53578 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
53579 testcase( cbrk+size==usableSize );
53580 testcase( pc+size==usableSize );
53581 memcpy(&data[cbrk], &temp[pc], size);
53582 put2byte(pAddr, cbrk);
53584 assert( cbrk>=iCellFirst );
53585 put2byte(&data[hdr+5], cbrk);
53586 data[hdr+1] = 0;
53587 data[hdr+2] = 0;
53588 data[hdr+7] = 0;
53589 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
53590 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53591 if( cbrk-iCellFirst!=pPage->nFree ){
53592 return SQLITE_CORRUPT_BKPT;
53594 return SQLITE_OK;
53598 ** Allocate nByte bytes of space from within the B-Tree page passed
53599 ** as the first argument. Write into *pIdx the index into pPage->aData[]
53600 ** of the first byte of allocated space. Return either SQLITE_OK or
53601 ** an error code (usually SQLITE_CORRUPT).
53603 ** The caller guarantees that there is sufficient space to make the
53604 ** allocation. This routine might need to defragment in order to bring
53605 ** all the space together, however. This routine will avoid using
53606 ** the first two bytes past the cell pointer area since presumably this
53607 ** allocation is being made in order to insert a new cell, so we will
53608 ** also end up needing a new cell pointer.
53610 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
53611 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
53612 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
53613 int top; /* First byte of cell content area */
53614 int gap; /* First byte of gap between cell pointers and cell content */
53615 int rc; /* Integer return code */
53616 int usableSize; /* Usable size of the page */
53618 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53619 assert( pPage->pBt );
53620 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53621 assert( nByte>=0 ); /* Minimum cell size is 4 */
53622 assert( pPage->nFree>=nByte );
53623 assert( pPage->nOverflow==0 );
53624 usableSize = pPage->pBt->usableSize;
53625 assert( nByte < usableSize-8 );
53627 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
53628 gap = pPage->cellOffset + 2*pPage->nCell;
53629 assert( gap<=65536 );
53630 top = get2byte(&data[hdr+5]);
53631 if( gap>top ){
53632 if( top==0 ){
53633 top = 65536;
53634 }else{
53635 return SQLITE_CORRUPT_BKPT;
53639 /* If there is enough space between gap and top for one more cell pointer
53640 ** array entry offset, and if the freelist is not empty, then search the
53641 ** freelist looking for a free slot big enough to satisfy the request.
53643 testcase( gap+2==top );
53644 testcase( gap+1==top );
53645 testcase( gap==top );
53646 if( gap+2<=top && (data[hdr+1] || data[hdr+2]) ){
53647 int pc, addr;
53648 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
53649 int size; /* Size of the free slot */
53650 if( pc>usableSize-4 || pc<addr+4 ){
53651 return SQLITE_CORRUPT_BKPT;
53653 size = get2byte(&data[pc+2]);
53654 if( size>=nByte ){
53655 int x = size - nByte;
53656 testcase( x==4 );
53657 testcase( x==3 );
53658 if( x<4 ){
53659 if( data[hdr+7]>=60 ) goto defragment_page;
53660 /* Remove the slot from the free-list. Update the number of
53661 ** fragmented bytes within the page. */
53662 memcpy(&data[addr], &data[pc], 2);
53663 data[hdr+7] += (u8)x;
53664 }else if( size+pc > usableSize ){
53665 return SQLITE_CORRUPT_BKPT;
53666 }else{
53667 /* The slot remains on the free-list. Reduce its size to account
53668 ** for the portion used by the new allocation. */
53669 put2byte(&data[pc+2], x);
53671 *pIdx = pc + x;
53672 return SQLITE_OK;
53677 /* The request could not be fulfilled using a freelist slot. Check
53678 ** to see if defragmentation is necessary.
53680 testcase( gap+2+nByte==top );
53681 if( gap+2+nByte>top ){
53682 defragment_page:
53683 testcase( pPage->nCell==0 );
53684 rc = defragmentPage(pPage);
53685 if( rc ) return rc;
53686 top = get2byteNotZero(&data[hdr+5]);
53687 assert( gap+nByte<=top );
53691 /* Allocate memory from the gap in between the cell pointer array
53692 ** and the cell content area. The btreeInitPage() call has already
53693 ** validated the freelist. Given that the freelist is valid, there
53694 ** is no way that the allocation can extend off the end of the page.
53695 ** The assert() below verifies the previous sentence.
53697 top -= nByte;
53698 put2byte(&data[hdr+5], top);
53699 assert( top+nByte <= (int)pPage->pBt->usableSize );
53700 *pIdx = top;
53701 return SQLITE_OK;
53705 ** Return a section of the pPage->aData to the freelist.
53706 ** The first byte of the new free block is pPage->aData[iStart]
53707 ** and the size of the block is iSize bytes.
53709 ** Adjacent freeblocks are coalesced.
53711 ** Note that even though the freeblock list was checked by btreeInitPage(),
53712 ** that routine will not detect overlap between cells or freeblocks. Nor
53713 ** does it detect cells or freeblocks that encrouch into the reserved bytes
53714 ** at the end of the page. So do additional corruption checks inside this
53715 ** routine and return SQLITE_CORRUPT if any problems are found.
53717 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
53718 u16 iPtr; /* Address of ptr to next freeblock */
53719 u16 iFreeBlk; /* Address of the next freeblock */
53720 u8 hdr; /* Page header size. 0 or 100 */
53721 u8 nFrag = 0; /* Reduction in fragmentation */
53722 u16 iOrigSize = iSize; /* Original value of iSize */
53723 u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
53724 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
53725 unsigned char *data = pPage->aData; /* Page content */
53727 assert( pPage->pBt!=0 );
53728 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53729 assert( iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
53730 assert( iEnd <= pPage->pBt->usableSize );
53731 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53732 assert( iSize>=4 ); /* Minimum cell size is 4 */
53733 assert( iStart<=iLast );
53735 /* Overwrite deleted information with zeros when the secure_delete
53736 ** option is enabled */
53737 if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
53738 memset(&data[iStart], 0, iSize);
53741 /* The list of freeblocks must be in ascending order. Find the
53742 ** spot on the list where iStart should be inserted.
53744 hdr = pPage->hdrOffset;
53745 iPtr = hdr + 1;
53746 if( data[iPtr+1]==0 && data[iPtr]==0 ){
53747 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
53748 }else{
53749 while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
53750 if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
53751 iPtr = iFreeBlk;
53753 if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
53754 assert( iFreeBlk>iPtr || iFreeBlk==0 );
53756 /* At this point:
53757 ** iFreeBlk: First freeblock after iStart, or zero if none
53758 ** iPtr: The address of a pointer iFreeBlk
53760 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
53762 if( iFreeBlk && iEnd+3>=iFreeBlk ){
53763 nFrag = iFreeBlk - iEnd;
53764 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
53765 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
53766 iSize = iEnd - iStart;
53767 iFreeBlk = get2byte(&data[iFreeBlk]);
53770 /* If iPtr is another freeblock (that is, if iPtr is not the freelist
53771 ** pointer in the page header) then check to see if iStart should be
53772 ** coalesced onto the end of iPtr.
53774 if( iPtr>hdr+1 ){
53775 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
53776 if( iPtrEnd+3>=iStart ){
53777 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
53778 nFrag += iStart - iPtrEnd;
53779 iSize = iEnd - iPtr;
53780 iStart = iPtr;
53783 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
53784 data[hdr+7] -= nFrag;
53786 if( iStart==get2byte(&data[hdr+5]) ){
53787 /* The new freeblock is at the beginning of the cell content area,
53788 ** so just extend the cell content area rather than create another
53789 ** freelist entry */
53790 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
53791 put2byte(&data[hdr+1], iFreeBlk);
53792 put2byte(&data[hdr+5], iEnd);
53793 }else{
53794 /* Insert the new freeblock into the freelist */
53795 put2byte(&data[iPtr], iStart);
53796 put2byte(&data[iStart], iFreeBlk);
53797 put2byte(&data[iStart+2], iSize);
53799 pPage->nFree += iOrigSize;
53800 return SQLITE_OK;
53804 ** Decode the flags byte (the first byte of the header) for a page
53805 ** and initialize fields of the MemPage structure accordingly.
53807 ** Only the following combinations are supported. Anything different
53808 ** indicates a corrupt database files:
53810 ** PTF_ZERODATA
53811 ** PTF_ZERODATA | PTF_LEAF
53812 ** PTF_LEAFDATA | PTF_INTKEY
53813 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
53815 static int decodeFlags(MemPage *pPage, int flagByte){
53816 BtShared *pBt; /* A copy of pPage->pBt */
53818 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
53819 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53820 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
53821 flagByte &= ~PTF_LEAF;
53822 pPage->childPtrSize = 4-4*pPage->leaf;
53823 pBt = pPage->pBt;
53824 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
53825 pPage->intKey = 1;
53826 pPage->intKeyLeaf = pPage->leaf;
53827 pPage->noPayload = !pPage->leaf;
53828 pPage->maxLocal = pBt->maxLeaf;
53829 pPage->minLocal = pBt->minLeaf;
53830 }else if( flagByte==PTF_ZERODATA ){
53831 pPage->intKey = 0;
53832 pPage->intKeyLeaf = 0;
53833 pPage->noPayload = 0;
53834 pPage->maxLocal = pBt->maxLocal;
53835 pPage->minLocal = pBt->minLocal;
53836 }else{
53837 return SQLITE_CORRUPT_BKPT;
53839 pPage->max1bytePayload = pBt->max1bytePayload;
53840 return SQLITE_OK;
53844 ** Initialize the auxiliary information for a disk block.
53846 ** Return SQLITE_OK on success. If we see that the page does
53847 ** not contain a well-formed database page, then return
53848 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
53849 ** guarantee that the page is well-formed. It only shows that
53850 ** we failed to detect any corruption.
53852 static int btreeInitPage(MemPage *pPage){
53854 assert( pPage->pBt!=0 );
53855 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53856 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
53857 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
53858 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
53860 if( !pPage->isInit ){
53861 u16 pc; /* Address of a freeblock within pPage->aData[] */
53862 u8 hdr; /* Offset to beginning of page header */
53863 u8 *data; /* Equal to pPage->aData */
53864 BtShared *pBt; /* The main btree structure */
53865 int usableSize; /* Amount of usable space on each page */
53866 u16 cellOffset; /* Offset from start of page to first cell pointer */
53867 int nFree; /* Number of unused bytes on the page */
53868 int top; /* First byte of the cell content area */
53869 int iCellFirst; /* First allowable cell or freeblock offset */
53870 int iCellLast; /* Last possible cell or freeblock offset */
53872 pBt = pPage->pBt;
53874 hdr = pPage->hdrOffset;
53875 data = pPage->aData;
53876 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
53877 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
53878 pPage->maskPage = (u16)(pBt->pageSize - 1);
53879 pPage->nOverflow = 0;
53880 usableSize = pBt->usableSize;
53881 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
53882 pPage->aDataEnd = &data[usableSize];
53883 pPage->aCellIdx = &data[cellOffset];
53884 top = get2byteNotZero(&data[hdr+5]);
53885 pPage->nCell = get2byte(&data[hdr+3]);
53886 if( pPage->nCell>MX_CELL(pBt) ){
53887 /* To many cells for a single page. The page must be corrupt */
53888 return SQLITE_CORRUPT_BKPT;
53890 testcase( pPage->nCell==MX_CELL(pBt) );
53892 /* A malformed database page might cause us to read past the end
53893 ** of page when parsing a cell.
53895 ** The following block of code checks early to see if a cell extends
53896 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
53897 ** returned if it does.
53899 iCellFirst = cellOffset + 2*pPage->nCell;
53900 iCellLast = usableSize - 4;
53901 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
53903 int i; /* Index into the cell pointer array */
53904 int sz; /* Size of a cell */
53906 if( !pPage->leaf ) iCellLast--;
53907 for(i=0; i<pPage->nCell; i++){
53908 pc = get2byte(&data[cellOffset+i*2]);
53909 testcase( pc==iCellFirst );
53910 testcase( pc==iCellLast );
53911 if( pc<iCellFirst || pc>iCellLast ){
53912 return SQLITE_CORRUPT_BKPT;
53914 sz = cellSizePtr(pPage, &data[pc]);
53915 testcase( pc+sz==usableSize );
53916 if( pc+sz>usableSize ){
53917 return SQLITE_CORRUPT_BKPT;
53920 if( !pPage->leaf ) iCellLast++;
53922 #endif
53924 /* Compute the total free space on the page */
53925 pc = get2byte(&data[hdr+1]);
53926 nFree = data[hdr+7] + top;
53927 while( pc>0 ){
53928 u16 next, size;
53929 if( pc<iCellFirst || pc>iCellLast ){
53930 /* Start of free block is off the page */
53931 return SQLITE_CORRUPT_BKPT;
53933 next = get2byte(&data[pc]);
53934 size = get2byte(&data[pc+2]);
53935 if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
53936 /* Free blocks must be in ascending order. And the last byte of
53937 ** the free-block must lie on the database page. */
53938 return SQLITE_CORRUPT_BKPT;
53940 nFree = nFree + size;
53941 pc = next;
53944 /* At this point, nFree contains the sum of the offset to the start
53945 ** of the cell-content area plus the number of free bytes within
53946 ** the cell-content area. If this is greater than the usable-size
53947 ** of the page, then the page must be corrupted. This check also
53948 ** serves to verify that the offset to the start of the cell-content
53949 ** area, according to the page header, lies within the page.
53951 if( nFree>usableSize ){
53952 return SQLITE_CORRUPT_BKPT;
53954 pPage->nFree = (u16)(nFree - iCellFirst);
53955 pPage->isInit = 1;
53957 return SQLITE_OK;
53961 ** Set up a raw page so that it looks like a database page holding
53962 ** no entries.
53964 static void zeroPage(MemPage *pPage, int flags){
53965 unsigned char *data = pPage->aData;
53966 BtShared *pBt = pPage->pBt;
53967 u8 hdr = pPage->hdrOffset;
53968 u16 first;
53970 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
53971 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
53972 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
53973 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53974 assert( sqlite3_mutex_held(pBt->mutex) );
53975 if( pBt->btsFlags & BTS_SECURE_DELETE ){
53976 memset(&data[hdr], 0, pBt->usableSize - hdr);
53978 data[hdr] = (char)flags;
53979 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
53980 memset(&data[hdr+1], 0, 4);
53981 data[hdr+7] = 0;
53982 put2byte(&data[hdr+5], pBt->usableSize);
53983 pPage->nFree = (u16)(pBt->usableSize - first);
53984 decodeFlags(pPage, flags);
53985 pPage->cellOffset = first;
53986 pPage->aDataEnd = &data[pBt->usableSize];
53987 pPage->aCellIdx = &data[first];
53988 pPage->nOverflow = 0;
53989 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
53990 pPage->maskPage = (u16)(pBt->pageSize - 1);
53991 pPage->nCell = 0;
53992 pPage->isInit = 1;
53997 ** Convert a DbPage obtained from the pager into a MemPage used by
53998 ** the btree layer.
54000 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
54001 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
54002 pPage->aData = sqlite3PagerGetData(pDbPage);
54003 pPage->pDbPage = pDbPage;
54004 pPage->pBt = pBt;
54005 pPage->pgno = pgno;
54006 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
54007 return pPage;
54011 ** Get a page from the pager. Initialize the MemPage.pBt and
54012 ** MemPage.aData elements if needed.
54014 ** If the noContent flag is set, it means that we do not care about
54015 ** the content of the page at this time. So do not go to the disk
54016 ** to fetch the content. Just fill in the content with zeros for now.
54017 ** If in the future we call sqlite3PagerWrite() on this page, that
54018 ** means we have started to be concerned about content and the disk
54019 ** read should occur at that point.
54021 static int btreeGetPage(
54022 BtShared *pBt, /* The btree */
54023 Pgno pgno, /* Number of the page to fetch */
54024 MemPage **ppPage, /* Return the page in this parameter */
54025 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
54027 int rc;
54028 DbPage *pDbPage;
54030 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
54031 assert( sqlite3_mutex_held(pBt->mutex) );
54032 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
54033 if( rc ) return rc;
54034 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
54035 return SQLITE_OK;
54039 ** Retrieve a page from the pager cache. If the requested page is not
54040 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
54041 ** MemPage.aData elements if needed.
54043 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
54044 DbPage *pDbPage;
54045 assert( sqlite3_mutex_held(pBt->mutex) );
54046 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
54047 if( pDbPage ){
54048 return btreePageFromDbPage(pDbPage, pgno, pBt);
54050 return 0;
54054 ** Return the size of the database file in pages. If there is any kind of
54055 ** error, return ((unsigned int)-1).
54057 static Pgno btreePagecount(BtShared *pBt){
54058 return pBt->nPage;
54060 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
54061 assert( sqlite3BtreeHoldsMutex(p) );
54062 assert( ((p->pBt->nPage)&0x8000000)==0 );
54063 return btreePagecount(p->pBt);
54067 ** Get a page from the pager and initialize it. This routine is just a
54068 ** convenience wrapper around separate calls to btreeGetPage() and
54069 ** btreeInitPage().
54071 ** If an error occurs, then the value *ppPage is set to is undefined. It
54072 ** may remain unchanged, or it may be set to an invalid value.
54074 static int getAndInitPage(
54075 BtShared *pBt, /* The database file */
54076 Pgno pgno, /* Number of the page to get */
54077 MemPage **ppPage, /* Write the page pointer here */
54078 int bReadonly /* PAGER_GET_READONLY or 0 */
54080 int rc;
54081 assert( sqlite3_mutex_held(pBt->mutex) );
54082 assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
54084 if( pgno>btreePagecount(pBt) ){
54085 rc = SQLITE_CORRUPT_BKPT;
54086 }else{
54087 rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
54088 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
54089 rc = btreeInitPage(*ppPage);
54090 if( rc!=SQLITE_OK ){
54091 releasePage(*ppPage);
54096 testcase( pgno==0 );
54097 assert( pgno!=0 || rc==SQLITE_CORRUPT );
54098 return rc;
54102 ** Release a MemPage. This should be called once for each prior
54103 ** call to btreeGetPage.
54105 static void releasePage(MemPage *pPage){
54106 if( pPage ){
54107 assert( pPage->aData );
54108 assert( pPage->pBt );
54109 assert( pPage->pDbPage!=0 );
54110 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
54111 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
54112 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54113 sqlite3PagerUnrefNotNull(pPage->pDbPage);
54118 ** During a rollback, when the pager reloads information into the cache
54119 ** so that the cache is restored to its original state at the start of
54120 ** the transaction, for each page restored this routine is called.
54122 ** This routine needs to reset the extra data section at the end of the
54123 ** page to agree with the restored data.
54125 static void pageReinit(DbPage *pData){
54126 MemPage *pPage;
54127 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
54128 assert( sqlite3PagerPageRefcount(pData)>0 );
54129 if( pPage->isInit ){
54130 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54131 pPage->isInit = 0;
54132 if( sqlite3PagerPageRefcount(pData)>1 ){
54133 /* pPage might not be a btree page; it might be an overflow page
54134 ** or ptrmap page or a free page. In those cases, the following
54135 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
54136 ** But no harm is done by this. And it is very important that
54137 ** btreeInitPage() be called on every btree page so we make
54138 ** the call for every page that comes in for re-initing. */
54139 btreeInitPage(pPage);
54145 ** Invoke the busy handler for a btree.
54147 static int btreeInvokeBusyHandler(void *pArg){
54148 BtShared *pBt = (BtShared*)pArg;
54149 assert( pBt->db );
54150 assert( sqlite3_mutex_held(pBt->db->mutex) );
54151 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
54155 ** Open a database file.
54157 ** zFilename is the name of the database file. If zFilename is NULL
54158 ** then an ephemeral database is created. The ephemeral database might
54159 ** be exclusively in memory, or it might use a disk-based memory cache.
54160 ** Either way, the ephemeral database will be automatically deleted
54161 ** when sqlite3BtreeClose() is called.
54163 ** If zFilename is ":memory:" then an in-memory database is created
54164 ** that is automatically destroyed when it is closed.
54166 ** The "flags" parameter is a bitmask that might contain bits like
54167 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
54169 ** If the database is already opened in the same database connection
54170 ** and we are in shared cache mode, then the open will fail with an
54171 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
54172 ** objects in the same database connection since doing so will lead
54173 ** to problems with locking.
54175 SQLITE_PRIVATE int sqlite3BtreeOpen(
54176 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
54177 const char *zFilename, /* Name of the file containing the BTree database */
54178 sqlite3 *db, /* Associated database handle */
54179 Btree **ppBtree, /* Pointer to new Btree object written here */
54180 int flags, /* Options */
54181 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
54183 BtShared *pBt = 0; /* Shared part of btree structure */
54184 Btree *p; /* Handle to return */
54185 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
54186 int rc = SQLITE_OK; /* Result code from this function */
54187 u8 nReserve; /* Byte of unused space on each page */
54188 unsigned char zDbHeader[100]; /* Database header content */
54190 /* True if opening an ephemeral, temporary database */
54191 const int isTempDb = zFilename==0 || zFilename[0]==0;
54193 /* Set the variable isMemdb to true for an in-memory database, or
54194 ** false for a file-based database.
54196 #ifdef SQLITE_OMIT_MEMORYDB
54197 const int isMemdb = 0;
54198 #else
54199 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
54200 || (isTempDb && sqlite3TempInMemory(db))
54201 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
54202 #endif
54204 assert( db!=0 );
54205 assert( pVfs!=0 );
54206 assert( sqlite3_mutex_held(db->mutex) );
54207 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
54209 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
54210 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
54212 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
54213 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
54215 if( isMemdb ){
54216 flags |= BTREE_MEMORY;
54218 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
54219 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
54221 p = sqlite3MallocZero(sizeof(Btree));
54222 if( !p ){
54223 return SQLITE_NOMEM;
54225 p->inTrans = TRANS_NONE;
54226 p->db = db;
54227 #ifndef SQLITE_OMIT_SHARED_CACHE
54228 p->lock.pBtree = p;
54229 p->lock.iTable = 1;
54230 #endif
54232 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
54234 ** If this Btree is a candidate for shared cache, try to find an
54235 ** existing BtShared object that we can share with
54237 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
54238 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
54239 int nFullPathname = pVfs->mxPathname+1;
54240 char *zFullPathname = sqlite3Malloc(nFullPathname);
54241 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
54242 p->sharable = 1;
54243 if( !zFullPathname ){
54244 sqlite3_free(p);
54245 return SQLITE_NOMEM;
54247 if( isMemdb ){
54248 memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
54249 }else{
54250 rc = sqlite3OsFullPathname(pVfs, zFilename,
54251 nFullPathname, zFullPathname);
54252 if( rc ){
54253 sqlite3_free(zFullPathname);
54254 sqlite3_free(p);
54255 return rc;
54258 #if SQLITE_THREADSAFE
54259 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
54260 sqlite3_mutex_enter(mutexOpen);
54261 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
54262 sqlite3_mutex_enter(mutexShared);
54263 #endif
54264 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
54265 assert( pBt->nRef>0 );
54266 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
54267 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
54268 int iDb;
54269 for(iDb=db->nDb-1; iDb>=0; iDb--){
54270 Btree *pExisting = db->aDb[iDb].pBt;
54271 if( pExisting && pExisting->pBt==pBt ){
54272 sqlite3_mutex_leave(mutexShared);
54273 sqlite3_mutex_leave(mutexOpen);
54274 sqlite3_free(zFullPathname);
54275 sqlite3_free(p);
54276 return SQLITE_CONSTRAINT;
54279 p->pBt = pBt;
54280 pBt->nRef++;
54281 break;
54284 sqlite3_mutex_leave(mutexShared);
54285 sqlite3_free(zFullPathname);
54287 #ifdef SQLITE_DEBUG
54288 else{
54289 /* In debug mode, we mark all persistent databases as sharable
54290 ** even when they are not. This exercises the locking code and
54291 ** gives more opportunity for asserts(sqlite3_mutex_held())
54292 ** statements to find locking problems.
54294 p->sharable = 1;
54296 #endif
54298 #endif
54299 if( pBt==0 ){
54301 ** The following asserts make sure that structures used by the btree are
54302 ** the right size. This is to guard against size changes that result
54303 ** when compiling on a different architecture.
54305 assert( sizeof(i64)==8 || sizeof(i64)==4 );
54306 assert( sizeof(u64)==8 || sizeof(u64)==4 );
54307 assert( sizeof(u32)==4 );
54308 assert( sizeof(u16)==2 );
54309 assert( sizeof(Pgno)==4 );
54311 pBt = sqlite3MallocZero( sizeof(*pBt) );
54312 if( pBt==0 ){
54313 rc = SQLITE_NOMEM;
54314 goto btree_open_out;
54316 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
54317 EXTRA_SIZE, flags, vfsFlags, pageReinit);
54318 if( rc==SQLITE_OK ){
54319 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
54320 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
54322 if( rc!=SQLITE_OK ){
54323 goto btree_open_out;
54325 pBt->openFlags = (u8)flags;
54326 pBt->db = db;
54327 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
54328 p->pBt = pBt;
54330 pBt->pCursor = 0;
54331 pBt->pPage1 = 0;
54332 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
54333 #ifdef SQLITE_SECURE_DELETE
54334 pBt->btsFlags |= BTS_SECURE_DELETE;
54335 #endif
54336 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
54337 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
54338 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
54339 pBt->pageSize = 0;
54340 #ifndef SQLITE_OMIT_AUTOVACUUM
54341 /* If the magic name ":memory:" will create an in-memory database, then
54342 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
54343 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
54344 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
54345 ** regular file-name. In this case the auto-vacuum applies as per normal.
54347 if( zFilename && !isMemdb ){
54348 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
54349 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
54351 #endif
54352 nReserve = 0;
54353 }else{
54354 nReserve = zDbHeader[20];
54355 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
54356 #ifndef SQLITE_OMIT_AUTOVACUUM
54357 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
54358 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
54359 #endif
54361 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
54362 if( rc ) goto btree_open_out;
54363 pBt->usableSize = pBt->pageSize - nReserve;
54364 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
54366 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
54367 /* Add the new BtShared object to the linked list sharable BtShareds.
54369 if( p->sharable ){
54370 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
54371 pBt->nRef = 1;
54372 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
54373 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
54374 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
54375 if( pBt->mutex==0 ){
54376 rc = SQLITE_NOMEM;
54377 db->mallocFailed = 0;
54378 goto btree_open_out;
54381 sqlite3_mutex_enter(mutexShared);
54382 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
54383 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
54384 sqlite3_mutex_leave(mutexShared);
54386 #endif
54389 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
54390 /* If the new Btree uses a sharable pBtShared, then link the new
54391 ** Btree into the list of all sharable Btrees for the same connection.
54392 ** The list is kept in ascending order by pBt address.
54394 if( p->sharable ){
54395 int i;
54396 Btree *pSib;
54397 for(i=0; i<db->nDb; i++){
54398 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
54399 while( pSib->pPrev ){ pSib = pSib->pPrev; }
54400 if( p->pBt<pSib->pBt ){
54401 p->pNext = pSib;
54402 p->pPrev = 0;
54403 pSib->pPrev = p;
54404 }else{
54405 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
54406 pSib = pSib->pNext;
54408 p->pNext = pSib->pNext;
54409 p->pPrev = pSib;
54410 if( p->pNext ){
54411 p->pNext->pPrev = p;
54413 pSib->pNext = p;
54415 break;
54419 #endif
54420 *ppBtree = p;
54422 btree_open_out:
54423 if( rc!=SQLITE_OK ){
54424 if( pBt && pBt->pPager ){
54425 sqlite3PagerClose(pBt->pPager);
54427 sqlite3_free(pBt);
54428 sqlite3_free(p);
54429 *ppBtree = 0;
54430 }else{
54431 /* If the B-Tree was successfully opened, set the pager-cache size to the
54432 ** default value. Except, when opening on an existing shared pager-cache,
54433 ** do not change the pager-cache size.
54435 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
54436 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
54439 if( mutexOpen ){
54440 assert( sqlite3_mutex_held(mutexOpen) );
54441 sqlite3_mutex_leave(mutexOpen);
54443 return rc;
54447 ** Decrement the BtShared.nRef counter. When it reaches zero,
54448 ** remove the BtShared structure from the sharing list. Return
54449 ** true if the BtShared.nRef counter reaches zero and return
54450 ** false if it is still positive.
54452 static int removeFromSharingList(BtShared *pBt){
54453 #ifndef SQLITE_OMIT_SHARED_CACHE
54454 MUTEX_LOGIC( sqlite3_mutex *pMaster; )
54455 BtShared *pList;
54456 int removed = 0;
54458 assert( sqlite3_mutex_notheld(pBt->mutex) );
54459 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
54460 sqlite3_mutex_enter(pMaster);
54461 pBt->nRef--;
54462 if( pBt->nRef<=0 ){
54463 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
54464 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
54465 }else{
54466 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
54467 while( ALWAYS(pList) && pList->pNext!=pBt ){
54468 pList=pList->pNext;
54470 if( ALWAYS(pList) ){
54471 pList->pNext = pBt->pNext;
54474 if( SQLITE_THREADSAFE ){
54475 sqlite3_mutex_free(pBt->mutex);
54477 removed = 1;
54479 sqlite3_mutex_leave(pMaster);
54480 return removed;
54481 #else
54482 return 1;
54483 #endif
54487 ** Make sure pBt->pTmpSpace points to an allocation of
54488 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
54489 ** pointer.
54491 static void allocateTempSpace(BtShared *pBt){
54492 if( !pBt->pTmpSpace ){
54493 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
54495 /* One of the uses of pBt->pTmpSpace is to format cells before
54496 ** inserting them into a leaf page (function fillInCell()). If
54497 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
54498 ** by the various routines that manipulate binary cells. Which
54499 ** can mean that fillInCell() only initializes the first 2 or 3
54500 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
54501 ** it into a database page. This is not actually a problem, but it
54502 ** does cause a valgrind error when the 1 or 2 bytes of unitialized
54503 ** data is passed to system call write(). So to avoid this error,
54504 ** zero the first 4 bytes of temp space here.
54506 ** Also: Provide four bytes of initialized space before the
54507 ** beginning of pTmpSpace as an area available to prepend the
54508 ** left-child pointer to the beginning of a cell.
54510 if( pBt->pTmpSpace ){
54511 memset(pBt->pTmpSpace, 0, 8);
54512 pBt->pTmpSpace += 4;
54518 ** Free the pBt->pTmpSpace allocation
54520 static void freeTempSpace(BtShared *pBt){
54521 if( pBt->pTmpSpace ){
54522 pBt->pTmpSpace -= 4;
54523 sqlite3PageFree(pBt->pTmpSpace);
54524 pBt->pTmpSpace = 0;
54529 ** Close an open database and invalidate all cursors.
54531 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
54532 BtShared *pBt = p->pBt;
54533 BtCursor *pCur;
54535 /* Close all cursors opened via this handle. */
54536 assert( sqlite3_mutex_held(p->db->mutex) );
54537 sqlite3BtreeEnter(p);
54538 pCur = pBt->pCursor;
54539 while( pCur ){
54540 BtCursor *pTmp = pCur;
54541 pCur = pCur->pNext;
54542 if( pTmp->pBtree==p ){
54543 sqlite3BtreeCloseCursor(pTmp);
54547 /* Rollback any active transaction and free the handle structure.
54548 ** The call to sqlite3BtreeRollback() drops any table-locks held by
54549 ** this handle.
54551 sqlite3BtreeRollback(p, SQLITE_OK, 0);
54552 sqlite3BtreeLeave(p);
54554 /* If there are still other outstanding references to the shared-btree
54555 ** structure, return now. The remainder of this procedure cleans
54556 ** up the shared-btree.
54558 assert( p->wantToLock==0 && p->locked==0 );
54559 if( !p->sharable || removeFromSharingList(pBt) ){
54560 /* The pBt is no longer on the sharing list, so we can access
54561 ** it without having to hold the mutex.
54563 ** Clean out and delete the BtShared object.
54565 assert( !pBt->pCursor );
54566 sqlite3PagerClose(pBt->pPager);
54567 if( pBt->xFreeSchema && pBt->pSchema ){
54568 pBt->xFreeSchema(pBt->pSchema);
54570 sqlite3DbFree(0, pBt->pSchema);
54571 freeTempSpace(pBt);
54572 sqlite3_free(pBt);
54575 #ifndef SQLITE_OMIT_SHARED_CACHE
54576 assert( p->wantToLock==0 );
54577 assert( p->locked==0 );
54578 if( p->pPrev ) p->pPrev->pNext = p->pNext;
54579 if( p->pNext ) p->pNext->pPrev = p->pPrev;
54580 #endif
54582 sqlite3_free(p);
54583 return SQLITE_OK;
54587 ** Change the limit on the number of pages allowed in the cache.
54589 ** The maximum number of cache pages is set to the absolute
54590 ** value of mxPage. If mxPage is negative, the pager will
54591 ** operate asynchronously - it will not stop to do fsync()s
54592 ** to insure data is written to the disk surface before
54593 ** continuing. Transactions still work if synchronous is off,
54594 ** and the database cannot be corrupted if this program
54595 ** crashes. But if the operating system crashes or there is
54596 ** an abrupt power failure when synchronous is off, the database
54597 ** could be left in an inconsistent and unrecoverable state.
54598 ** Synchronous is on by default so database corruption is not
54599 ** normally a worry.
54601 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
54602 BtShared *pBt = p->pBt;
54603 assert( sqlite3_mutex_held(p->db->mutex) );
54604 sqlite3BtreeEnter(p);
54605 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
54606 sqlite3BtreeLeave(p);
54607 return SQLITE_OK;
54610 #if SQLITE_MAX_MMAP_SIZE>0
54612 ** Change the limit on the amount of the database file that may be
54613 ** memory mapped.
54615 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
54616 BtShared *pBt = p->pBt;
54617 assert( sqlite3_mutex_held(p->db->mutex) );
54618 sqlite3BtreeEnter(p);
54619 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
54620 sqlite3BtreeLeave(p);
54621 return SQLITE_OK;
54623 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
54626 ** Change the way data is synced to disk in order to increase or decrease
54627 ** how well the database resists damage due to OS crashes and power
54628 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
54629 ** there is a high probability of damage) Level 2 is the default. There
54630 ** is a very low but non-zero probability of damage. Level 3 reduces the
54631 ** probability of damage to near zero but with a write performance reduction.
54633 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
54634 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
54635 Btree *p, /* The btree to set the safety level on */
54636 unsigned pgFlags /* Various PAGER_* flags */
54638 BtShared *pBt = p->pBt;
54639 assert( sqlite3_mutex_held(p->db->mutex) );
54640 sqlite3BtreeEnter(p);
54641 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
54642 sqlite3BtreeLeave(p);
54643 return SQLITE_OK;
54645 #endif
54648 ** Return TRUE if the given btree is set to safety level 1. In other
54649 ** words, return TRUE if no sync() occurs on the disk files.
54651 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
54652 BtShared *pBt = p->pBt;
54653 int rc;
54654 assert( sqlite3_mutex_held(p->db->mutex) );
54655 sqlite3BtreeEnter(p);
54656 assert( pBt && pBt->pPager );
54657 rc = sqlite3PagerNosync(pBt->pPager);
54658 sqlite3BtreeLeave(p);
54659 return rc;
54663 ** Change the default pages size and the number of reserved bytes per page.
54664 ** Or, if the page size has already been fixed, return SQLITE_READONLY
54665 ** without changing anything.
54667 ** The page size must be a power of 2 between 512 and 65536. If the page
54668 ** size supplied does not meet this constraint then the page size is not
54669 ** changed.
54671 ** Page sizes are constrained to be a power of two so that the region
54672 ** of the database file used for locking (beginning at PENDING_BYTE,
54673 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
54674 ** at the beginning of a page.
54676 ** If parameter nReserve is less than zero, then the number of reserved
54677 ** bytes per page is left unchanged.
54679 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
54680 ** and autovacuum mode can no longer be changed.
54682 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
54683 int rc = SQLITE_OK;
54684 BtShared *pBt = p->pBt;
54685 assert( nReserve>=-1 && nReserve<=255 );
54686 sqlite3BtreeEnter(p);
54687 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
54688 sqlite3BtreeLeave(p);
54689 return SQLITE_READONLY;
54691 if( nReserve<0 ){
54692 nReserve = pBt->pageSize - pBt->usableSize;
54694 assert( nReserve>=0 && nReserve<=255 );
54695 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
54696 ((pageSize-1)&pageSize)==0 ){
54697 assert( (pageSize & 7)==0 );
54698 assert( !pBt->pPage1 && !pBt->pCursor );
54699 pBt->pageSize = (u32)pageSize;
54700 freeTempSpace(pBt);
54702 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
54703 pBt->usableSize = pBt->pageSize - (u16)nReserve;
54704 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
54705 sqlite3BtreeLeave(p);
54706 return rc;
54710 ** Return the currently defined page size
54712 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
54713 return p->pBt->pageSize;
54716 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
54718 ** This function is similar to sqlite3BtreeGetReserve(), except that it
54719 ** may only be called if it is guaranteed that the b-tree mutex is already
54720 ** held.
54722 ** This is useful in one special case in the backup API code where it is
54723 ** known that the shared b-tree mutex is held, but the mutex on the
54724 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
54725 ** were to be called, it might collide with some other operation on the
54726 ** database handle that owns *p, causing undefined behavior.
54728 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
54729 assert( sqlite3_mutex_held(p->pBt->mutex) );
54730 return p->pBt->pageSize - p->pBt->usableSize;
54732 #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
54734 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
54736 ** Return the number of bytes of space at the end of every page that
54737 ** are intentually left unused. This is the "reserved" space that is
54738 ** sometimes used by extensions.
54740 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
54741 int n;
54742 sqlite3BtreeEnter(p);
54743 n = p->pBt->pageSize - p->pBt->usableSize;
54744 sqlite3BtreeLeave(p);
54745 return n;
54749 ** Set the maximum page count for a database if mxPage is positive.
54750 ** No changes are made if mxPage is 0 or negative.
54751 ** Regardless of the value of mxPage, return the maximum page count.
54753 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
54754 int n;
54755 sqlite3BtreeEnter(p);
54756 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
54757 sqlite3BtreeLeave(p);
54758 return n;
54762 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
54763 ** then make no changes. Always return the value of the BTS_SECURE_DELETE
54764 ** setting after the change.
54766 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
54767 int b;
54768 if( p==0 ) return 0;
54769 sqlite3BtreeEnter(p);
54770 if( newFlag>=0 ){
54771 p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
54772 if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
54774 b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
54775 sqlite3BtreeLeave(p);
54776 return b;
54778 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
54781 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
54782 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
54783 ** is disabled. The default value for the auto-vacuum property is
54784 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
54786 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
54787 #ifdef SQLITE_OMIT_AUTOVACUUM
54788 return SQLITE_READONLY;
54789 #else
54790 BtShared *pBt = p->pBt;
54791 int rc = SQLITE_OK;
54792 u8 av = (u8)autoVacuum;
54794 sqlite3BtreeEnter(p);
54795 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
54796 rc = SQLITE_READONLY;
54797 }else{
54798 pBt->autoVacuum = av ?1:0;
54799 pBt->incrVacuum = av==2 ?1:0;
54801 sqlite3BtreeLeave(p);
54802 return rc;
54803 #endif
54807 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
54808 ** enabled 1 is returned. Otherwise 0.
54810 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
54811 #ifdef SQLITE_OMIT_AUTOVACUUM
54812 return BTREE_AUTOVACUUM_NONE;
54813 #else
54814 int rc;
54815 sqlite3BtreeEnter(p);
54816 rc = (
54817 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
54818 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
54819 BTREE_AUTOVACUUM_INCR
54821 sqlite3BtreeLeave(p);
54822 return rc;
54823 #endif
54828 ** Get a reference to pPage1 of the database file. This will
54829 ** also acquire a readlock on that file.
54831 ** SQLITE_OK is returned on success. If the file is not a
54832 ** well-formed database file, then SQLITE_CORRUPT is returned.
54833 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
54834 ** is returned if we run out of memory.
54836 static int lockBtree(BtShared *pBt){
54837 int rc; /* Result code from subfunctions */
54838 MemPage *pPage1; /* Page 1 of the database file */
54839 int nPage; /* Number of pages in the database */
54840 int nPageFile = 0; /* Number of pages in the database file */
54841 int nPageHeader; /* Number of pages in the database according to hdr */
54843 assert( sqlite3_mutex_held(pBt->mutex) );
54844 assert( pBt->pPage1==0 );
54845 rc = sqlite3PagerSharedLock(pBt->pPager);
54846 if( rc!=SQLITE_OK ) return rc;
54847 rc = btreeGetPage(pBt, 1, &pPage1, 0);
54848 if( rc!=SQLITE_OK ) return rc;
54850 /* Do some checking to help insure the file we opened really is
54851 ** a valid database file.
54853 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
54854 sqlite3PagerPagecount(pBt->pPager, &nPageFile);
54855 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
54856 nPage = nPageFile;
54858 if( nPage>0 ){
54859 u32 pageSize;
54860 u32 usableSize;
54861 u8 *page1 = pPage1->aData;
54862 rc = SQLITE_NOTADB;
54863 if( memcmp(page1, zMagicHeader, 16)!=0 ){
54864 goto page1_init_failed;
54867 #ifdef SQLITE_OMIT_WAL
54868 if( page1[18]>1 ){
54869 pBt->btsFlags |= BTS_READ_ONLY;
54871 if( page1[19]>1 ){
54872 goto page1_init_failed;
54874 #else
54875 if( page1[18]>2 ){
54876 pBt->btsFlags |= BTS_READ_ONLY;
54878 if( page1[19]>2 ){
54879 goto page1_init_failed;
54882 /* If the write version is set to 2, this database should be accessed
54883 ** in WAL mode. If the log is not already open, open it now. Then
54884 ** return SQLITE_OK and return without populating BtShared.pPage1.
54885 ** The caller detects this and calls this function again. This is
54886 ** required as the version of page 1 currently in the page1 buffer
54887 ** may not be the latest version - there may be a newer one in the log
54888 ** file.
54890 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
54891 int isOpen = 0;
54892 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
54893 if( rc!=SQLITE_OK ){
54894 goto page1_init_failed;
54895 }else if( isOpen==0 ){
54896 releasePage(pPage1);
54897 return SQLITE_OK;
54899 rc = SQLITE_NOTADB;
54901 #endif
54903 /* The maximum embedded fraction must be exactly 25%. And the minimum
54904 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
54905 ** The original design allowed these amounts to vary, but as of
54906 ** version 3.6.0, we require them to be fixed.
54908 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
54909 goto page1_init_failed;
54911 pageSize = (page1[16]<<8) | (page1[17]<<16);
54912 if( ((pageSize-1)&pageSize)!=0
54913 || pageSize>SQLITE_MAX_PAGE_SIZE
54914 || pageSize<=256
54916 goto page1_init_failed;
54918 assert( (pageSize & 7)==0 );
54919 usableSize = pageSize - page1[20];
54920 if( (u32)pageSize!=pBt->pageSize ){
54921 /* After reading the first page of the database assuming a page size
54922 ** of BtShared.pageSize, we have discovered that the page-size is
54923 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
54924 ** zero and return SQLITE_OK. The caller will call this function
54925 ** again with the correct page-size.
54927 releasePage(pPage1);
54928 pBt->usableSize = usableSize;
54929 pBt->pageSize = pageSize;
54930 freeTempSpace(pBt);
54931 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
54932 pageSize-usableSize);
54933 return rc;
54935 if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
54936 rc = SQLITE_CORRUPT_BKPT;
54937 goto page1_init_failed;
54939 if( usableSize<480 ){
54940 goto page1_init_failed;
54942 pBt->pageSize = pageSize;
54943 pBt->usableSize = usableSize;
54944 #ifndef SQLITE_OMIT_AUTOVACUUM
54945 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
54946 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
54947 #endif
54950 /* maxLocal is the maximum amount of payload to store locally for
54951 ** a cell. Make sure it is small enough so that at least minFanout
54952 ** cells can will fit on one page. We assume a 10-byte page header.
54953 ** Besides the payload, the cell must store:
54954 ** 2-byte pointer to the cell
54955 ** 4-byte child pointer
54956 ** 9-byte nKey value
54957 ** 4-byte nData value
54958 ** 4-byte overflow page pointer
54959 ** So a cell consists of a 2-byte pointer, a header which is as much as
54960 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
54961 ** page pointer.
54963 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
54964 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
54965 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
54966 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
54967 if( pBt->maxLocal>127 ){
54968 pBt->max1bytePayload = 127;
54969 }else{
54970 pBt->max1bytePayload = (u8)pBt->maxLocal;
54972 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
54973 pBt->pPage1 = pPage1;
54974 pBt->nPage = nPage;
54975 return SQLITE_OK;
54977 page1_init_failed:
54978 releasePage(pPage1);
54979 pBt->pPage1 = 0;
54980 return rc;
54983 #ifndef NDEBUG
54985 ** Return the number of cursors open on pBt. This is for use
54986 ** in assert() expressions, so it is only compiled if NDEBUG is not
54987 ** defined.
54989 ** Only write cursors are counted if wrOnly is true. If wrOnly is
54990 ** false then all cursors are counted.
54992 ** For the purposes of this routine, a cursor is any cursor that
54993 ** is capable of reading or writing to the database. Cursors that
54994 ** have been tripped into the CURSOR_FAULT state are not counted.
54996 static int countValidCursors(BtShared *pBt, int wrOnly){
54997 BtCursor *pCur;
54998 int r = 0;
54999 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
55000 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
55001 && pCur->eState!=CURSOR_FAULT ) r++;
55003 return r;
55005 #endif
55008 ** If there are no outstanding cursors and we are not in the middle
55009 ** of a transaction but there is a read lock on the database, then
55010 ** this routine unrefs the first page of the database file which
55011 ** has the effect of releasing the read lock.
55013 ** If there is a transaction in progress, this routine is a no-op.
55015 static void unlockBtreeIfUnused(BtShared *pBt){
55016 assert( sqlite3_mutex_held(pBt->mutex) );
55017 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
55018 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
55019 MemPage *pPage1 = pBt->pPage1;
55020 assert( pPage1->aData );
55021 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
55022 pBt->pPage1 = 0;
55023 releasePage(pPage1);
55028 ** If pBt points to an empty file then convert that empty file
55029 ** into a new empty database by initializing the first page of
55030 ** the database.
55032 static int newDatabase(BtShared *pBt){
55033 MemPage *pP1;
55034 unsigned char *data;
55035 int rc;
55037 assert( sqlite3_mutex_held(pBt->mutex) );
55038 if( pBt->nPage>0 ){
55039 return SQLITE_OK;
55041 pP1 = pBt->pPage1;
55042 assert( pP1!=0 );
55043 data = pP1->aData;
55044 rc = sqlite3PagerWrite(pP1->pDbPage);
55045 if( rc ) return rc;
55046 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
55047 assert( sizeof(zMagicHeader)==16 );
55048 data[16] = (u8)((pBt->pageSize>>8)&0xff);
55049 data[17] = (u8)((pBt->pageSize>>16)&0xff);
55050 data[18] = 1;
55051 data[19] = 1;
55052 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
55053 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
55054 data[21] = 64;
55055 data[22] = 32;
55056 data[23] = 32;
55057 memset(&data[24], 0, 100-24);
55058 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
55059 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
55060 #ifndef SQLITE_OMIT_AUTOVACUUM
55061 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
55062 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
55063 put4byte(&data[36 + 4*4], pBt->autoVacuum);
55064 put4byte(&data[36 + 7*4], pBt->incrVacuum);
55065 #endif
55066 pBt->nPage = 1;
55067 data[31] = 1;
55068 return SQLITE_OK;
55072 ** Initialize the first page of the database file (creating a database
55073 ** consisting of a single page and no schema objects). Return SQLITE_OK
55074 ** if successful, or an SQLite error code otherwise.
55076 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
55077 int rc;
55078 sqlite3BtreeEnter(p);
55079 p->pBt->nPage = 0;
55080 rc = newDatabase(p->pBt);
55081 sqlite3BtreeLeave(p);
55082 return rc;
55086 ** Attempt to start a new transaction. A write-transaction
55087 ** is started if the second argument is nonzero, otherwise a read-
55088 ** transaction. If the second argument is 2 or more and exclusive
55089 ** transaction is started, meaning that no other process is allowed
55090 ** to access the database. A preexisting transaction may not be
55091 ** upgraded to exclusive by calling this routine a second time - the
55092 ** exclusivity flag only works for a new transaction.
55094 ** A write-transaction must be started before attempting any
55095 ** changes to the database. None of the following routines
55096 ** will work unless a transaction is started first:
55098 ** sqlite3BtreeCreateTable()
55099 ** sqlite3BtreeCreateIndex()
55100 ** sqlite3BtreeClearTable()
55101 ** sqlite3BtreeDropTable()
55102 ** sqlite3BtreeInsert()
55103 ** sqlite3BtreeDelete()
55104 ** sqlite3BtreeUpdateMeta()
55106 ** If an initial attempt to acquire the lock fails because of lock contention
55107 ** and the database was previously unlocked, then invoke the busy handler
55108 ** if there is one. But if there was previously a read-lock, do not
55109 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
55110 ** returned when there is already a read-lock in order to avoid a deadlock.
55112 ** Suppose there are two processes A and B. A has a read lock and B has
55113 ** a reserved lock. B tries to promote to exclusive but is blocked because
55114 ** of A's read lock. A tries to promote to reserved but is blocked by B.
55115 ** One or the other of the two processes must give way or there can be
55116 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
55117 ** when A already has a read lock, we encourage A to give up and let B
55118 ** proceed.
55120 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
55121 sqlite3 *pBlock = 0;
55122 BtShared *pBt = p->pBt;
55123 int rc = SQLITE_OK;
55125 sqlite3BtreeEnter(p);
55126 btreeIntegrity(p);
55128 /* If the btree is already in a write-transaction, or it
55129 ** is already in a read-transaction and a read-transaction
55130 ** is requested, this is a no-op.
55132 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
55133 goto trans_begun;
55135 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
55137 /* Write transactions are not possible on a read-only database */
55138 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
55139 rc = SQLITE_READONLY;
55140 goto trans_begun;
55143 #ifndef SQLITE_OMIT_SHARED_CACHE
55144 /* If another database handle has already opened a write transaction
55145 ** on this shared-btree structure and a second write transaction is
55146 ** requested, return SQLITE_LOCKED.
55148 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
55149 || (pBt->btsFlags & BTS_PENDING)!=0
55151 pBlock = pBt->pWriter->db;
55152 }else if( wrflag>1 ){
55153 BtLock *pIter;
55154 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
55155 if( pIter->pBtree!=p ){
55156 pBlock = pIter->pBtree->db;
55157 break;
55161 if( pBlock ){
55162 sqlite3ConnectionBlocked(p->db, pBlock);
55163 rc = SQLITE_LOCKED_SHAREDCACHE;
55164 goto trans_begun;
55166 #endif
55168 /* Any read-only or read-write transaction implies a read-lock on
55169 ** page 1. So if some other shared-cache client already has a write-lock
55170 ** on page 1, the transaction cannot be opened. */
55171 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
55172 if( SQLITE_OK!=rc ) goto trans_begun;
55174 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
55175 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
55176 do {
55177 /* Call lockBtree() until either pBt->pPage1 is populated or
55178 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
55179 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
55180 ** reading page 1 it discovers that the page-size of the database
55181 ** file is not pBt->pageSize. In this case lockBtree() will update
55182 ** pBt->pageSize to the page-size of the file on disk.
55184 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
55186 if( rc==SQLITE_OK && wrflag ){
55187 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
55188 rc = SQLITE_READONLY;
55189 }else{
55190 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
55191 if( rc==SQLITE_OK ){
55192 rc = newDatabase(pBt);
55197 if( rc!=SQLITE_OK ){
55198 unlockBtreeIfUnused(pBt);
55200 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
55201 btreeInvokeBusyHandler(pBt) );
55203 if( rc==SQLITE_OK ){
55204 if( p->inTrans==TRANS_NONE ){
55205 pBt->nTransaction++;
55206 #ifndef SQLITE_OMIT_SHARED_CACHE
55207 if( p->sharable ){
55208 assert( p->lock.pBtree==p && p->lock.iTable==1 );
55209 p->lock.eLock = READ_LOCK;
55210 p->lock.pNext = pBt->pLock;
55211 pBt->pLock = &p->lock;
55213 #endif
55215 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
55216 if( p->inTrans>pBt->inTransaction ){
55217 pBt->inTransaction = p->inTrans;
55219 if( wrflag ){
55220 MemPage *pPage1 = pBt->pPage1;
55221 #ifndef SQLITE_OMIT_SHARED_CACHE
55222 assert( !pBt->pWriter );
55223 pBt->pWriter = p;
55224 pBt->btsFlags &= ~BTS_EXCLUSIVE;
55225 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
55226 #endif
55228 /* If the db-size header field is incorrect (as it may be if an old
55229 ** client has been writing the database file), update it now. Doing
55230 ** this sooner rather than later means the database size can safely
55231 ** re-read the database size from page 1 if a savepoint or transaction
55232 ** rollback occurs within the transaction.
55234 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
55235 rc = sqlite3PagerWrite(pPage1->pDbPage);
55236 if( rc==SQLITE_OK ){
55237 put4byte(&pPage1->aData[28], pBt->nPage);
55244 trans_begun:
55245 if( rc==SQLITE_OK && wrflag ){
55246 /* This call makes sure that the pager has the correct number of
55247 ** open savepoints. If the second parameter is greater than 0 and
55248 ** the sub-journal is not already open, then it will be opened here.
55250 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
55253 btreeIntegrity(p);
55254 sqlite3BtreeLeave(p);
55255 return rc;
55258 #ifndef SQLITE_OMIT_AUTOVACUUM
55261 ** Set the pointer-map entries for all children of page pPage. Also, if
55262 ** pPage contains cells that point to overflow pages, set the pointer
55263 ** map entries for the overflow pages as well.
55265 static int setChildPtrmaps(MemPage *pPage){
55266 int i; /* Counter variable */
55267 int nCell; /* Number of cells in page pPage */
55268 int rc; /* Return code */
55269 BtShared *pBt = pPage->pBt;
55270 u8 isInitOrig = pPage->isInit;
55271 Pgno pgno = pPage->pgno;
55273 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55274 rc = btreeInitPage(pPage);
55275 if( rc!=SQLITE_OK ){
55276 goto set_child_ptrmaps_out;
55278 nCell = pPage->nCell;
55280 for(i=0; i<nCell; i++){
55281 u8 *pCell = findCell(pPage, i);
55283 ptrmapPutOvflPtr(pPage, pCell, &rc);
55285 if( !pPage->leaf ){
55286 Pgno childPgno = get4byte(pCell);
55287 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
55291 if( !pPage->leaf ){
55292 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55293 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
55296 set_child_ptrmaps_out:
55297 pPage->isInit = isInitOrig;
55298 return rc;
55302 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
55303 ** that it points to iTo. Parameter eType describes the type of pointer to
55304 ** be modified, as follows:
55306 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
55307 ** page of pPage.
55309 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
55310 ** page pointed to by one of the cells on pPage.
55312 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
55313 ** overflow page in the list.
55315 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
55316 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55317 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55318 if( eType==PTRMAP_OVERFLOW2 ){
55319 /* The pointer is always the first 4 bytes of the page in this case. */
55320 if( get4byte(pPage->aData)!=iFrom ){
55321 return SQLITE_CORRUPT_BKPT;
55323 put4byte(pPage->aData, iTo);
55324 }else{
55325 u8 isInitOrig = pPage->isInit;
55326 int i;
55327 int nCell;
55329 btreeInitPage(pPage);
55330 nCell = pPage->nCell;
55332 for(i=0; i<nCell; i++){
55333 u8 *pCell = findCell(pPage, i);
55334 if( eType==PTRMAP_OVERFLOW1 ){
55335 CellInfo info;
55336 btreeParseCellPtr(pPage, pCell, &info);
55337 if( info.iOverflow
55338 && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
55339 && iFrom==get4byte(&pCell[info.iOverflow])
55341 put4byte(&pCell[info.iOverflow], iTo);
55342 break;
55344 }else{
55345 if( get4byte(pCell)==iFrom ){
55346 put4byte(pCell, iTo);
55347 break;
55352 if( i==nCell ){
55353 if( eType!=PTRMAP_BTREE ||
55354 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
55355 return SQLITE_CORRUPT_BKPT;
55357 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
55360 pPage->isInit = isInitOrig;
55362 return SQLITE_OK;
55367 ** Move the open database page pDbPage to location iFreePage in the
55368 ** database. The pDbPage reference remains valid.
55370 ** The isCommit flag indicates that there is no need to remember that
55371 ** the journal needs to be sync()ed before database page pDbPage->pgno
55372 ** can be written to. The caller has already promised not to write to that
55373 ** page.
55375 static int relocatePage(
55376 BtShared *pBt, /* Btree */
55377 MemPage *pDbPage, /* Open page to move */
55378 u8 eType, /* Pointer map 'type' entry for pDbPage */
55379 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
55380 Pgno iFreePage, /* The location to move pDbPage to */
55381 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
55383 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
55384 Pgno iDbPage = pDbPage->pgno;
55385 Pager *pPager = pBt->pPager;
55386 int rc;
55388 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
55389 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
55390 assert( sqlite3_mutex_held(pBt->mutex) );
55391 assert( pDbPage->pBt==pBt );
55393 /* Move page iDbPage from its current location to page number iFreePage */
55394 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
55395 iDbPage, iFreePage, iPtrPage, eType));
55396 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
55397 if( rc!=SQLITE_OK ){
55398 return rc;
55400 pDbPage->pgno = iFreePage;
55402 /* If pDbPage was a btree-page, then it may have child pages and/or cells
55403 ** that point to overflow pages. The pointer map entries for all these
55404 ** pages need to be changed.
55406 ** If pDbPage is an overflow page, then the first 4 bytes may store a
55407 ** pointer to a subsequent overflow page. If this is the case, then
55408 ** the pointer map needs to be updated for the subsequent overflow page.
55410 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
55411 rc = setChildPtrmaps(pDbPage);
55412 if( rc!=SQLITE_OK ){
55413 return rc;
55415 }else{
55416 Pgno nextOvfl = get4byte(pDbPage->aData);
55417 if( nextOvfl!=0 ){
55418 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
55419 if( rc!=SQLITE_OK ){
55420 return rc;
55425 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
55426 ** that it points at iFreePage. Also fix the pointer map entry for
55427 ** iPtrPage.
55429 if( eType!=PTRMAP_ROOTPAGE ){
55430 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
55431 if( rc!=SQLITE_OK ){
55432 return rc;
55434 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
55435 if( rc!=SQLITE_OK ){
55436 releasePage(pPtrPage);
55437 return rc;
55439 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
55440 releasePage(pPtrPage);
55441 if( rc==SQLITE_OK ){
55442 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
55445 return rc;
55448 /* Forward declaration required by incrVacuumStep(). */
55449 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
55452 ** Perform a single step of an incremental-vacuum. If successful, return
55453 ** SQLITE_OK. If there is no work to do (and therefore no point in
55454 ** calling this function again), return SQLITE_DONE. Or, if an error
55455 ** occurs, return some other error code.
55457 ** More specifically, this function attempts to re-organize the database so
55458 ** that the last page of the file currently in use is no longer in use.
55460 ** Parameter nFin is the number of pages that this database would contain
55461 ** were this function called until it returns SQLITE_DONE.
55463 ** If the bCommit parameter is non-zero, this function assumes that the
55464 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
55465 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
55466 ** operation, or false for an incremental vacuum.
55468 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
55469 Pgno nFreeList; /* Number of pages still on the free-list */
55470 int rc;
55472 assert( sqlite3_mutex_held(pBt->mutex) );
55473 assert( iLastPg>nFin );
55475 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
55476 u8 eType;
55477 Pgno iPtrPage;
55479 nFreeList = get4byte(&pBt->pPage1->aData[36]);
55480 if( nFreeList==0 ){
55481 return SQLITE_DONE;
55484 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
55485 if( rc!=SQLITE_OK ){
55486 return rc;
55488 if( eType==PTRMAP_ROOTPAGE ){
55489 return SQLITE_CORRUPT_BKPT;
55492 if( eType==PTRMAP_FREEPAGE ){
55493 if( bCommit==0 ){
55494 /* Remove the page from the files free-list. This is not required
55495 ** if bCommit is non-zero. In that case, the free-list will be
55496 ** truncated to zero after this function returns, so it doesn't
55497 ** matter if it still contains some garbage entries.
55499 Pgno iFreePg;
55500 MemPage *pFreePg;
55501 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
55502 if( rc!=SQLITE_OK ){
55503 return rc;
55505 assert( iFreePg==iLastPg );
55506 releasePage(pFreePg);
55508 } else {
55509 Pgno iFreePg; /* Index of free page to move pLastPg to */
55510 MemPage *pLastPg;
55511 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
55512 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
55514 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
55515 if( rc!=SQLITE_OK ){
55516 return rc;
55519 /* If bCommit is zero, this loop runs exactly once and page pLastPg
55520 ** is swapped with the first free page pulled off the free list.
55522 ** On the other hand, if bCommit is greater than zero, then keep
55523 ** looping until a free-page located within the first nFin pages
55524 ** of the file is found.
55526 if( bCommit==0 ){
55527 eMode = BTALLOC_LE;
55528 iNear = nFin;
55530 do {
55531 MemPage *pFreePg;
55532 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
55533 if( rc!=SQLITE_OK ){
55534 releasePage(pLastPg);
55535 return rc;
55537 releasePage(pFreePg);
55538 }while( bCommit && iFreePg>nFin );
55539 assert( iFreePg<iLastPg );
55541 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
55542 releasePage(pLastPg);
55543 if( rc!=SQLITE_OK ){
55544 return rc;
55549 if( bCommit==0 ){
55550 do {
55551 iLastPg--;
55552 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
55553 pBt->bDoTruncate = 1;
55554 pBt->nPage = iLastPg;
55556 return SQLITE_OK;
55560 ** The database opened by the first argument is an auto-vacuum database
55561 ** nOrig pages in size containing nFree free pages. Return the expected
55562 ** size of the database in pages following an auto-vacuum operation.
55564 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
55565 int nEntry; /* Number of entries on one ptrmap page */
55566 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
55567 Pgno nFin; /* Return value */
55569 nEntry = pBt->usableSize/5;
55570 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
55571 nFin = nOrig - nFree - nPtrmap;
55572 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
55573 nFin--;
55575 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
55576 nFin--;
55579 return nFin;
55583 ** A write-transaction must be opened before calling this function.
55584 ** It performs a single unit of work towards an incremental vacuum.
55586 ** If the incremental vacuum is finished after this function has run,
55587 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
55588 ** SQLITE_OK is returned. Otherwise an SQLite error code.
55590 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
55591 int rc;
55592 BtShared *pBt = p->pBt;
55594 sqlite3BtreeEnter(p);
55595 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
55596 if( !pBt->autoVacuum ){
55597 rc = SQLITE_DONE;
55598 }else{
55599 Pgno nOrig = btreePagecount(pBt);
55600 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
55601 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
55603 if( nOrig<nFin ){
55604 rc = SQLITE_CORRUPT_BKPT;
55605 }else if( nFree>0 ){
55606 rc = saveAllCursors(pBt, 0, 0);
55607 if( rc==SQLITE_OK ){
55608 invalidateAllOverflowCache(pBt);
55609 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
55611 if( rc==SQLITE_OK ){
55612 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55613 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
55615 }else{
55616 rc = SQLITE_DONE;
55619 sqlite3BtreeLeave(p);
55620 return rc;
55624 ** This routine is called prior to sqlite3PagerCommit when a transaction
55625 ** is committed for an auto-vacuum database.
55627 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
55628 ** the database file should be truncated to during the commit process.
55629 ** i.e. the database has been reorganized so that only the first *pnTrunc
55630 ** pages are in use.
55632 static int autoVacuumCommit(BtShared *pBt){
55633 int rc = SQLITE_OK;
55634 Pager *pPager = pBt->pPager;
55635 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
55637 assert( sqlite3_mutex_held(pBt->mutex) );
55638 invalidateAllOverflowCache(pBt);
55639 assert(pBt->autoVacuum);
55640 if( !pBt->incrVacuum ){
55641 Pgno nFin; /* Number of pages in database after autovacuuming */
55642 Pgno nFree; /* Number of pages on the freelist initially */
55643 Pgno iFree; /* The next page to be freed */
55644 Pgno nOrig; /* Database size before freeing */
55646 nOrig = btreePagecount(pBt);
55647 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
55648 /* It is not possible to create a database for which the final page
55649 ** is either a pointer-map page or the pending-byte page. If one
55650 ** is encountered, this indicates corruption.
55652 return SQLITE_CORRUPT_BKPT;
55655 nFree = get4byte(&pBt->pPage1->aData[36]);
55656 nFin = finalDbSize(pBt, nOrig, nFree);
55657 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
55658 if( nFin<nOrig ){
55659 rc = saveAllCursors(pBt, 0, 0);
55661 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
55662 rc = incrVacuumStep(pBt, nFin, iFree, 1);
55664 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
55665 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55666 put4byte(&pBt->pPage1->aData[32], 0);
55667 put4byte(&pBt->pPage1->aData[36], 0);
55668 put4byte(&pBt->pPage1->aData[28], nFin);
55669 pBt->bDoTruncate = 1;
55670 pBt->nPage = nFin;
55672 if( rc!=SQLITE_OK ){
55673 sqlite3PagerRollback(pPager);
55677 assert( nRef>=sqlite3PagerRefcount(pPager) );
55678 return rc;
55681 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
55682 # define setChildPtrmaps(x) SQLITE_OK
55683 #endif
55686 ** This routine does the first phase of a two-phase commit. This routine
55687 ** causes a rollback journal to be created (if it does not already exist)
55688 ** and populated with enough information so that if a power loss occurs
55689 ** the database can be restored to its original state by playing back
55690 ** the journal. Then the contents of the journal are flushed out to
55691 ** the disk. After the journal is safely on oxide, the changes to the
55692 ** database are written into the database file and flushed to oxide.
55693 ** At the end of this call, the rollback journal still exists on the
55694 ** disk and we are still holding all locks, so the transaction has not
55695 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
55696 ** commit process.
55698 ** This call is a no-op if no write-transaction is currently active on pBt.
55700 ** Otherwise, sync the database file for the btree pBt. zMaster points to
55701 ** the name of a master journal file that should be written into the
55702 ** individual journal file, or is NULL, indicating no master journal file
55703 ** (single database transaction).
55705 ** When this is called, the master journal should already have been
55706 ** created, populated with this journal pointer and synced to disk.
55708 ** Once this is routine has returned, the only thing required to commit
55709 ** the write-transaction for this database file is to delete the journal.
55711 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
55712 int rc = SQLITE_OK;
55713 if( p->inTrans==TRANS_WRITE ){
55714 BtShared *pBt = p->pBt;
55715 sqlite3BtreeEnter(p);
55716 #ifndef SQLITE_OMIT_AUTOVACUUM
55717 if( pBt->autoVacuum ){
55718 rc = autoVacuumCommit(pBt);
55719 if( rc!=SQLITE_OK ){
55720 sqlite3BtreeLeave(p);
55721 return rc;
55724 if( pBt->bDoTruncate ){
55725 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
55727 #endif
55728 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
55729 sqlite3BtreeLeave(p);
55731 return rc;
55735 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
55736 ** at the conclusion of a transaction.
55738 static void btreeEndTransaction(Btree *p){
55739 BtShared *pBt = p->pBt;
55740 sqlite3 *db = p->db;
55741 assert( sqlite3BtreeHoldsMutex(p) );
55743 #ifndef SQLITE_OMIT_AUTOVACUUM
55744 pBt->bDoTruncate = 0;
55745 #endif
55746 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
55747 /* If there are other active statements that belong to this database
55748 ** handle, downgrade to a read-only transaction. The other statements
55749 ** may still be reading from the database. */
55750 downgradeAllSharedCacheTableLocks(p);
55751 p->inTrans = TRANS_READ;
55752 }else{
55753 /* If the handle had any kind of transaction open, decrement the
55754 ** transaction count of the shared btree. If the transaction count
55755 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
55756 ** call below will unlock the pager. */
55757 if( p->inTrans!=TRANS_NONE ){
55758 clearAllSharedCacheTableLocks(p);
55759 pBt->nTransaction--;
55760 if( 0==pBt->nTransaction ){
55761 pBt->inTransaction = TRANS_NONE;
55765 /* Set the current transaction state to TRANS_NONE and unlock the
55766 ** pager if this call closed the only read or write transaction. */
55767 p->inTrans = TRANS_NONE;
55768 unlockBtreeIfUnused(pBt);
55771 btreeIntegrity(p);
55775 ** Commit the transaction currently in progress.
55777 ** This routine implements the second phase of a 2-phase commit. The
55778 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
55779 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
55780 ** routine did all the work of writing information out to disk and flushing the
55781 ** contents so that they are written onto the disk platter. All this
55782 ** routine has to do is delete or truncate or zero the header in the
55783 ** the rollback journal (which causes the transaction to commit) and
55784 ** drop locks.
55786 ** Normally, if an error occurs while the pager layer is attempting to
55787 ** finalize the underlying journal file, this function returns an error and
55788 ** the upper layer will attempt a rollback. However, if the second argument
55789 ** is non-zero then this b-tree transaction is part of a multi-file
55790 ** transaction. In this case, the transaction has already been committed
55791 ** (by deleting a master journal file) and the caller will ignore this
55792 ** functions return code. So, even if an error occurs in the pager layer,
55793 ** reset the b-tree objects internal state to indicate that the write
55794 ** transaction has been closed. This is quite safe, as the pager will have
55795 ** transitioned to the error state.
55797 ** This will release the write lock on the database file. If there
55798 ** are no active cursors, it also releases the read lock.
55800 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
55802 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
55803 sqlite3BtreeEnter(p);
55804 btreeIntegrity(p);
55806 /* If the handle has a write-transaction open, commit the shared-btrees
55807 ** transaction and set the shared state to TRANS_READ.
55809 if( p->inTrans==TRANS_WRITE ){
55810 int rc;
55811 BtShared *pBt = p->pBt;
55812 assert( pBt->inTransaction==TRANS_WRITE );
55813 assert( pBt->nTransaction>0 );
55814 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
55815 if( rc!=SQLITE_OK && bCleanup==0 ){
55816 sqlite3BtreeLeave(p);
55817 return rc;
55819 pBt->inTransaction = TRANS_READ;
55820 btreeClearHasContent(pBt);
55823 btreeEndTransaction(p);
55824 sqlite3BtreeLeave(p);
55825 return SQLITE_OK;
55829 ** Do both phases of a commit.
55831 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
55832 int rc;
55833 sqlite3BtreeEnter(p);
55834 rc = sqlite3BtreeCommitPhaseOne(p, 0);
55835 if( rc==SQLITE_OK ){
55836 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
55838 sqlite3BtreeLeave(p);
55839 return rc;
55843 ** This routine sets the state to CURSOR_FAULT and the error
55844 ** code to errCode for every cursor on any BtShared that pBtree
55845 ** references. Or if the writeOnly flag is set to 1, then only
55846 ** trip write cursors and leave read cursors unchanged.
55848 ** Every cursor is a candidate to be tripped, including cursors
55849 ** that belong to other database connections that happen to be
55850 ** sharing the cache with pBtree.
55852 ** This routine gets called when a rollback occurs. If the writeOnly
55853 ** flag is true, then only write-cursors need be tripped - read-only
55854 ** cursors save their current positions so that they may continue
55855 ** following the rollback. Or, if writeOnly is false, all cursors are
55856 ** tripped. In general, writeOnly is false if the transaction being
55857 ** rolled back modified the database schema. In this case b-tree root
55858 ** pages may be moved or deleted from the database altogether, making
55859 ** it unsafe for read cursors to continue.
55861 ** If the writeOnly flag is true and an error is encountered while
55862 ** saving the current position of a read-only cursor, all cursors,
55863 ** including all read-cursors are tripped.
55865 ** SQLITE_OK is returned if successful, or if an error occurs while
55866 ** saving a cursor position, an SQLite error code.
55868 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
55869 BtCursor *p;
55870 int rc = SQLITE_OK;
55872 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
55873 if( pBtree ){
55874 sqlite3BtreeEnter(pBtree);
55875 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
55876 int i;
55877 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
55878 if( p->eState==CURSOR_VALID ){
55879 rc = saveCursorPosition(p);
55880 if( rc!=SQLITE_OK ){
55881 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
55882 break;
55885 }else{
55886 sqlite3BtreeClearCursor(p);
55887 p->eState = CURSOR_FAULT;
55888 p->skipNext = errCode;
55890 for(i=0; i<=p->iPage; i++){
55891 releasePage(p->apPage[i]);
55892 p->apPage[i] = 0;
55895 sqlite3BtreeLeave(pBtree);
55897 return rc;
55901 ** Rollback the transaction in progress.
55903 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
55904 ** Only write cursors are tripped if writeOnly is true but all cursors are
55905 ** tripped if writeOnly is false. Any attempt to use
55906 ** a tripped cursor will result in an error.
55908 ** This will release the write lock on the database file. If there
55909 ** are no active cursors, it also releases the read lock.
55911 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
55912 int rc;
55913 BtShared *pBt = p->pBt;
55914 MemPage *pPage1;
55916 assert( writeOnly==1 || writeOnly==0 );
55917 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
55918 sqlite3BtreeEnter(p);
55919 if( tripCode==SQLITE_OK ){
55920 rc = tripCode = saveAllCursors(pBt, 0, 0);
55921 if( rc ) writeOnly = 0;
55922 }else{
55923 rc = SQLITE_OK;
55925 if( tripCode ){
55926 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
55927 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
55928 if( rc2!=SQLITE_OK ) rc = rc2;
55930 btreeIntegrity(p);
55932 if( p->inTrans==TRANS_WRITE ){
55933 int rc2;
55935 assert( TRANS_WRITE==pBt->inTransaction );
55936 rc2 = sqlite3PagerRollback(pBt->pPager);
55937 if( rc2!=SQLITE_OK ){
55938 rc = rc2;
55941 /* The rollback may have destroyed the pPage1->aData value. So
55942 ** call btreeGetPage() on page 1 again to make
55943 ** sure pPage1->aData is set correctly. */
55944 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
55945 int nPage = get4byte(28+(u8*)pPage1->aData);
55946 testcase( nPage==0 );
55947 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
55948 testcase( pBt->nPage!=nPage );
55949 pBt->nPage = nPage;
55950 releasePage(pPage1);
55952 assert( countValidCursors(pBt, 1)==0 );
55953 pBt->inTransaction = TRANS_READ;
55954 btreeClearHasContent(pBt);
55957 btreeEndTransaction(p);
55958 sqlite3BtreeLeave(p);
55959 return rc;
55963 ** Start a statement subtransaction. The subtransaction can be rolled
55964 ** back independently of the main transaction. You must start a transaction
55965 ** before starting a subtransaction. The subtransaction is ended automatically
55966 ** if the main transaction commits or rolls back.
55968 ** Statement subtransactions are used around individual SQL statements
55969 ** that are contained within a BEGIN...COMMIT block. If a constraint
55970 ** error occurs within the statement, the effect of that one statement
55971 ** can be rolled back without having to rollback the entire transaction.
55973 ** A statement sub-transaction is implemented as an anonymous savepoint. The
55974 ** value passed as the second parameter is the total number of savepoints,
55975 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
55976 ** are no active savepoints and no other statement-transactions open,
55977 ** iStatement is 1. This anonymous savepoint can be released or rolled back
55978 ** using the sqlite3BtreeSavepoint() function.
55980 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
55981 int rc;
55982 BtShared *pBt = p->pBt;
55983 sqlite3BtreeEnter(p);
55984 assert( p->inTrans==TRANS_WRITE );
55985 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
55986 assert( iStatement>0 );
55987 assert( iStatement>p->db->nSavepoint );
55988 assert( pBt->inTransaction==TRANS_WRITE );
55989 /* At the pager level, a statement transaction is a savepoint with
55990 ** an index greater than all savepoints created explicitly using
55991 ** SQL statements. It is illegal to open, release or rollback any
55992 ** such savepoints while the statement transaction savepoint is active.
55994 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
55995 sqlite3BtreeLeave(p);
55996 return rc;
56000 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
56001 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
56002 ** savepoint identified by parameter iSavepoint, depending on the value
56003 ** of op.
56005 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
56006 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
56007 ** contents of the entire transaction are rolled back. This is different
56008 ** from a normal transaction rollback, as no locks are released and the
56009 ** transaction remains open.
56011 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
56012 int rc = SQLITE_OK;
56013 if( p && p->inTrans==TRANS_WRITE ){
56014 BtShared *pBt = p->pBt;
56015 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
56016 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
56017 sqlite3BtreeEnter(p);
56018 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
56019 if( rc==SQLITE_OK ){
56020 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
56021 pBt->nPage = 0;
56023 rc = newDatabase(pBt);
56024 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
56026 /* The database size was written into the offset 28 of the header
56027 ** when the transaction started, so we know that the value at offset
56028 ** 28 is nonzero. */
56029 assert( pBt->nPage>0 );
56031 sqlite3BtreeLeave(p);
56033 return rc;
56037 ** Create a new cursor for the BTree whose root is on the page
56038 ** iTable. If a read-only cursor is requested, it is assumed that
56039 ** the caller already has at least a read-only transaction open
56040 ** on the database already. If a write-cursor is requested, then
56041 ** the caller is assumed to have an open write transaction.
56043 ** If wrFlag==0, then the cursor can only be used for reading.
56044 ** If wrFlag==1, then the cursor can be used for reading or for
56045 ** writing if other conditions for writing are also met. These
56046 ** are the conditions that must be met in order for writing to
56047 ** be allowed:
56049 ** 1: The cursor must have been opened with wrFlag==1
56051 ** 2: Other database connections that share the same pager cache
56052 ** but which are not in the READ_UNCOMMITTED state may not have
56053 ** cursors open with wrFlag==0 on the same table. Otherwise
56054 ** the changes made by this write cursor would be visible to
56055 ** the read cursors in the other database connection.
56057 ** 3: The database must be writable (not on read-only media)
56059 ** 4: There must be an active transaction.
56061 ** No checking is done to make sure that page iTable really is the
56062 ** root page of a b-tree. If it is not, then the cursor acquired
56063 ** will not work correctly.
56065 ** It is assumed that the sqlite3BtreeCursorZero() has been called
56066 ** on pCur to initialize the memory space prior to invoking this routine.
56068 static int btreeCursor(
56069 Btree *p, /* The btree */
56070 int iTable, /* Root page of table to open */
56071 int wrFlag, /* 1 to write. 0 read-only */
56072 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
56073 BtCursor *pCur /* Space for new cursor */
56075 BtShared *pBt = p->pBt; /* Shared b-tree handle */
56077 assert( sqlite3BtreeHoldsMutex(p) );
56078 assert( wrFlag==0 || wrFlag==1 );
56080 /* The following assert statements verify that if this is a sharable
56081 ** b-tree database, the connection is holding the required table locks,
56082 ** and that no other connection has any open cursor that conflicts with
56083 ** this lock. */
56084 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
56085 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
56087 /* Assert that the caller has opened the required transaction. */
56088 assert( p->inTrans>TRANS_NONE );
56089 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
56090 assert( pBt->pPage1 && pBt->pPage1->aData );
56092 if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
56093 return SQLITE_READONLY;
56095 if( wrFlag ){
56096 allocateTempSpace(pBt);
56097 if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM;
56099 if( iTable==1 && btreePagecount(pBt)==0 ){
56100 assert( wrFlag==0 );
56101 iTable = 0;
56104 /* Now that no other errors can occur, finish filling in the BtCursor
56105 ** variables and link the cursor into the BtShared list. */
56106 pCur->pgnoRoot = (Pgno)iTable;
56107 pCur->iPage = -1;
56108 pCur->pKeyInfo = pKeyInfo;
56109 pCur->pBtree = p;
56110 pCur->pBt = pBt;
56111 assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
56112 pCur->curFlags = wrFlag;
56113 pCur->pNext = pBt->pCursor;
56114 if( pCur->pNext ){
56115 pCur->pNext->pPrev = pCur;
56117 pBt->pCursor = pCur;
56118 pCur->eState = CURSOR_INVALID;
56119 return SQLITE_OK;
56121 SQLITE_PRIVATE int sqlite3BtreeCursor(
56122 Btree *p, /* The btree */
56123 int iTable, /* Root page of table to open */
56124 int wrFlag, /* 1 to write. 0 read-only */
56125 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
56126 BtCursor *pCur /* Write new cursor here */
56128 int rc;
56129 sqlite3BtreeEnter(p);
56130 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
56131 sqlite3BtreeLeave(p);
56132 return rc;
56136 ** Return the size of a BtCursor object in bytes.
56138 ** This interfaces is needed so that users of cursors can preallocate
56139 ** sufficient storage to hold a cursor. The BtCursor object is opaque
56140 ** to users so they cannot do the sizeof() themselves - they must call
56141 ** this routine.
56143 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
56144 return ROUND8(sizeof(BtCursor));
56148 ** Initialize memory that will be converted into a BtCursor object.
56150 ** The simple approach here would be to memset() the entire object
56151 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
56152 ** do not need to be zeroed and they are large, so we can save a lot
56153 ** of run-time by skipping the initialization of those elements.
56155 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
56156 memset(p, 0, offsetof(BtCursor, iPage));
56160 ** Close a cursor. The read lock on the database file is released
56161 ** when the last cursor is closed.
56163 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
56164 Btree *pBtree = pCur->pBtree;
56165 if( pBtree ){
56166 int i;
56167 BtShared *pBt = pCur->pBt;
56168 sqlite3BtreeEnter(pBtree);
56169 sqlite3BtreeClearCursor(pCur);
56170 if( pCur->pPrev ){
56171 pCur->pPrev->pNext = pCur->pNext;
56172 }else{
56173 pBt->pCursor = pCur->pNext;
56175 if( pCur->pNext ){
56176 pCur->pNext->pPrev = pCur->pPrev;
56178 for(i=0; i<=pCur->iPage; i++){
56179 releasePage(pCur->apPage[i]);
56181 unlockBtreeIfUnused(pBt);
56182 sqlite3DbFree(pBtree->db, pCur->aOverflow);
56183 /* sqlite3_free(pCur); */
56184 sqlite3BtreeLeave(pBtree);
56186 return SQLITE_OK;
56190 ** Make sure the BtCursor* given in the argument has a valid
56191 ** BtCursor.info structure. If it is not already valid, call
56192 ** btreeParseCell() to fill it in.
56194 ** BtCursor.info is a cache of the information in the current cell.
56195 ** Using this cache reduces the number of calls to btreeParseCell().
56197 ** 2007-06-25: There is a bug in some versions of MSVC that cause the
56198 ** compiler to crash when getCellInfo() is implemented as a macro.
56199 ** But there is a measureable speed advantage to using the macro on gcc
56200 ** (when less compiler optimizations like -Os or -O0 are used and the
56201 ** compiler is not doing aggressive inlining.) So we use a real function
56202 ** for MSVC and a macro for everything else. Ticket #2457.
56204 #ifndef NDEBUG
56205 static void assertCellInfo(BtCursor *pCur){
56206 CellInfo info;
56207 int iPage = pCur->iPage;
56208 memset(&info, 0, sizeof(info));
56209 btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
56210 assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
56212 #else
56213 #define assertCellInfo(x)
56214 #endif
56215 #ifdef _MSC_VER
56216 /* Use a real function in MSVC to work around bugs in that compiler. */
56217 static void getCellInfo(BtCursor *pCur){
56218 if( pCur->info.nSize==0 ){
56219 int iPage = pCur->iPage;
56220 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
56221 pCur->curFlags |= BTCF_ValidNKey;
56222 }else{
56223 assertCellInfo(pCur);
56226 #else /* if not _MSC_VER */
56227 /* Use a macro in all other compilers so that the function is inlined */
56228 #define getCellInfo(pCur) \
56229 if( pCur->info.nSize==0 ){ \
56230 int iPage = pCur->iPage; \
56231 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
56232 pCur->curFlags |= BTCF_ValidNKey; \
56233 }else{ \
56234 assertCellInfo(pCur); \
56236 #endif /* _MSC_VER */
56238 #ifndef NDEBUG /* The next routine used only within assert() statements */
56240 ** Return true if the given BtCursor is valid. A valid cursor is one
56241 ** that is currently pointing to a row in a (non-empty) table.
56242 ** This is a verification routine is used only within assert() statements.
56244 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
56245 return pCur && pCur->eState==CURSOR_VALID;
56247 #endif /* NDEBUG */
56250 ** Set *pSize to the size of the buffer needed to hold the value of
56251 ** the key for the current entry. If the cursor is not pointing
56252 ** to a valid entry, *pSize is set to 0.
56254 ** For a table with the INTKEY flag set, this routine returns the key
56255 ** itself, not the number of bytes in the key.
56257 ** The caller must position the cursor prior to invoking this routine.
56259 ** This routine cannot fail. It always returns SQLITE_OK.
56261 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
56262 assert( cursorHoldsMutex(pCur) );
56263 assert( pCur->eState==CURSOR_VALID );
56264 getCellInfo(pCur);
56265 *pSize = pCur->info.nKey;
56266 return SQLITE_OK;
56270 ** Set *pSize to the number of bytes of data in the entry the
56271 ** cursor currently points to.
56273 ** The caller must guarantee that the cursor is pointing to a non-NULL
56274 ** valid entry. In other words, the calling procedure must guarantee
56275 ** that the cursor has Cursor.eState==CURSOR_VALID.
56277 ** Failure is not possible. This function always returns SQLITE_OK.
56278 ** It might just as well be a procedure (returning void) but we continue
56279 ** to return an integer result code for historical reasons.
56281 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
56282 assert( cursorHoldsMutex(pCur) );
56283 assert( pCur->eState==CURSOR_VALID );
56284 assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
56285 getCellInfo(pCur);
56286 *pSize = pCur->info.nPayload;
56287 return SQLITE_OK;
56291 ** Given the page number of an overflow page in the database (parameter
56292 ** ovfl), this function finds the page number of the next page in the
56293 ** linked list of overflow pages. If possible, it uses the auto-vacuum
56294 ** pointer-map data instead of reading the content of page ovfl to do so.
56296 ** If an error occurs an SQLite error code is returned. Otherwise:
56298 ** The page number of the next overflow page in the linked list is
56299 ** written to *pPgnoNext. If page ovfl is the last page in its linked
56300 ** list, *pPgnoNext is set to zero.
56302 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
56303 ** to page number pOvfl was obtained, then *ppPage is set to point to that
56304 ** reference. It is the responsibility of the caller to call releasePage()
56305 ** on *ppPage to free the reference. In no reference was obtained (because
56306 ** the pointer-map was used to obtain the value for *pPgnoNext), then
56307 ** *ppPage is set to zero.
56309 static int getOverflowPage(
56310 BtShared *pBt, /* The database file */
56311 Pgno ovfl, /* Current overflow page number */
56312 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
56313 Pgno *pPgnoNext /* OUT: Next overflow page number */
56315 Pgno next = 0;
56316 MemPage *pPage = 0;
56317 int rc = SQLITE_OK;
56319 assert( sqlite3_mutex_held(pBt->mutex) );
56320 assert(pPgnoNext);
56322 #ifndef SQLITE_OMIT_AUTOVACUUM
56323 /* Try to find the next page in the overflow list using the
56324 ** autovacuum pointer-map pages. Guess that the next page in
56325 ** the overflow list is page number (ovfl+1). If that guess turns
56326 ** out to be wrong, fall back to loading the data of page
56327 ** number ovfl to determine the next page number.
56329 if( pBt->autoVacuum ){
56330 Pgno pgno;
56331 Pgno iGuess = ovfl+1;
56332 u8 eType;
56334 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
56335 iGuess++;
56338 if( iGuess<=btreePagecount(pBt) ){
56339 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
56340 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
56341 next = iGuess;
56342 rc = SQLITE_DONE;
56346 #endif
56348 assert( next==0 || rc==SQLITE_DONE );
56349 if( rc==SQLITE_OK ){
56350 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
56351 assert( rc==SQLITE_OK || pPage==0 );
56352 if( rc==SQLITE_OK ){
56353 next = get4byte(pPage->aData);
56357 *pPgnoNext = next;
56358 if( ppPage ){
56359 *ppPage = pPage;
56360 }else{
56361 releasePage(pPage);
56363 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
56367 ** Copy data from a buffer to a page, or from a page to a buffer.
56369 ** pPayload is a pointer to data stored on database page pDbPage.
56370 ** If argument eOp is false, then nByte bytes of data are copied
56371 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
56372 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
56373 ** of data are copied from the buffer pBuf to pPayload.
56375 ** SQLITE_OK is returned on success, otherwise an error code.
56377 static int copyPayload(
56378 void *pPayload, /* Pointer to page data */
56379 void *pBuf, /* Pointer to buffer */
56380 int nByte, /* Number of bytes to copy */
56381 int eOp, /* 0 -> copy from page, 1 -> copy to page */
56382 DbPage *pDbPage /* Page containing pPayload */
56384 if( eOp ){
56385 /* Copy data from buffer to page (a write operation) */
56386 int rc = sqlite3PagerWrite(pDbPage);
56387 if( rc!=SQLITE_OK ){
56388 return rc;
56390 memcpy(pPayload, pBuf, nByte);
56391 }else{
56392 /* Copy data from page to buffer (a read operation) */
56393 memcpy(pBuf, pPayload, nByte);
56395 return SQLITE_OK;
56399 ** This function is used to read or overwrite payload information
56400 ** for the entry that the pCur cursor is pointing to. The eOp
56401 ** argument is interpreted as follows:
56403 ** 0: The operation is a read. Populate the overflow cache.
56404 ** 1: The operation is a write. Populate the overflow cache.
56405 ** 2: The operation is a read. Do not populate the overflow cache.
56407 ** A total of "amt" bytes are read or written beginning at "offset".
56408 ** Data is read to or from the buffer pBuf.
56410 ** The content being read or written might appear on the main page
56411 ** or be scattered out on multiple overflow pages.
56413 ** If the current cursor entry uses one or more overflow pages and the
56414 ** eOp argument is not 2, this function may allocate space for and lazily
56415 ** populates the overflow page-list cache array (BtCursor.aOverflow).
56416 ** Subsequent calls use this cache to make seeking to the supplied offset
56417 ** more efficient.
56419 ** Once an overflow page-list cache has been allocated, it may be
56420 ** invalidated if some other cursor writes to the same table, or if
56421 ** the cursor is moved to a different row. Additionally, in auto-vacuum
56422 ** mode, the following events may invalidate an overflow page-list cache.
56424 ** * An incremental vacuum,
56425 ** * A commit in auto_vacuum="full" mode,
56426 ** * Creating a table (may require moving an overflow page).
56428 static int accessPayload(
56429 BtCursor *pCur, /* Cursor pointing to entry to read from */
56430 u32 offset, /* Begin reading this far into payload */
56431 u32 amt, /* Read this many bytes */
56432 unsigned char *pBuf, /* Write the bytes into this buffer */
56433 int eOp /* zero to read. non-zero to write. */
56435 unsigned char *aPayload;
56436 int rc = SQLITE_OK;
56437 int iIdx = 0;
56438 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
56439 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
56440 #ifdef SQLITE_DIRECT_OVERFLOW_READ
56441 unsigned char * const pBufStart = pBuf;
56442 int bEnd; /* True if reading to end of data */
56443 #endif
56445 assert( pPage );
56446 assert( pCur->eState==CURSOR_VALID );
56447 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
56448 assert( cursorHoldsMutex(pCur) );
56449 assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */
56451 getCellInfo(pCur);
56452 aPayload = pCur->info.pPayload;
56453 #ifdef SQLITE_DIRECT_OVERFLOW_READ
56454 bEnd = offset+amt==pCur->info.nPayload;
56455 #endif
56456 assert( offset+amt <= pCur->info.nPayload );
56458 if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){
56459 /* Trying to read or write past the end of the data is an error */
56460 return SQLITE_CORRUPT_BKPT;
56463 /* Check if data must be read/written to/from the btree page itself. */
56464 if( offset<pCur->info.nLocal ){
56465 int a = amt;
56466 if( a+offset>pCur->info.nLocal ){
56467 a = pCur->info.nLocal - offset;
56469 rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
56470 offset = 0;
56471 pBuf += a;
56472 amt -= a;
56473 }else{
56474 offset -= pCur->info.nLocal;
56477 if( rc==SQLITE_OK && amt>0 ){
56478 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
56479 Pgno nextPage;
56481 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
56483 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
56484 ** Except, do not allocate aOverflow[] for eOp==2.
56486 ** The aOverflow[] array is sized at one entry for each overflow page
56487 ** in the overflow chain. The page number of the first overflow page is
56488 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
56489 ** means "not yet known" (the cache is lazily populated).
56491 if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
56492 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
56493 if( nOvfl>pCur->nOvflAlloc ){
56494 Pgno *aNew = (Pgno*)sqlite3DbRealloc(
56495 pCur->pBtree->db, pCur->aOverflow, nOvfl*2*sizeof(Pgno)
56497 if( aNew==0 ){
56498 rc = SQLITE_NOMEM;
56499 }else{
56500 pCur->nOvflAlloc = nOvfl*2;
56501 pCur->aOverflow = aNew;
56504 if( rc==SQLITE_OK ){
56505 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
56506 pCur->curFlags |= BTCF_ValidOvfl;
56510 /* If the overflow page-list cache has been allocated and the
56511 ** entry for the first required overflow page is valid, skip
56512 ** directly to it.
56514 if( (pCur->curFlags & BTCF_ValidOvfl)!=0
56515 && pCur->aOverflow[offset/ovflSize]
56517 iIdx = (offset/ovflSize);
56518 nextPage = pCur->aOverflow[iIdx];
56519 offset = (offset%ovflSize);
56522 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
56524 /* If required, populate the overflow page-list cache. */
56525 if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
56526 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
56527 pCur->aOverflow[iIdx] = nextPage;
56530 if( offset>=ovflSize ){
56531 /* The only reason to read this page is to obtain the page
56532 ** number for the next page in the overflow chain. The page
56533 ** data is not required. So first try to lookup the overflow
56534 ** page-list cache, if any, then fall back to the getOverflowPage()
56535 ** function.
56537 ** Note that the aOverflow[] array must be allocated because eOp!=2
56538 ** here. If eOp==2, then offset==0 and this branch is never taken.
56540 assert( eOp!=2 );
56541 assert( pCur->curFlags & BTCF_ValidOvfl );
56542 if( pCur->aOverflow[iIdx+1] ){
56543 nextPage = pCur->aOverflow[iIdx+1];
56544 }else{
56545 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
56547 offset -= ovflSize;
56548 }else{
56549 /* Need to read this page properly. It contains some of the
56550 ** range of data that is being read (eOp==0) or written (eOp!=0).
56552 #ifdef SQLITE_DIRECT_OVERFLOW_READ
56553 sqlite3_file *fd;
56554 #endif
56555 int a = amt;
56556 if( a + offset > ovflSize ){
56557 a = ovflSize - offset;
56560 #ifdef SQLITE_DIRECT_OVERFLOW_READ
56561 /* If all the following are true:
56563 ** 1) this is a read operation, and
56564 ** 2) data is required from the start of this overflow page, and
56565 ** 3) the database is file-backed, and
56566 ** 4) there is no open write-transaction, and
56567 ** 5) the database is not a WAL database,
56568 ** 6) all data from the page is being read.
56569 ** 7) at least 4 bytes have already been read into the output buffer
56571 ** then data can be read directly from the database file into the
56572 ** output buffer, bypassing the page-cache altogether. This speeds
56573 ** up loading large records that span many overflow pages.
56575 if( (eOp&0x01)==0 /* (1) */
56576 && offset==0 /* (2) */
56577 && (bEnd || a==ovflSize) /* (6) */
56578 && pBt->inTransaction==TRANS_READ /* (4) */
56579 && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
56580 && pBt->pPage1->aData[19]==0x01 /* (5) */
56581 && &pBuf[-4]>=pBufStart /* (7) */
56583 u8 aSave[4];
56584 u8 *aWrite = &pBuf[-4];
56585 assert( aWrite>=pBufStart ); /* hence (7) */
56586 memcpy(aSave, aWrite, 4);
56587 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
56588 nextPage = get4byte(aWrite);
56589 memcpy(aWrite, aSave, 4);
56590 }else
56591 #endif
56594 DbPage *pDbPage;
56595 rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
56596 ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
56598 if( rc==SQLITE_OK ){
56599 aPayload = sqlite3PagerGetData(pDbPage);
56600 nextPage = get4byte(aPayload);
56601 rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
56602 sqlite3PagerUnref(pDbPage);
56603 offset = 0;
56606 amt -= a;
56607 pBuf += a;
56612 if( rc==SQLITE_OK && amt>0 ){
56613 return SQLITE_CORRUPT_BKPT;
56615 return rc;
56619 ** Read part of the key associated with cursor pCur. Exactly
56620 ** "amt" bytes will be transferred into pBuf[]. The transfer
56621 ** begins at "offset".
56623 ** The caller must ensure that pCur is pointing to a valid row
56624 ** in the table.
56626 ** Return SQLITE_OK on success or an error code if anything goes
56627 ** wrong. An error is returned if "offset+amt" is larger than
56628 ** the available payload.
56630 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
56631 assert( cursorHoldsMutex(pCur) );
56632 assert( pCur->eState==CURSOR_VALID );
56633 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
56634 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
56635 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
56639 ** Read part of the data associated with cursor pCur. Exactly
56640 ** "amt" bytes will be transfered into pBuf[]. The transfer
56641 ** begins at "offset".
56643 ** Return SQLITE_OK on success or an error code if anything goes
56644 ** wrong. An error is returned if "offset+amt" is larger than
56645 ** the available payload.
56647 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
56648 int rc;
56650 #ifndef SQLITE_OMIT_INCRBLOB
56651 if ( pCur->eState==CURSOR_INVALID ){
56652 return SQLITE_ABORT;
56654 #endif
56656 assert( cursorHoldsMutex(pCur) );
56657 rc = restoreCursorPosition(pCur);
56658 if( rc==SQLITE_OK ){
56659 assert( pCur->eState==CURSOR_VALID );
56660 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
56661 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
56662 rc = accessPayload(pCur, offset, amt, pBuf, 0);
56664 return rc;
56668 ** Return a pointer to payload information from the entry that the
56669 ** pCur cursor is pointing to. The pointer is to the beginning of
56670 ** the key if index btrees (pPage->intKey==0) and is the data for
56671 ** table btrees (pPage->intKey==1). The number of bytes of available
56672 ** key/data is written into *pAmt. If *pAmt==0, then the value
56673 ** returned will not be a valid pointer.
56675 ** This routine is an optimization. It is common for the entire key
56676 ** and data to fit on the local page and for there to be no overflow
56677 ** pages. When that is so, this routine can be used to access the
56678 ** key and data without making a copy. If the key and/or data spills
56679 ** onto overflow pages, then accessPayload() must be used to reassemble
56680 ** the key/data and copy it into a preallocated buffer.
56682 ** The pointer returned by this routine looks directly into the cached
56683 ** page of the database. The data might change or move the next time
56684 ** any btree routine is called.
56686 static const void *fetchPayload(
56687 BtCursor *pCur, /* Cursor pointing to entry to read from */
56688 u32 *pAmt /* Write the number of available bytes here */
56690 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
56691 assert( pCur->eState==CURSOR_VALID );
56692 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
56693 assert( cursorHoldsMutex(pCur) );
56694 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
56695 assert( pCur->info.nSize>0 );
56696 *pAmt = pCur->info.nLocal;
56697 return (void*)pCur->info.pPayload;
56702 ** For the entry that cursor pCur is point to, return as
56703 ** many bytes of the key or data as are available on the local
56704 ** b-tree page. Write the number of available bytes into *pAmt.
56706 ** The pointer returned is ephemeral. The key/data may move
56707 ** or be destroyed on the next call to any Btree routine,
56708 ** including calls from other threads against the same cache.
56709 ** Hence, a mutex on the BtShared should be held prior to calling
56710 ** this routine.
56712 ** These routines is used to get quick access to key and data
56713 ** in the common case where no overflow pages are used.
56715 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
56716 return fetchPayload(pCur, pAmt);
56718 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
56719 return fetchPayload(pCur, pAmt);
56724 ** Move the cursor down to a new child page. The newPgno argument is the
56725 ** page number of the child page to move to.
56727 ** This function returns SQLITE_CORRUPT if the page-header flags field of
56728 ** the new child page does not match the flags field of the parent (i.e.
56729 ** if an intkey page appears to be the parent of a non-intkey page, or
56730 ** vice-versa).
56732 static int moveToChild(BtCursor *pCur, u32 newPgno){
56733 int rc;
56734 int i = pCur->iPage;
56735 MemPage *pNewPage;
56736 BtShared *pBt = pCur->pBt;
56738 assert( cursorHoldsMutex(pCur) );
56739 assert( pCur->eState==CURSOR_VALID );
56740 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
56741 assert( pCur->iPage>=0 );
56742 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
56743 return SQLITE_CORRUPT_BKPT;
56745 rc = getAndInitPage(pBt, newPgno, &pNewPage,
56746 (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
56747 if( rc ) return rc;
56748 pCur->apPage[i+1] = pNewPage;
56749 pCur->aiIdx[i+1] = 0;
56750 pCur->iPage++;
56752 pCur->info.nSize = 0;
56753 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
56754 if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
56755 return SQLITE_CORRUPT_BKPT;
56757 return SQLITE_OK;
56760 #if 0
56762 ** Page pParent is an internal (non-leaf) tree page. This function
56763 ** asserts that page number iChild is the left-child if the iIdx'th
56764 ** cell in page pParent. Or, if iIdx is equal to the total number of
56765 ** cells in pParent, that page number iChild is the right-child of
56766 ** the page.
56768 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
56769 assert( iIdx<=pParent->nCell );
56770 if( iIdx==pParent->nCell ){
56771 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
56772 }else{
56773 assert( get4byte(findCell(pParent, iIdx))==iChild );
56776 #else
56777 # define assertParentIndex(x,y,z)
56778 #endif
56781 ** Move the cursor up to the parent page.
56783 ** pCur->idx is set to the cell index that contains the pointer
56784 ** to the page we are coming from. If we are coming from the
56785 ** right-most child page then pCur->idx is set to one more than
56786 ** the largest cell index.
56788 static void moveToParent(BtCursor *pCur){
56789 assert( cursorHoldsMutex(pCur) );
56790 assert( pCur->eState==CURSOR_VALID );
56791 assert( pCur->iPage>0 );
56792 assert( pCur->apPage[pCur->iPage] );
56794 /* UPDATE: It is actually possible for the condition tested by the assert
56795 ** below to be untrue if the database file is corrupt. This can occur if
56796 ** one cursor has modified page pParent while a reference to it is held
56797 ** by a second cursor. Which can only happen if a single page is linked
56798 ** into more than one b-tree structure in a corrupt database. */
56799 #if 0
56800 assertParentIndex(
56801 pCur->apPage[pCur->iPage-1],
56802 pCur->aiIdx[pCur->iPage-1],
56803 pCur->apPage[pCur->iPage]->pgno
56805 #endif
56806 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
56808 releasePage(pCur->apPage[pCur->iPage]);
56809 pCur->iPage--;
56810 pCur->info.nSize = 0;
56811 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
56815 ** Move the cursor to point to the root page of its b-tree structure.
56817 ** If the table has a virtual root page, then the cursor is moved to point
56818 ** to the virtual root page instead of the actual root page. A table has a
56819 ** virtual root page when the actual root page contains no cells and a
56820 ** single child page. This can only happen with the table rooted at page 1.
56822 ** If the b-tree structure is empty, the cursor state is set to
56823 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
56824 ** cell located on the root (or virtual root) page and the cursor state
56825 ** is set to CURSOR_VALID.
56827 ** If this function returns successfully, it may be assumed that the
56828 ** page-header flags indicate that the [virtual] root-page is the expected
56829 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
56830 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
56831 ** indicating a table b-tree, or if the caller did specify a KeyInfo
56832 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
56833 ** b-tree).
56835 static int moveToRoot(BtCursor *pCur){
56836 MemPage *pRoot;
56837 int rc = SQLITE_OK;
56839 assert( cursorHoldsMutex(pCur) );
56840 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
56841 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
56842 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
56843 if( pCur->eState>=CURSOR_REQUIRESEEK ){
56844 if( pCur->eState==CURSOR_FAULT ){
56845 assert( pCur->skipNext!=SQLITE_OK );
56846 return pCur->skipNext;
56848 sqlite3BtreeClearCursor(pCur);
56851 if( pCur->iPage>=0 ){
56852 while( pCur->iPage ) releasePage(pCur->apPage[pCur->iPage--]);
56853 }else if( pCur->pgnoRoot==0 ){
56854 pCur->eState = CURSOR_INVALID;
56855 return SQLITE_OK;
56856 }else{
56857 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
56858 (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
56859 if( rc!=SQLITE_OK ){
56860 pCur->eState = CURSOR_INVALID;
56861 return rc;
56863 pCur->iPage = 0;
56865 pRoot = pCur->apPage[0];
56866 assert( pRoot->pgno==pCur->pgnoRoot );
56868 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
56869 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
56870 ** NULL, the caller expects a table b-tree. If this is not the case,
56871 ** return an SQLITE_CORRUPT error.
56873 ** Earlier versions of SQLite assumed that this test could not fail
56874 ** if the root page was already loaded when this function was called (i.e.
56875 ** if pCur->iPage>=0). But this is not so if the database is corrupted
56876 ** in such a way that page pRoot is linked into a second b-tree table
56877 ** (or the freelist). */
56878 assert( pRoot->intKey==1 || pRoot->intKey==0 );
56879 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
56880 return SQLITE_CORRUPT_BKPT;
56883 pCur->aiIdx[0] = 0;
56884 pCur->info.nSize = 0;
56885 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
56887 if( pRoot->nCell>0 ){
56888 pCur->eState = CURSOR_VALID;
56889 }else if( !pRoot->leaf ){
56890 Pgno subpage;
56891 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
56892 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
56893 pCur->eState = CURSOR_VALID;
56894 rc = moveToChild(pCur, subpage);
56895 }else{
56896 pCur->eState = CURSOR_INVALID;
56898 return rc;
56902 ** Move the cursor down to the left-most leaf entry beneath the
56903 ** entry to which it is currently pointing.
56905 ** The left-most leaf is the one with the smallest key - the first
56906 ** in ascending order.
56908 static int moveToLeftmost(BtCursor *pCur){
56909 Pgno pgno;
56910 int rc = SQLITE_OK;
56911 MemPage *pPage;
56913 assert( cursorHoldsMutex(pCur) );
56914 assert( pCur->eState==CURSOR_VALID );
56915 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
56916 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
56917 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
56918 rc = moveToChild(pCur, pgno);
56920 return rc;
56924 ** Move the cursor down to the right-most leaf entry beneath the
56925 ** page to which it is currently pointing. Notice the difference
56926 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
56927 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
56928 ** finds the right-most entry beneath the *page*.
56930 ** The right-most entry is the one with the largest key - the last
56931 ** key in ascending order.
56933 static int moveToRightmost(BtCursor *pCur){
56934 Pgno pgno;
56935 int rc = SQLITE_OK;
56936 MemPage *pPage = 0;
56938 assert( cursorHoldsMutex(pCur) );
56939 assert( pCur->eState==CURSOR_VALID );
56940 while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
56941 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
56942 pCur->aiIdx[pCur->iPage] = pPage->nCell;
56943 rc = moveToChild(pCur, pgno);
56944 if( rc ) return rc;
56946 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
56947 assert( pCur->info.nSize==0 );
56948 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
56949 return SQLITE_OK;
56952 /* Move the cursor to the first entry in the table. Return SQLITE_OK
56953 ** on success. Set *pRes to 0 if the cursor actually points to something
56954 ** or set *pRes to 1 if the table is empty.
56956 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
56957 int rc;
56959 assert( cursorHoldsMutex(pCur) );
56960 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
56961 rc = moveToRoot(pCur);
56962 if( rc==SQLITE_OK ){
56963 if( pCur->eState==CURSOR_INVALID ){
56964 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
56965 *pRes = 1;
56966 }else{
56967 assert( pCur->apPage[pCur->iPage]->nCell>0 );
56968 *pRes = 0;
56969 rc = moveToLeftmost(pCur);
56972 return rc;
56975 /* Move the cursor to the last entry in the table. Return SQLITE_OK
56976 ** on success. Set *pRes to 0 if the cursor actually points to something
56977 ** or set *pRes to 1 if the table is empty.
56979 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
56980 int rc;
56982 assert( cursorHoldsMutex(pCur) );
56983 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
56985 /* If the cursor already points to the last entry, this is a no-op. */
56986 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
56987 #ifdef SQLITE_DEBUG
56988 /* This block serves to assert() that the cursor really does point
56989 ** to the last entry in the b-tree. */
56990 int ii;
56991 for(ii=0; ii<pCur->iPage; ii++){
56992 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
56994 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
56995 assert( pCur->apPage[pCur->iPage]->leaf );
56996 #endif
56997 return SQLITE_OK;
57000 rc = moveToRoot(pCur);
57001 if( rc==SQLITE_OK ){
57002 if( CURSOR_INVALID==pCur->eState ){
57003 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
57004 *pRes = 1;
57005 }else{
57006 assert( pCur->eState==CURSOR_VALID );
57007 *pRes = 0;
57008 rc = moveToRightmost(pCur);
57009 if( rc==SQLITE_OK ){
57010 pCur->curFlags |= BTCF_AtLast;
57011 }else{
57012 pCur->curFlags &= ~BTCF_AtLast;
57017 return rc;
57020 /* Move the cursor so that it points to an entry near the key
57021 ** specified by pIdxKey or intKey. Return a success code.
57023 ** For INTKEY tables, the intKey parameter is used. pIdxKey
57024 ** must be NULL. For index tables, pIdxKey is used and intKey
57025 ** is ignored.
57027 ** If an exact match is not found, then the cursor is always
57028 ** left pointing at a leaf page which would hold the entry if it
57029 ** were present. The cursor might point to an entry that comes
57030 ** before or after the key.
57032 ** An integer is written into *pRes which is the result of
57033 ** comparing the key with the entry to which the cursor is
57034 ** pointing. The meaning of the integer written into
57035 ** *pRes is as follows:
57037 ** *pRes<0 The cursor is left pointing at an entry that
57038 ** is smaller than intKey/pIdxKey or if the table is empty
57039 ** and the cursor is therefore left point to nothing.
57041 ** *pRes==0 The cursor is left pointing at an entry that
57042 ** exactly matches intKey/pIdxKey.
57044 ** *pRes>0 The cursor is left pointing at an entry that
57045 ** is larger than intKey/pIdxKey.
57048 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
57049 BtCursor *pCur, /* The cursor to be moved */
57050 UnpackedRecord *pIdxKey, /* Unpacked index key */
57051 i64 intKey, /* The table key */
57052 int biasRight, /* If true, bias the search to the high end */
57053 int *pRes /* Write search results here */
57055 int rc;
57056 RecordCompare xRecordCompare;
57058 assert( cursorHoldsMutex(pCur) );
57059 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
57060 assert( pRes );
57061 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
57063 /* If the cursor is already positioned at the point we are trying
57064 ** to move to, then just return without doing any work */
57065 if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
57066 && pCur->apPage[0]->intKey
57068 if( pCur->info.nKey==intKey ){
57069 *pRes = 0;
57070 return SQLITE_OK;
57072 if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
57073 *pRes = -1;
57074 return SQLITE_OK;
57078 if( pIdxKey ){
57079 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
57080 pIdxKey->errCode = 0;
57081 assert( pIdxKey->default_rc==1
57082 || pIdxKey->default_rc==0
57083 || pIdxKey->default_rc==-1
57085 }else{
57086 xRecordCompare = 0; /* All keys are integers */
57089 rc = moveToRoot(pCur);
57090 if( rc ){
57091 return rc;
57093 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
57094 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
57095 assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
57096 if( pCur->eState==CURSOR_INVALID ){
57097 *pRes = -1;
57098 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
57099 return SQLITE_OK;
57101 assert( pCur->apPage[0]->intKey || pIdxKey );
57102 for(;;){
57103 int lwr, upr, idx, c;
57104 Pgno chldPg;
57105 MemPage *pPage = pCur->apPage[pCur->iPage];
57106 u8 *pCell; /* Pointer to current cell in pPage */
57108 /* pPage->nCell must be greater than zero. If this is the root-page
57109 ** the cursor would have been INVALID above and this for(;;) loop
57110 ** not run. If this is not the root-page, then the moveToChild() routine
57111 ** would have already detected db corruption. Similarly, pPage must
57112 ** be the right kind (index or table) of b-tree page. Otherwise
57113 ** a moveToChild() or moveToRoot() call would have detected corruption. */
57114 assert( pPage->nCell>0 );
57115 assert( pPage->intKey==(pIdxKey==0) );
57116 lwr = 0;
57117 upr = pPage->nCell-1;
57118 assert( biasRight==0 || biasRight==1 );
57119 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
57120 pCur->aiIdx[pCur->iPage] = (u16)idx;
57121 if( xRecordCompare==0 ){
57122 for(;;){
57123 i64 nCellKey;
57124 pCell = findCell(pPage, idx) + pPage->childPtrSize;
57125 if( pPage->intKeyLeaf ){
57126 while( 0x80 <= *(pCell++) ){
57127 if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
57130 getVarint(pCell, (u64*)&nCellKey);
57131 if( nCellKey<intKey ){
57132 lwr = idx+1;
57133 if( lwr>upr ){ c = -1; break; }
57134 }else if( nCellKey>intKey ){
57135 upr = idx-1;
57136 if( lwr>upr ){ c = +1; break; }
57137 }else{
57138 assert( nCellKey==intKey );
57139 pCur->curFlags |= BTCF_ValidNKey;
57140 pCur->info.nKey = nCellKey;
57141 pCur->aiIdx[pCur->iPage] = (u16)idx;
57142 if( !pPage->leaf ){
57143 lwr = idx;
57144 goto moveto_next_layer;
57145 }else{
57146 *pRes = 0;
57147 rc = SQLITE_OK;
57148 goto moveto_finish;
57151 assert( lwr+upr>=0 );
57152 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
57154 }else{
57155 for(;;){
57156 int nCell;
57157 pCell = findCell(pPage, idx) + pPage->childPtrSize;
57159 /* The maximum supported page-size is 65536 bytes. This means that
57160 ** the maximum number of record bytes stored on an index B-Tree
57161 ** page is less than 16384 bytes and may be stored as a 2-byte
57162 ** varint. This information is used to attempt to avoid parsing
57163 ** the entire cell by checking for the cases where the record is
57164 ** stored entirely within the b-tree page by inspecting the first
57165 ** 2 bytes of the cell.
57167 nCell = pCell[0];
57168 if( nCell<=pPage->max1bytePayload ){
57169 /* This branch runs if the record-size field of the cell is a
57170 ** single byte varint and the record fits entirely on the main
57171 ** b-tree page. */
57172 testcase( pCell+nCell+1==pPage->aDataEnd );
57173 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
57174 }else if( !(pCell[1] & 0x80)
57175 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
57177 /* The record-size field is a 2 byte varint and the record
57178 ** fits entirely on the main b-tree page. */
57179 testcase( pCell+nCell+2==pPage->aDataEnd );
57180 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
57181 }else{
57182 /* The record flows over onto one or more overflow pages. In
57183 ** this case the whole cell needs to be parsed, a buffer allocated
57184 ** and accessPayload() used to retrieve the record into the
57185 ** buffer before VdbeRecordCompare() can be called. */
57186 void *pCellKey;
57187 u8 * const pCellBody = pCell - pPage->childPtrSize;
57188 btreeParseCellPtr(pPage, pCellBody, &pCur->info);
57189 nCell = (int)pCur->info.nKey;
57190 pCellKey = sqlite3Malloc( nCell );
57191 if( pCellKey==0 ){
57192 rc = SQLITE_NOMEM;
57193 goto moveto_finish;
57195 pCur->aiIdx[pCur->iPage] = (u16)idx;
57196 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
57197 if( rc ){
57198 sqlite3_free(pCellKey);
57199 goto moveto_finish;
57201 c = xRecordCompare(nCell, pCellKey, pIdxKey);
57202 sqlite3_free(pCellKey);
57204 assert(
57205 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
57206 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
57208 if( c<0 ){
57209 lwr = idx+1;
57210 }else if( c>0 ){
57211 upr = idx-1;
57212 }else{
57213 assert( c==0 );
57214 *pRes = 0;
57215 rc = SQLITE_OK;
57216 pCur->aiIdx[pCur->iPage] = (u16)idx;
57217 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
57218 goto moveto_finish;
57220 if( lwr>upr ) break;
57221 assert( lwr+upr>=0 );
57222 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
57225 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
57226 assert( pPage->isInit );
57227 if( pPage->leaf ){
57228 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
57229 pCur->aiIdx[pCur->iPage] = (u16)idx;
57230 *pRes = c;
57231 rc = SQLITE_OK;
57232 goto moveto_finish;
57234 moveto_next_layer:
57235 if( lwr>=pPage->nCell ){
57236 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
57237 }else{
57238 chldPg = get4byte(findCell(pPage, lwr));
57240 pCur->aiIdx[pCur->iPage] = (u16)lwr;
57241 rc = moveToChild(pCur, chldPg);
57242 if( rc ) break;
57244 moveto_finish:
57245 pCur->info.nSize = 0;
57246 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
57247 return rc;
57252 ** Return TRUE if the cursor is not pointing at an entry of the table.
57254 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
57255 ** past the last entry in the table or sqlite3BtreePrev() moves past
57256 ** the first entry. TRUE is also returned if the table is empty.
57258 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
57259 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
57260 ** have been deleted? This API will need to change to return an error code
57261 ** as well as the boolean result value.
57263 return (CURSOR_VALID!=pCur->eState);
57267 ** Advance the cursor to the next entry in the database. If
57268 ** successful then set *pRes=0. If the cursor
57269 ** was already pointing to the last entry in the database before
57270 ** this routine was called, then set *pRes=1.
57272 ** The main entry point is sqlite3BtreeNext(). That routine is optimized
57273 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
57274 ** to the next cell on the current page. The (slower) btreeNext() helper
57275 ** routine is called when it is necessary to move to a different page or
57276 ** to restore the cursor.
57278 ** The calling function will set *pRes to 0 or 1. The initial *pRes value
57279 ** will be 1 if the cursor being stepped corresponds to an SQL index and
57280 ** if this routine could have been skipped if that SQL index had been
57281 ** a unique index. Otherwise the caller will have set *pRes to zero.
57282 ** Zero is the common case. The btree implementation is free to use the
57283 ** initial *pRes value as a hint to improve performance, but the current
57284 ** SQLite btree implementation does not. (Note that the comdb2 btree
57285 ** implementation does use this hint, however.)
57287 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
57288 int rc;
57289 int idx;
57290 MemPage *pPage;
57292 assert( cursorHoldsMutex(pCur) );
57293 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
57294 assert( *pRes==0 );
57295 if( pCur->eState!=CURSOR_VALID ){
57296 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
57297 rc = restoreCursorPosition(pCur);
57298 if( rc!=SQLITE_OK ){
57299 return rc;
57301 if( CURSOR_INVALID==pCur->eState ){
57302 *pRes = 1;
57303 return SQLITE_OK;
57305 if( pCur->skipNext ){
57306 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
57307 pCur->eState = CURSOR_VALID;
57308 if( pCur->skipNext>0 ){
57309 pCur->skipNext = 0;
57310 return SQLITE_OK;
57312 pCur->skipNext = 0;
57316 pPage = pCur->apPage[pCur->iPage];
57317 idx = ++pCur->aiIdx[pCur->iPage];
57318 assert( pPage->isInit );
57320 /* If the database file is corrupt, it is possible for the value of idx
57321 ** to be invalid here. This can only occur if a second cursor modifies
57322 ** the page while cursor pCur is holding a reference to it. Which can
57323 ** only happen if the database is corrupt in such a way as to link the
57324 ** page into more than one b-tree structure. */
57325 testcase( idx>pPage->nCell );
57327 if( idx>=pPage->nCell ){
57328 if( !pPage->leaf ){
57329 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
57330 if( rc ) return rc;
57331 return moveToLeftmost(pCur);
57334 if( pCur->iPage==0 ){
57335 *pRes = 1;
57336 pCur->eState = CURSOR_INVALID;
57337 return SQLITE_OK;
57339 moveToParent(pCur);
57340 pPage = pCur->apPage[pCur->iPage];
57341 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
57342 if( pPage->intKey ){
57343 return sqlite3BtreeNext(pCur, pRes);
57344 }else{
57345 return SQLITE_OK;
57348 if( pPage->leaf ){
57349 return SQLITE_OK;
57350 }else{
57351 return moveToLeftmost(pCur);
57354 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
57355 MemPage *pPage;
57356 assert( cursorHoldsMutex(pCur) );
57357 assert( pRes!=0 );
57358 assert( *pRes==0 || *pRes==1 );
57359 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
57360 pCur->info.nSize = 0;
57361 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
57362 *pRes = 0;
57363 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
57364 pPage = pCur->apPage[pCur->iPage];
57365 if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
57366 pCur->aiIdx[pCur->iPage]--;
57367 return btreeNext(pCur, pRes);
57369 if( pPage->leaf ){
57370 return SQLITE_OK;
57371 }else{
57372 return moveToLeftmost(pCur);
57377 ** Step the cursor to the back to the previous entry in the database. If
57378 ** successful then set *pRes=0. If the cursor
57379 ** was already pointing to the first entry in the database before
57380 ** this routine was called, then set *pRes=1.
57382 ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
57383 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
57384 ** to the previous cell on the current page. The (slower) btreePrevious()
57385 ** helper routine is called when it is necessary to move to a different page
57386 ** or to restore the cursor.
57388 ** The calling function will set *pRes to 0 or 1. The initial *pRes value
57389 ** will be 1 if the cursor being stepped corresponds to an SQL index and
57390 ** if this routine could have been skipped if that SQL index had been
57391 ** a unique index. Otherwise the caller will have set *pRes to zero.
57392 ** Zero is the common case. The btree implementation is free to use the
57393 ** initial *pRes value as a hint to improve performance, but the current
57394 ** SQLite btree implementation does not. (Note that the comdb2 btree
57395 ** implementation does use this hint, however.)
57397 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
57398 int rc;
57399 MemPage *pPage;
57401 assert( cursorHoldsMutex(pCur) );
57402 assert( pRes!=0 );
57403 assert( *pRes==0 );
57404 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
57405 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
57406 assert( pCur->info.nSize==0 );
57407 if( pCur->eState!=CURSOR_VALID ){
57408 rc = restoreCursorPosition(pCur);
57409 if( rc!=SQLITE_OK ){
57410 return rc;
57412 if( CURSOR_INVALID==pCur->eState ){
57413 *pRes = 1;
57414 return SQLITE_OK;
57416 if( pCur->skipNext ){
57417 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
57418 pCur->eState = CURSOR_VALID;
57419 if( pCur->skipNext<0 ){
57420 pCur->skipNext = 0;
57421 return SQLITE_OK;
57423 pCur->skipNext = 0;
57427 pPage = pCur->apPage[pCur->iPage];
57428 assert( pPage->isInit );
57429 if( !pPage->leaf ){
57430 int idx = pCur->aiIdx[pCur->iPage];
57431 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
57432 if( rc ) return rc;
57433 rc = moveToRightmost(pCur);
57434 }else{
57435 while( pCur->aiIdx[pCur->iPage]==0 ){
57436 if( pCur->iPage==0 ){
57437 pCur->eState = CURSOR_INVALID;
57438 *pRes = 1;
57439 return SQLITE_OK;
57441 moveToParent(pCur);
57443 assert( pCur->info.nSize==0 );
57444 assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
57446 pCur->aiIdx[pCur->iPage]--;
57447 pPage = pCur->apPage[pCur->iPage];
57448 if( pPage->intKey && !pPage->leaf ){
57449 rc = sqlite3BtreePrevious(pCur, pRes);
57450 }else{
57451 rc = SQLITE_OK;
57454 return rc;
57456 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
57457 assert( cursorHoldsMutex(pCur) );
57458 assert( pRes!=0 );
57459 assert( *pRes==0 || *pRes==1 );
57460 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
57461 *pRes = 0;
57462 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
57463 pCur->info.nSize = 0;
57464 if( pCur->eState!=CURSOR_VALID
57465 || pCur->aiIdx[pCur->iPage]==0
57466 || pCur->apPage[pCur->iPage]->leaf==0
57468 return btreePrevious(pCur, pRes);
57470 pCur->aiIdx[pCur->iPage]--;
57471 return SQLITE_OK;
57475 ** Allocate a new page from the database file.
57477 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
57478 ** has already been called on the new page.) The new page has also
57479 ** been referenced and the calling routine is responsible for calling
57480 ** sqlite3PagerUnref() on the new page when it is done.
57482 ** SQLITE_OK is returned on success. Any other return value indicates
57483 ** an error. *ppPage and *pPgno are undefined in the event of an error.
57484 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
57486 ** If the "nearby" parameter is not 0, then an effort is made to
57487 ** locate a page close to the page number "nearby". This can be used in an
57488 ** attempt to keep related pages close to each other in the database file,
57489 ** which in turn can make database access faster.
57491 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
57492 ** anywhere on the free-list, then it is guaranteed to be returned. If
57493 ** eMode is BTALLOC_LT then the page returned will be less than or equal
57494 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
57495 ** are no restrictions on which page is returned.
57497 static int allocateBtreePage(
57498 BtShared *pBt, /* The btree */
57499 MemPage **ppPage, /* Store pointer to the allocated page here */
57500 Pgno *pPgno, /* Store the page number here */
57501 Pgno nearby, /* Search for a page near this one */
57502 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
57504 MemPage *pPage1;
57505 int rc;
57506 u32 n; /* Number of pages on the freelist */
57507 u32 k; /* Number of leaves on the trunk of the freelist */
57508 MemPage *pTrunk = 0;
57509 MemPage *pPrevTrunk = 0;
57510 Pgno mxPage; /* Total size of the database file */
57512 assert( sqlite3_mutex_held(pBt->mutex) );
57513 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
57514 pPage1 = pBt->pPage1;
57515 mxPage = btreePagecount(pBt);
57516 n = get4byte(&pPage1->aData[36]);
57517 testcase( n==mxPage-1 );
57518 if( n>=mxPage ){
57519 return SQLITE_CORRUPT_BKPT;
57521 if( n>0 ){
57522 /* There are pages on the freelist. Reuse one of those pages. */
57523 Pgno iTrunk;
57524 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
57526 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
57527 ** shows that the page 'nearby' is somewhere on the free-list, then
57528 ** the entire-list will be searched for that page.
57530 #ifndef SQLITE_OMIT_AUTOVACUUM
57531 if( eMode==BTALLOC_EXACT ){
57532 if( nearby<=mxPage ){
57533 u8 eType;
57534 assert( nearby>0 );
57535 assert( pBt->autoVacuum );
57536 rc = ptrmapGet(pBt, nearby, &eType, 0);
57537 if( rc ) return rc;
57538 if( eType==PTRMAP_FREEPAGE ){
57539 searchList = 1;
57542 }else if( eMode==BTALLOC_LE ){
57543 searchList = 1;
57545 #endif
57547 /* Decrement the free-list count by 1. Set iTrunk to the index of the
57548 ** first free-list trunk page. iPrevTrunk is initially 1.
57550 rc = sqlite3PagerWrite(pPage1->pDbPage);
57551 if( rc ) return rc;
57552 put4byte(&pPage1->aData[36], n-1);
57554 /* The code within this loop is run only once if the 'searchList' variable
57555 ** is not true. Otherwise, it runs once for each trunk-page on the
57556 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
57557 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
57559 do {
57560 pPrevTrunk = pTrunk;
57561 if( pPrevTrunk ){
57562 iTrunk = get4byte(&pPrevTrunk->aData[0]);
57563 }else{
57564 iTrunk = get4byte(&pPage1->aData[32]);
57566 testcase( iTrunk==mxPage );
57567 if( iTrunk>mxPage ){
57568 rc = SQLITE_CORRUPT_BKPT;
57569 }else{
57570 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
57572 if( rc ){
57573 pTrunk = 0;
57574 goto end_allocate_page;
57576 assert( pTrunk!=0 );
57577 assert( pTrunk->aData!=0 );
57579 k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
57580 if( k==0 && !searchList ){
57581 /* The trunk has no leaves and the list is not being searched.
57582 ** So extract the trunk page itself and use it as the newly
57583 ** allocated page */
57584 assert( pPrevTrunk==0 );
57585 rc = sqlite3PagerWrite(pTrunk->pDbPage);
57586 if( rc ){
57587 goto end_allocate_page;
57589 *pPgno = iTrunk;
57590 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
57591 *ppPage = pTrunk;
57592 pTrunk = 0;
57593 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
57594 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
57595 /* Value of k is out of range. Database corruption */
57596 rc = SQLITE_CORRUPT_BKPT;
57597 goto end_allocate_page;
57598 #ifndef SQLITE_OMIT_AUTOVACUUM
57599 }else if( searchList
57600 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
57602 /* The list is being searched and this trunk page is the page
57603 ** to allocate, regardless of whether it has leaves.
57605 *pPgno = iTrunk;
57606 *ppPage = pTrunk;
57607 searchList = 0;
57608 rc = sqlite3PagerWrite(pTrunk->pDbPage);
57609 if( rc ){
57610 goto end_allocate_page;
57612 if( k==0 ){
57613 if( !pPrevTrunk ){
57614 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
57615 }else{
57616 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
57617 if( rc!=SQLITE_OK ){
57618 goto end_allocate_page;
57620 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
57622 }else{
57623 /* The trunk page is required by the caller but it contains
57624 ** pointers to free-list leaves. The first leaf becomes a trunk
57625 ** page in this case.
57627 MemPage *pNewTrunk;
57628 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
57629 if( iNewTrunk>mxPage ){
57630 rc = SQLITE_CORRUPT_BKPT;
57631 goto end_allocate_page;
57633 testcase( iNewTrunk==mxPage );
57634 rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
57635 if( rc!=SQLITE_OK ){
57636 goto end_allocate_page;
57638 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
57639 if( rc!=SQLITE_OK ){
57640 releasePage(pNewTrunk);
57641 goto end_allocate_page;
57643 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
57644 put4byte(&pNewTrunk->aData[4], k-1);
57645 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
57646 releasePage(pNewTrunk);
57647 if( !pPrevTrunk ){
57648 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
57649 put4byte(&pPage1->aData[32], iNewTrunk);
57650 }else{
57651 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
57652 if( rc ){
57653 goto end_allocate_page;
57655 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
57658 pTrunk = 0;
57659 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
57660 #endif
57661 }else if( k>0 ){
57662 /* Extract a leaf from the trunk */
57663 u32 closest;
57664 Pgno iPage;
57665 unsigned char *aData = pTrunk->aData;
57666 if( nearby>0 ){
57667 u32 i;
57668 closest = 0;
57669 if( eMode==BTALLOC_LE ){
57670 for(i=0; i<k; i++){
57671 iPage = get4byte(&aData[8+i*4]);
57672 if( iPage<=nearby ){
57673 closest = i;
57674 break;
57677 }else{
57678 int dist;
57679 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
57680 for(i=1; i<k; i++){
57681 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
57682 if( d2<dist ){
57683 closest = i;
57684 dist = d2;
57688 }else{
57689 closest = 0;
57692 iPage = get4byte(&aData[8+closest*4]);
57693 testcase( iPage==mxPage );
57694 if( iPage>mxPage ){
57695 rc = SQLITE_CORRUPT_BKPT;
57696 goto end_allocate_page;
57698 testcase( iPage==mxPage );
57699 if( !searchList
57700 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
57702 int noContent;
57703 *pPgno = iPage;
57704 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
57705 ": %d more free pages\n",
57706 *pPgno, closest+1, k, pTrunk->pgno, n-1));
57707 rc = sqlite3PagerWrite(pTrunk->pDbPage);
57708 if( rc ) goto end_allocate_page;
57709 if( closest<k-1 ){
57710 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
57712 put4byte(&aData[4], k-1);
57713 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
57714 rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
57715 if( rc==SQLITE_OK ){
57716 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
57717 if( rc!=SQLITE_OK ){
57718 releasePage(*ppPage);
57721 searchList = 0;
57724 releasePage(pPrevTrunk);
57725 pPrevTrunk = 0;
57726 }while( searchList );
57727 }else{
57728 /* There are no pages on the freelist, so append a new page to the
57729 ** database image.
57731 ** Normally, new pages allocated by this block can be requested from the
57732 ** pager layer with the 'no-content' flag set. This prevents the pager
57733 ** from trying to read the pages content from disk. However, if the
57734 ** current transaction has already run one or more incremental-vacuum
57735 ** steps, then the page we are about to allocate may contain content
57736 ** that is required in the event of a rollback. In this case, do
57737 ** not set the no-content flag. This causes the pager to load and journal
57738 ** the current page content before overwriting it.
57740 ** Note that the pager will not actually attempt to load or journal
57741 ** content for any page that really does lie past the end of the database
57742 ** file on disk. So the effects of disabling the no-content optimization
57743 ** here are confined to those pages that lie between the end of the
57744 ** database image and the end of the database file.
57746 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
57748 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
57749 if( rc ) return rc;
57750 pBt->nPage++;
57751 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
57753 #ifndef SQLITE_OMIT_AUTOVACUUM
57754 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
57755 /* If *pPgno refers to a pointer-map page, allocate two new pages
57756 ** at the end of the file instead of one. The first allocated page
57757 ** becomes a new pointer-map page, the second is used by the caller.
57759 MemPage *pPg = 0;
57760 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
57761 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
57762 rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
57763 if( rc==SQLITE_OK ){
57764 rc = sqlite3PagerWrite(pPg->pDbPage);
57765 releasePage(pPg);
57767 if( rc ) return rc;
57768 pBt->nPage++;
57769 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
57771 #endif
57772 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
57773 *pPgno = pBt->nPage;
57775 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
57776 rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
57777 if( rc ) return rc;
57778 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
57779 if( rc!=SQLITE_OK ){
57780 releasePage(*ppPage);
57782 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
57785 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
57787 end_allocate_page:
57788 releasePage(pTrunk);
57789 releasePage(pPrevTrunk);
57790 if( rc==SQLITE_OK ){
57791 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
57792 releasePage(*ppPage);
57793 *ppPage = 0;
57794 return SQLITE_CORRUPT_BKPT;
57796 (*ppPage)->isInit = 0;
57797 }else{
57798 *ppPage = 0;
57800 assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
57801 return rc;
57805 ** This function is used to add page iPage to the database file free-list.
57806 ** It is assumed that the page is not already a part of the free-list.
57808 ** The value passed as the second argument to this function is optional.
57809 ** If the caller happens to have a pointer to the MemPage object
57810 ** corresponding to page iPage handy, it may pass it as the second value.
57811 ** Otherwise, it may pass NULL.
57813 ** If a pointer to a MemPage object is passed as the second argument,
57814 ** its reference count is not altered by this function.
57816 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
57817 MemPage *pTrunk = 0; /* Free-list trunk page */
57818 Pgno iTrunk = 0; /* Page number of free-list trunk page */
57819 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
57820 MemPage *pPage; /* Page being freed. May be NULL. */
57821 int rc; /* Return Code */
57822 int nFree; /* Initial number of pages on free-list */
57824 assert( sqlite3_mutex_held(pBt->mutex) );
57825 assert( iPage>1 );
57826 assert( !pMemPage || pMemPage->pgno==iPage );
57828 if( pMemPage ){
57829 pPage = pMemPage;
57830 sqlite3PagerRef(pPage->pDbPage);
57831 }else{
57832 pPage = btreePageLookup(pBt, iPage);
57835 /* Increment the free page count on pPage1 */
57836 rc = sqlite3PagerWrite(pPage1->pDbPage);
57837 if( rc ) goto freepage_out;
57838 nFree = get4byte(&pPage1->aData[36]);
57839 put4byte(&pPage1->aData[36], nFree+1);
57841 if( pBt->btsFlags & BTS_SECURE_DELETE ){
57842 /* If the secure_delete option is enabled, then
57843 ** always fully overwrite deleted information with zeros.
57845 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
57846 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
57848 goto freepage_out;
57850 memset(pPage->aData, 0, pPage->pBt->pageSize);
57853 /* If the database supports auto-vacuum, write an entry in the pointer-map
57854 ** to indicate that the page is free.
57856 if( ISAUTOVACUUM ){
57857 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
57858 if( rc ) goto freepage_out;
57861 /* Now manipulate the actual database free-list structure. There are two
57862 ** possibilities. If the free-list is currently empty, or if the first
57863 ** trunk page in the free-list is full, then this page will become a
57864 ** new free-list trunk page. Otherwise, it will become a leaf of the
57865 ** first trunk page in the current free-list. This block tests if it
57866 ** is possible to add the page as a new free-list leaf.
57868 if( nFree!=0 ){
57869 u32 nLeaf; /* Initial number of leaf cells on trunk page */
57871 iTrunk = get4byte(&pPage1->aData[32]);
57872 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
57873 if( rc!=SQLITE_OK ){
57874 goto freepage_out;
57877 nLeaf = get4byte(&pTrunk->aData[4]);
57878 assert( pBt->usableSize>32 );
57879 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
57880 rc = SQLITE_CORRUPT_BKPT;
57881 goto freepage_out;
57883 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
57884 /* In this case there is room on the trunk page to insert the page
57885 ** being freed as a new leaf.
57887 ** Note that the trunk page is not really full until it contains
57888 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
57889 ** coded. But due to a coding error in versions of SQLite prior to
57890 ** 3.6.0, databases with freelist trunk pages holding more than
57891 ** usableSize/4 - 8 entries will be reported as corrupt. In order
57892 ** to maintain backwards compatibility with older versions of SQLite,
57893 ** we will continue to restrict the number of entries to usableSize/4 - 8
57894 ** for now. At some point in the future (once everyone has upgraded
57895 ** to 3.6.0 or later) we should consider fixing the conditional above
57896 ** to read "usableSize/4-2" instead of "usableSize/4-8".
57898 rc = sqlite3PagerWrite(pTrunk->pDbPage);
57899 if( rc==SQLITE_OK ){
57900 put4byte(&pTrunk->aData[4], nLeaf+1);
57901 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
57902 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
57903 sqlite3PagerDontWrite(pPage->pDbPage);
57905 rc = btreeSetHasContent(pBt, iPage);
57907 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
57908 goto freepage_out;
57912 /* If control flows to this point, then it was not possible to add the
57913 ** the page being freed as a leaf page of the first trunk in the free-list.
57914 ** Possibly because the free-list is empty, or possibly because the
57915 ** first trunk in the free-list is full. Either way, the page being freed
57916 ** will become the new first trunk page in the free-list.
57918 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
57919 goto freepage_out;
57921 rc = sqlite3PagerWrite(pPage->pDbPage);
57922 if( rc!=SQLITE_OK ){
57923 goto freepage_out;
57925 put4byte(pPage->aData, iTrunk);
57926 put4byte(&pPage->aData[4], 0);
57927 put4byte(&pPage1->aData[32], iPage);
57928 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
57930 freepage_out:
57931 if( pPage ){
57932 pPage->isInit = 0;
57934 releasePage(pPage);
57935 releasePage(pTrunk);
57936 return rc;
57938 static void freePage(MemPage *pPage, int *pRC){
57939 if( (*pRC)==SQLITE_OK ){
57940 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
57945 ** Free any overflow pages associated with the given Cell. Write the
57946 ** local Cell size (the number of bytes on the original page, omitting
57947 ** overflow) into *pnSize.
57949 static int clearCell(
57950 MemPage *pPage, /* The page that contains the Cell */
57951 unsigned char *pCell, /* First byte of the Cell */
57952 u16 *pnSize /* Write the size of the Cell here */
57954 BtShared *pBt = pPage->pBt;
57955 CellInfo info;
57956 Pgno ovflPgno;
57957 int rc;
57958 int nOvfl;
57959 u32 ovflPageSize;
57961 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
57962 btreeParseCellPtr(pPage, pCell, &info);
57963 *pnSize = info.nSize;
57964 if( info.iOverflow==0 ){
57965 return SQLITE_OK; /* No overflow pages. Return without doing anything */
57967 if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
57968 return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
57970 ovflPgno = get4byte(&pCell[info.iOverflow]);
57971 assert( pBt->usableSize > 4 );
57972 ovflPageSize = pBt->usableSize - 4;
57973 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
57974 assert( ovflPgno==0 || nOvfl>0 );
57975 while( nOvfl-- ){
57976 Pgno iNext = 0;
57977 MemPage *pOvfl = 0;
57978 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
57979 /* 0 is not a legal page number and page 1 cannot be an
57980 ** overflow page. Therefore if ovflPgno<2 or past the end of the
57981 ** file the database must be corrupt. */
57982 return SQLITE_CORRUPT_BKPT;
57984 if( nOvfl ){
57985 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
57986 if( rc ) return rc;
57989 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
57990 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
57992 /* There is no reason any cursor should have an outstanding reference
57993 ** to an overflow page belonging to a cell that is being deleted/updated.
57994 ** So if there exists more than one reference to this page, then it
57995 ** must not really be an overflow page and the database must be corrupt.
57996 ** It is helpful to detect this before calling freePage2(), as
57997 ** freePage2() may zero the page contents if secure-delete mode is
57998 ** enabled. If this 'overflow' page happens to be a page that the
57999 ** caller is iterating through or using in some other way, this
58000 ** can be problematic.
58002 rc = SQLITE_CORRUPT_BKPT;
58003 }else{
58004 rc = freePage2(pBt, pOvfl, ovflPgno);
58007 if( pOvfl ){
58008 sqlite3PagerUnref(pOvfl->pDbPage);
58010 if( rc ) return rc;
58011 ovflPgno = iNext;
58013 return SQLITE_OK;
58017 ** Create the byte sequence used to represent a cell on page pPage
58018 ** and write that byte sequence into pCell[]. Overflow pages are
58019 ** allocated and filled in as necessary. The calling procedure
58020 ** is responsible for making sure sufficient space has been allocated
58021 ** for pCell[].
58023 ** Note that pCell does not necessary need to point to the pPage->aData
58024 ** area. pCell might point to some temporary storage. The cell will
58025 ** be constructed in this temporary area then copied into pPage->aData
58026 ** later.
58028 static int fillInCell(
58029 MemPage *pPage, /* The page that contains the cell */
58030 unsigned char *pCell, /* Complete text of the cell */
58031 const void *pKey, i64 nKey, /* The key */
58032 const void *pData,int nData, /* The data */
58033 int nZero, /* Extra zero bytes to append to pData */
58034 int *pnSize /* Write cell size here */
58036 int nPayload;
58037 const u8 *pSrc;
58038 int nSrc, n, rc;
58039 int spaceLeft;
58040 MemPage *pOvfl = 0;
58041 MemPage *pToRelease = 0;
58042 unsigned char *pPrior;
58043 unsigned char *pPayload;
58044 BtShared *pBt = pPage->pBt;
58045 Pgno pgnoOvfl = 0;
58046 int nHeader;
58048 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58050 /* pPage is not necessarily writeable since pCell might be auxiliary
58051 ** buffer space that is separate from the pPage buffer area */
58052 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
58053 || sqlite3PagerIswriteable(pPage->pDbPage) );
58055 /* Fill in the header. */
58056 nHeader = pPage->childPtrSize;
58057 nPayload = nData + nZero;
58058 if( pPage->intKeyLeaf ){
58059 nHeader += putVarint32(&pCell[nHeader], nPayload);
58060 }else{
58061 assert( nData==0 );
58062 assert( nZero==0 );
58064 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
58066 /* Fill in the payload size */
58067 if( pPage->intKey ){
58068 pSrc = pData;
58069 nSrc = nData;
58070 nData = 0;
58071 }else{
58072 if( NEVER(nKey>0x7fffffff || pKey==0) ){
58073 return SQLITE_CORRUPT_BKPT;
58075 nPayload = (int)nKey;
58076 pSrc = pKey;
58077 nSrc = (int)nKey;
58079 if( nPayload<=pPage->maxLocal ){
58080 n = nHeader + nPayload;
58081 testcase( n==3 );
58082 testcase( n==4 );
58083 if( n<4 ) n = 4;
58084 *pnSize = n;
58085 spaceLeft = nPayload;
58086 pPrior = pCell;
58087 }else{
58088 int mn = pPage->minLocal;
58089 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
58090 testcase( n==pPage->maxLocal );
58091 testcase( n==pPage->maxLocal+1 );
58092 if( n > pPage->maxLocal ) n = mn;
58093 spaceLeft = n;
58094 *pnSize = n + nHeader + 4;
58095 pPrior = &pCell[nHeader+n];
58097 pPayload = &pCell[nHeader];
58099 /* At this point variables should be set as follows:
58101 ** nPayload Total payload size in bytes
58102 ** pPayload Begin writing payload here
58103 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
58104 ** that means content must spill into overflow pages.
58105 ** *pnSize Size of the local cell (not counting overflow pages)
58106 ** pPrior Where to write the pgno of the first overflow page
58108 ** Use a call to btreeParseCellPtr() to verify that the values above
58109 ** were computed correctly.
58111 #if SQLITE_DEBUG
58113 CellInfo info;
58114 btreeParseCellPtr(pPage, pCell, &info);
58115 assert( nHeader=(int)(info.pPayload - pCell) );
58116 assert( info.nKey==nKey );
58117 assert( *pnSize == info.nSize );
58118 assert( spaceLeft == info.nLocal );
58119 assert( pPrior == &pCell[info.iOverflow] );
58121 #endif
58123 /* Write the payload into the local Cell and any extra into overflow pages */
58124 while( nPayload>0 ){
58125 if( spaceLeft==0 ){
58126 #ifndef SQLITE_OMIT_AUTOVACUUM
58127 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
58128 if( pBt->autoVacuum ){
58130 pgnoOvfl++;
58131 } while(
58132 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
58135 #endif
58136 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
58137 #ifndef SQLITE_OMIT_AUTOVACUUM
58138 /* If the database supports auto-vacuum, and the second or subsequent
58139 ** overflow page is being allocated, add an entry to the pointer-map
58140 ** for that page now.
58142 ** If this is the first overflow page, then write a partial entry
58143 ** to the pointer-map. If we write nothing to this pointer-map slot,
58144 ** then the optimistic overflow chain processing in clearCell()
58145 ** may misinterpret the uninitialized values and delete the
58146 ** wrong pages from the database.
58148 if( pBt->autoVacuum && rc==SQLITE_OK ){
58149 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
58150 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
58151 if( rc ){
58152 releasePage(pOvfl);
58155 #endif
58156 if( rc ){
58157 releasePage(pToRelease);
58158 return rc;
58161 /* If pToRelease is not zero than pPrior points into the data area
58162 ** of pToRelease. Make sure pToRelease is still writeable. */
58163 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
58165 /* If pPrior is part of the data area of pPage, then make sure pPage
58166 ** is still writeable */
58167 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
58168 || sqlite3PagerIswriteable(pPage->pDbPage) );
58170 put4byte(pPrior, pgnoOvfl);
58171 releasePage(pToRelease);
58172 pToRelease = pOvfl;
58173 pPrior = pOvfl->aData;
58174 put4byte(pPrior, 0);
58175 pPayload = &pOvfl->aData[4];
58176 spaceLeft = pBt->usableSize - 4;
58178 n = nPayload;
58179 if( n>spaceLeft ) n = spaceLeft;
58181 /* If pToRelease is not zero than pPayload points into the data area
58182 ** of pToRelease. Make sure pToRelease is still writeable. */
58183 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
58185 /* If pPayload is part of the data area of pPage, then make sure pPage
58186 ** is still writeable */
58187 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
58188 || sqlite3PagerIswriteable(pPage->pDbPage) );
58190 if( nSrc>0 ){
58191 if( n>nSrc ) n = nSrc;
58192 assert( pSrc );
58193 memcpy(pPayload, pSrc, n);
58194 }else{
58195 memset(pPayload, 0, n);
58197 nPayload -= n;
58198 pPayload += n;
58199 pSrc += n;
58200 nSrc -= n;
58201 spaceLeft -= n;
58202 if( nSrc==0 ){
58203 nSrc = nData;
58204 pSrc = pData;
58207 releasePage(pToRelease);
58208 return SQLITE_OK;
58212 ** Remove the i-th cell from pPage. This routine effects pPage only.
58213 ** The cell content is not freed or deallocated. It is assumed that
58214 ** the cell content has been copied someplace else. This routine just
58215 ** removes the reference to the cell from pPage.
58217 ** "sz" must be the number of bytes in the cell.
58219 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
58220 u32 pc; /* Offset to cell content of cell being deleted */
58221 u8 *data; /* pPage->aData */
58222 u8 *ptr; /* Used to move bytes around within data[] */
58223 int rc; /* The return code */
58224 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
58226 if( *pRC ) return;
58228 assert( idx>=0 && idx<pPage->nCell );
58229 assert( sz==cellSize(pPage, idx) );
58230 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
58231 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58232 data = pPage->aData;
58233 ptr = &pPage->aCellIdx[2*idx];
58234 pc = get2byte(ptr);
58235 hdr = pPage->hdrOffset;
58236 testcase( pc==get2byte(&data[hdr+5]) );
58237 testcase( pc+sz==pPage->pBt->usableSize );
58238 if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
58239 *pRC = SQLITE_CORRUPT_BKPT;
58240 return;
58242 rc = freeSpace(pPage, pc, sz);
58243 if( rc ){
58244 *pRC = rc;
58245 return;
58247 pPage->nCell--;
58248 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
58249 put2byte(&data[hdr+3], pPage->nCell);
58250 pPage->nFree += 2;
58254 ** Insert a new cell on pPage at cell index "i". pCell points to the
58255 ** content of the cell.
58257 ** If the cell content will fit on the page, then put it there. If it
58258 ** will not fit, then make a copy of the cell content into pTemp if
58259 ** pTemp is not null. Regardless of pTemp, allocate a new entry
58260 ** in pPage->apOvfl[] and make it point to the cell content (either
58261 ** in pTemp or the original pCell) and also record its index.
58262 ** Allocating a new entry in pPage->aCell[] implies that
58263 ** pPage->nOverflow is incremented.
58265 static void insertCell(
58266 MemPage *pPage, /* Page into which we are copying */
58267 int i, /* New cell becomes the i-th cell of the page */
58268 u8 *pCell, /* Content of the new cell */
58269 int sz, /* Bytes of content in pCell */
58270 u8 *pTemp, /* Temp storage space for pCell, if needed */
58271 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
58272 int *pRC /* Read and write return code from here */
58274 int idx = 0; /* Where to write new cell content in data[] */
58275 int j; /* Loop counter */
58276 int end; /* First byte past the last cell pointer in data[] */
58277 int ins; /* Index in data[] where new cell pointer is inserted */
58278 int cellOffset; /* Address of first cell pointer in data[] */
58279 u8 *data; /* The content of the whole page */
58281 if( *pRC ) return;
58283 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
58284 assert( MX_CELL(pPage->pBt)<=10921 );
58285 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
58286 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
58287 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
58288 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58289 /* The cell should normally be sized correctly. However, when moving a
58290 ** malformed cell from a leaf page to an interior page, if the cell size
58291 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
58292 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
58293 ** the term after the || in the following assert(). */
58294 assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
58295 if( pPage->nOverflow || sz+2>pPage->nFree ){
58296 if( pTemp ){
58297 memcpy(pTemp, pCell, sz);
58298 pCell = pTemp;
58300 if( iChild ){
58301 put4byte(pCell, iChild);
58303 j = pPage->nOverflow++;
58304 assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
58305 pPage->apOvfl[j] = pCell;
58306 pPage->aiOvfl[j] = (u16)i;
58307 }else{
58308 int rc = sqlite3PagerWrite(pPage->pDbPage);
58309 if( rc!=SQLITE_OK ){
58310 *pRC = rc;
58311 return;
58313 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
58314 data = pPage->aData;
58315 cellOffset = pPage->cellOffset;
58316 end = cellOffset + 2*pPage->nCell;
58317 ins = cellOffset + 2*i;
58318 rc = allocateSpace(pPage, sz, &idx);
58319 if( rc ){ *pRC = rc; return; }
58320 /* The allocateSpace() routine guarantees the following two properties
58321 ** if it returns success */
58322 assert( idx >= end+2 );
58323 assert( idx+sz <= (int)pPage->pBt->usableSize );
58324 pPage->nCell++;
58325 pPage->nFree -= (u16)(2 + sz);
58326 memcpy(&data[idx], pCell, sz);
58327 if( iChild ){
58328 put4byte(&data[idx], iChild);
58330 memmove(&data[ins+2], &data[ins], end-ins);
58331 put2byte(&data[ins], idx);
58332 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
58333 #ifndef SQLITE_OMIT_AUTOVACUUM
58334 if( pPage->pBt->autoVacuum ){
58335 /* The cell may contain a pointer to an overflow page. If so, write
58336 ** the entry for the overflow page into the pointer map.
58338 ptrmapPutOvflPtr(pPage, pCell, pRC);
58340 #endif
58345 ** Add a list of cells to a page. The page should be initially empty.
58346 ** The cells are guaranteed to fit on the page.
58348 static void assemblePage(
58349 MemPage *pPage, /* The page to be assembled */
58350 int nCell, /* The number of cells to add to this page */
58351 u8 **apCell, /* Pointers to cell bodies */
58352 u16 *aSize /* Sizes of the cells */
58354 int i; /* Loop counter */
58355 u8 *pCellptr; /* Address of next cell pointer */
58356 int cellbody; /* Address of next cell body */
58357 u8 * const data = pPage->aData; /* Pointer to data for pPage */
58358 const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
58359 const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
58361 assert( pPage->nOverflow==0 );
58362 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58363 assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
58364 && (int)MX_CELL(pPage->pBt)<=10921);
58365 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
58367 /* Check that the page has just been zeroed by zeroPage() */
58368 assert( pPage->nCell==0 );
58369 assert( get2byteNotZero(&data[hdr+5])==nUsable );
58371 pCellptr = &pPage->aCellIdx[nCell*2];
58372 cellbody = nUsable;
58373 for(i=nCell-1; i>=0; i--){
58374 u16 sz = aSize[i];
58375 pCellptr -= 2;
58376 cellbody -= sz;
58377 put2byte(pCellptr, cellbody);
58378 memcpy(&data[cellbody], apCell[i], sz);
58380 put2byte(&data[hdr+3], nCell);
58381 put2byte(&data[hdr+5], cellbody);
58382 pPage->nFree -= (nCell*2 + nUsable - cellbody);
58383 pPage->nCell = (u16)nCell;
58387 ** The following parameters determine how many adjacent pages get involved
58388 ** in a balancing operation. NN is the number of neighbors on either side
58389 ** of the page that participate in the balancing operation. NB is the
58390 ** total number of pages that participate, including the target page and
58391 ** NN neighbors on either side.
58393 ** The minimum value of NN is 1 (of course). Increasing NN above 1
58394 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
58395 ** in exchange for a larger degradation in INSERT and UPDATE performance.
58396 ** The value of NN appears to give the best results overall.
58398 #define NN 1 /* Number of neighbors on either side of pPage */
58399 #define NB (NN*2+1) /* Total pages involved in the balance */
58402 #ifndef SQLITE_OMIT_QUICKBALANCE
58404 ** This version of balance() handles the common special case where
58405 ** a new entry is being inserted on the extreme right-end of the
58406 ** tree, in other words, when the new entry will become the largest
58407 ** entry in the tree.
58409 ** Instead of trying to balance the 3 right-most leaf pages, just add
58410 ** a new page to the right-hand side and put the one new entry in
58411 ** that page. This leaves the right side of the tree somewhat
58412 ** unbalanced. But odds are that we will be inserting new entries
58413 ** at the end soon afterwards so the nearly empty page will quickly
58414 ** fill up. On average.
58416 ** pPage is the leaf page which is the right-most page in the tree.
58417 ** pParent is its parent. pPage must have a single overflow entry
58418 ** which is also the right-most entry on the page.
58420 ** The pSpace buffer is used to store a temporary copy of the divider
58421 ** cell that will be inserted into pParent. Such a cell consists of a 4
58422 ** byte page number followed by a variable length integer. In other
58423 ** words, at most 13 bytes. Hence the pSpace buffer must be at
58424 ** least 13 bytes in size.
58426 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
58427 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
58428 MemPage *pNew; /* Newly allocated page */
58429 int rc; /* Return Code */
58430 Pgno pgnoNew; /* Page number of pNew */
58432 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58433 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
58434 assert( pPage->nOverflow==1 );
58436 /* This error condition is now caught prior to reaching this function */
58437 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
58439 /* Allocate a new page. This page will become the right-sibling of
58440 ** pPage. Make the parent page writable, so that the new divider cell
58441 ** may be inserted. If both these operations are successful, proceed.
58443 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
58445 if( rc==SQLITE_OK ){
58447 u8 *pOut = &pSpace[4];
58448 u8 *pCell = pPage->apOvfl[0];
58449 u16 szCell = cellSizePtr(pPage, pCell);
58450 u8 *pStop;
58452 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
58453 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
58454 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
58455 assemblePage(pNew, 1, &pCell, &szCell);
58457 /* If this is an auto-vacuum database, update the pointer map
58458 ** with entries for the new page, and any pointer from the
58459 ** cell on the page to an overflow page. If either of these
58460 ** operations fails, the return code is set, but the contents
58461 ** of the parent page are still manipulated by thh code below.
58462 ** That is Ok, at this point the parent page is guaranteed to
58463 ** be marked as dirty. Returning an error code will cause a
58464 ** rollback, undoing any changes made to the parent page.
58466 if( ISAUTOVACUUM ){
58467 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
58468 if( szCell>pNew->minLocal ){
58469 ptrmapPutOvflPtr(pNew, pCell, &rc);
58473 /* Create a divider cell to insert into pParent. The divider cell
58474 ** consists of a 4-byte page number (the page number of pPage) and
58475 ** a variable length key value (which must be the same value as the
58476 ** largest key on pPage).
58478 ** To find the largest key value on pPage, first find the right-most
58479 ** cell on pPage. The first two fields of this cell are the
58480 ** record-length (a variable length integer at most 32-bits in size)
58481 ** and the key value (a variable length integer, may have any value).
58482 ** The first of the while(...) loops below skips over the record-length
58483 ** field. The second while(...) loop copies the key value from the
58484 ** cell on pPage into the pSpace buffer.
58486 pCell = findCell(pPage, pPage->nCell-1);
58487 pStop = &pCell[9];
58488 while( (*(pCell++)&0x80) && pCell<pStop );
58489 pStop = &pCell[9];
58490 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
58492 /* Insert the new divider cell into pParent. */
58493 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
58494 0, pPage->pgno, &rc);
58496 /* Set the right-child pointer of pParent to point to the new page. */
58497 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
58499 /* Release the reference to the new page. */
58500 releasePage(pNew);
58503 return rc;
58505 #endif /* SQLITE_OMIT_QUICKBALANCE */
58507 #if 0
58509 ** This function does not contribute anything to the operation of SQLite.
58510 ** it is sometimes activated temporarily while debugging code responsible
58511 ** for setting pointer-map entries.
58513 static int ptrmapCheckPages(MemPage **apPage, int nPage){
58514 int i, j;
58515 for(i=0; i<nPage; i++){
58516 Pgno n;
58517 u8 e;
58518 MemPage *pPage = apPage[i];
58519 BtShared *pBt = pPage->pBt;
58520 assert( pPage->isInit );
58522 for(j=0; j<pPage->nCell; j++){
58523 CellInfo info;
58524 u8 *z;
58526 z = findCell(pPage, j);
58527 btreeParseCellPtr(pPage, z, &info);
58528 if( info.iOverflow ){
58529 Pgno ovfl = get4byte(&z[info.iOverflow]);
58530 ptrmapGet(pBt, ovfl, &e, &n);
58531 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
58533 if( !pPage->leaf ){
58534 Pgno child = get4byte(z);
58535 ptrmapGet(pBt, child, &e, &n);
58536 assert( n==pPage->pgno && e==PTRMAP_BTREE );
58539 if( !pPage->leaf ){
58540 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
58541 ptrmapGet(pBt, child, &e, &n);
58542 assert( n==pPage->pgno && e==PTRMAP_BTREE );
58545 return 1;
58547 #endif
58550 ** This function is used to copy the contents of the b-tree node stored
58551 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
58552 ** the pointer-map entries for each child page are updated so that the
58553 ** parent page stored in the pointer map is page pTo. If pFrom contained
58554 ** any cells with overflow page pointers, then the corresponding pointer
58555 ** map entries are also updated so that the parent page is page pTo.
58557 ** If pFrom is currently carrying any overflow cells (entries in the
58558 ** MemPage.apOvfl[] array), they are not copied to pTo.
58560 ** Before returning, page pTo is reinitialized using btreeInitPage().
58562 ** The performance of this function is not critical. It is only used by
58563 ** the balance_shallower() and balance_deeper() procedures, neither of
58564 ** which are called often under normal circumstances.
58566 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
58567 if( (*pRC)==SQLITE_OK ){
58568 BtShared * const pBt = pFrom->pBt;
58569 u8 * const aFrom = pFrom->aData;
58570 u8 * const aTo = pTo->aData;
58571 int const iFromHdr = pFrom->hdrOffset;
58572 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
58573 int rc;
58574 int iData;
58577 assert( pFrom->isInit );
58578 assert( pFrom->nFree>=iToHdr );
58579 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
58581 /* Copy the b-tree node content from page pFrom to page pTo. */
58582 iData = get2byte(&aFrom[iFromHdr+5]);
58583 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
58584 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
58586 /* Reinitialize page pTo so that the contents of the MemPage structure
58587 ** match the new data. The initialization of pTo can actually fail under
58588 ** fairly obscure circumstances, even though it is a copy of initialized
58589 ** page pFrom.
58591 pTo->isInit = 0;
58592 rc = btreeInitPage(pTo);
58593 if( rc!=SQLITE_OK ){
58594 *pRC = rc;
58595 return;
58598 /* If this is an auto-vacuum database, update the pointer-map entries
58599 ** for any b-tree or overflow pages that pTo now contains the pointers to.
58601 if( ISAUTOVACUUM ){
58602 *pRC = setChildPtrmaps(pTo);
58608 ** This routine redistributes cells on the iParentIdx'th child of pParent
58609 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
58610 ** same amount of free space. Usually a single sibling on either side of the
58611 ** page are used in the balancing, though both siblings might come from one
58612 ** side if the page is the first or last child of its parent. If the page
58613 ** has fewer than 2 siblings (something which can only happen if the page
58614 ** is a root page or a child of a root page) then all available siblings
58615 ** participate in the balancing.
58617 ** The number of siblings of the page might be increased or decreased by
58618 ** one or two in an effort to keep pages nearly full but not over full.
58620 ** Note that when this routine is called, some of the cells on the page
58621 ** might not actually be stored in MemPage.aData[]. This can happen
58622 ** if the page is overfull. This routine ensures that all cells allocated
58623 ** to the page and its siblings fit into MemPage.aData[] before returning.
58625 ** In the course of balancing the page and its siblings, cells may be
58626 ** inserted into or removed from the parent page (pParent). Doing so
58627 ** may cause the parent page to become overfull or underfull. If this
58628 ** happens, it is the responsibility of the caller to invoke the correct
58629 ** balancing routine to fix this problem (see the balance() routine).
58631 ** If this routine fails for any reason, it might leave the database
58632 ** in a corrupted state. So if this routine fails, the database should
58633 ** be rolled back.
58635 ** The third argument to this function, aOvflSpace, is a pointer to a
58636 ** buffer big enough to hold one page. If while inserting cells into the parent
58637 ** page (pParent) the parent page becomes overfull, this buffer is
58638 ** used to store the parent's overflow cells. Because this function inserts
58639 ** a maximum of four divider cells into the parent page, and the maximum
58640 ** size of a cell stored within an internal node is always less than 1/4
58641 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
58642 ** enough for all overflow cells.
58644 ** If aOvflSpace is set to a null pointer, this function returns
58645 ** SQLITE_NOMEM.
58647 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
58648 #pragma optimize("", off)
58649 #endif
58650 static int balance_nonroot(
58651 MemPage *pParent, /* Parent page of siblings being balanced */
58652 int iParentIdx, /* Index of "the page" in pParent */
58653 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
58654 int isRoot, /* True if pParent is a root-page */
58655 int bBulk /* True if this call is part of a bulk load */
58657 BtShared *pBt; /* The whole database */
58658 int nCell = 0; /* Number of cells in apCell[] */
58659 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
58660 int nNew = 0; /* Number of pages in apNew[] */
58661 int nOld; /* Number of pages in apOld[] */
58662 int i, j, k; /* Loop counters */
58663 int nxDiv; /* Next divider slot in pParent->aCell[] */
58664 int rc = SQLITE_OK; /* The return code */
58665 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
58666 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
58667 int usableSpace; /* Bytes in pPage beyond the header */
58668 int pageFlags; /* Value of pPage->aData[0] */
58669 int subtotal; /* Subtotal of bytes in cells on one page */
58670 int iSpace1 = 0; /* First unused byte of aSpace1[] */
58671 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
58672 int szScratch; /* Size of scratch memory requested */
58673 MemPage *apOld[NB]; /* pPage and up to two siblings */
58674 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
58675 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
58676 u8 *pRight; /* Location in parent of right-sibling pointer */
58677 u8 *apDiv[NB-1]; /* Divider cells in pParent */
58678 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
58679 int szNew[NB+2]; /* Combined size of cells place on i-th page */
58680 u8 **apCell = 0; /* All cells begin balanced */
58681 u16 *szCell; /* Local size of all cells in apCell[] */
58682 u8 *aSpace1; /* Space for copies of dividers cells */
58683 Pgno pgno; /* Temp var to store a page number in */
58685 pBt = pParent->pBt;
58686 assert( sqlite3_mutex_held(pBt->mutex) );
58687 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
58689 #if 0
58690 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
58691 #endif
58693 /* At this point pParent may have at most one overflow cell. And if
58694 ** this overflow cell is present, it must be the cell with
58695 ** index iParentIdx. This scenario comes about when this function
58696 ** is called (indirectly) from sqlite3BtreeDelete().
58698 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
58699 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
58701 if( !aOvflSpace ){
58702 return SQLITE_NOMEM;
58705 /* Find the sibling pages to balance. Also locate the cells in pParent
58706 ** that divide the siblings. An attempt is made to find NN siblings on
58707 ** either side of pPage. More siblings are taken from one side, however,
58708 ** if there are fewer than NN siblings on the other side. If pParent
58709 ** has NB or fewer children then all children of pParent are taken.
58711 ** This loop also drops the divider cells from the parent page. This
58712 ** way, the remainder of the function does not have to deal with any
58713 ** overflow cells in the parent page, since if any existed they will
58714 ** have already been removed.
58716 i = pParent->nOverflow + pParent->nCell;
58717 if( i<2 ){
58718 nxDiv = 0;
58719 }else{
58720 assert( bBulk==0 || bBulk==1 );
58721 if( iParentIdx==0 ){
58722 nxDiv = 0;
58723 }else if( iParentIdx==i ){
58724 nxDiv = i-2+bBulk;
58725 }else{
58726 assert( bBulk==0 );
58727 nxDiv = iParentIdx-1;
58729 i = 2-bBulk;
58731 nOld = i+1;
58732 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
58733 pRight = &pParent->aData[pParent->hdrOffset+8];
58734 }else{
58735 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
58737 pgno = get4byte(pRight);
58738 while( 1 ){
58739 rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
58740 if( rc ){
58741 memset(apOld, 0, (i+1)*sizeof(MemPage*));
58742 goto balance_cleanup;
58744 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
58745 if( (i--)==0 ) break;
58747 if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
58748 apDiv[i] = pParent->apOvfl[0];
58749 pgno = get4byte(apDiv[i]);
58750 szNew[i] = cellSizePtr(pParent, apDiv[i]);
58751 pParent->nOverflow = 0;
58752 }else{
58753 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
58754 pgno = get4byte(apDiv[i]);
58755 szNew[i] = cellSizePtr(pParent, apDiv[i]);
58757 /* Drop the cell from the parent page. apDiv[i] still points to
58758 ** the cell within the parent, even though it has been dropped.
58759 ** This is safe because dropping a cell only overwrites the first
58760 ** four bytes of it, and this function does not need the first
58761 ** four bytes of the divider cell. So the pointer is safe to use
58762 ** later on.
58764 ** But not if we are in secure-delete mode. In secure-delete mode,
58765 ** the dropCell() routine will overwrite the entire cell with zeroes.
58766 ** In this case, temporarily copy the cell into the aOvflSpace[]
58767 ** buffer. It will be copied out again as soon as the aSpace[] buffer
58768 ** is allocated. */
58769 if( pBt->btsFlags & BTS_SECURE_DELETE ){
58770 int iOff;
58772 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
58773 if( (iOff+szNew[i])>(int)pBt->usableSize ){
58774 rc = SQLITE_CORRUPT_BKPT;
58775 memset(apOld, 0, (i+1)*sizeof(MemPage*));
58776 goto balance_cleanup;
58777 }else{
58778 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
58779 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
58782 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
58786 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
58787 ** alignment */
58788 nMaxCells = (nMaxCells + 3)&~3;
58791 ** Allocate space for memory structures
58793 k = pBt->pageSize + ROUND8(sizeof(MemPage));
58794 szScratch =
58795 nMaxCells*sizeof(u8*) /* apCell */
58796 + nMaxCells*sizeof(u16) /* szCell */
58797 + pBt->pageSize /* aSpace1 */
58798 + k*nOld; /* Page copies (apCopy) */
58799 apCell = sqlite3ScratchMalloc( szScratch );
58800 if( apCell==0 ){
58801 rc = SQLITE_NOMEM;
58802 goto balance_cleanup;
58804 szCell = (u16*)&apCell[nMaxCells];
58805 aSpace1 = (u8*)&szCell[nMaxCells];
58806 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
58809 ** Load pointers to all cells on sibling pages and the divider cells
58810 ** into the local apCell[] array. Make copies of the divider cells
58811 ** into space obtained from aSpace1[] and remove the divider cells
58812 ** from pParent.
58814 ** If the siblings are on leaf pages, then the child pointers of the
58815 ** divider cells are stripped from the cells before they are copied
58816 ** into aSpace1[]. In this way, all cells in apCell[] are without
58817 ** child pointers. If siblings are not leaves, then all cell in
58818 ** apCell[] include child pointers. Either way, all cells in apCell[]
58819 ** are alike.
58821 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
58822 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
58824 leafCorrection = apOld[0]->leaf*4;
58825 leafData = apOld[0]->intKeyLeaf;
58826 for(i=0; i<nOld; i++){
58827 int limit;
58829 /* Before doing anything else, take a copy of the i'th original sibling
58830 ** The rest of this function will use data from the copies rather
58831 ** that the original pages since the original pages will be in the
58832 ** process of being overwritten. */
58833 MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
58834 memcpy(pOld, apOld[i], sizeof(MemPage));
58835 pOld->aData = (void*)&pOld[1];
58836 memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
58838 limit = pOld->nCell+pOld->nOverflow;
58839 if( pOld->nOverflow>0 ){
58840 for(j=0; j<limit; j++){
58841 assert( nCell<nMaxCells );
58842 apCell[nCell] = findOverflowCell(pOld, j);
58843 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
58844 nCell++;
58846 }else{
58847 u8 *aData = pOld->aData;
58848 u16 maskPage = pOld->maskPage;
58849 u16 cellOffset = pOld->cellOffset;
58850 for(j=0; j<limit; j++){
58851 assert( nCell<nMaxCells );
58852 apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
58853 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
58854 nCell++;
58857 if( i<nOld-1 && !leafData){
58858 u16 sz = (u16)szNew[i];
58859 u8 *pTemp;
58860 assert( nCell<nMaxCells );
58861 szCell[nCell] = sz;
58862 pTemp = &aSpace1[iSpace1];
58863 iSpace1 += sz;
58864 assert( sz<=pBt->maxLocal+23 );
58865 assert( iSpace1 <= (int)pBt->pageSize );
58866 memcpy(pTemp, apDiv[i], sz);
58867 apCell[nCell] = pTemp+leafCorrection;
58868 assert( leafCorrection==0 || leafCorrection==4 );
58869 szCell[nCell] = szCell[nCell] - leafCorrection;
58870 if( !pOld->leaf ){
58871 assert( leafCorrection==0 );
58872 assert( pOld->hdrOffset==0 );
58873 /* The right pointer of the child page pOld becomes the left
58874 ** pointer of the divider cell */
58875 memcpy(apCell[nCell], &pOld->aData[8], 4);
58876 }else{
58877 assert( leafCorrection==4 );
58878 if( szCell[nCell]<4 ){
58879 /* Do not allow any cells smaller than 4 bytes. */
58880 szCell[nCell] = 4;
58883 nCell++;
58888 ** Figure out the number of pages needed to hold all nCell cells.
58889 ** Store this number in "k". Also compute szNew[] which is the total
58890 ** size of all cells on the i-th page and cntNew[] which is the index
58891 ** in apCell[] of the cell that divides page i from page i+1.
58892 ** cntNew[k] should equal nCell.
58894 ** Values computed by this block:
58896 ** k: The total number of sibling pages
58897 ** szNew[i]: Spaced used on the i-th sibling page.
58898 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
58899 ** the right of the i-th sibling page.
58900 ** usableSpace: Number of bytes of space available on each sibling.
58903 usableSpace = pBt->usableSize - 12 + leafCorrection;
58904 for(subtotal=k=i=0; i<nCell; i++){
58905 assert( i<nMaxCells );
58906 subtotal += szCell[i] + 2;
58907 if( subtotal > usableSpace ){
58908 szNew[k] = subtotal - szCell[i];
58909 cntNew[k] = i;
58910 if( leafData ){ i--; }
58911 subtotal = 0;
58912 k++;
58913 if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
58916 szNew[k] = subtotal;
58917 cntNew[k] = nCell;
58918 k++;
58921 ** The packing computed by the previous block is biased toward the siblings
58922 ** on the left side. The left siblings are always nearly full, while the
58923 ** right-most sibling might be nearly empty. This block of code attempts
58924 ** to adjust the packing of siblings to get a better balance.
58926 ** This adjustment is more than an optimization. The packing above might
58927 ** be so out of balance as to be illegal. For example, the right-most
58928 ** sibling might be completely empty. This adjustment is not optional.
58930 for(i=k-1; i>0; i--){
58931 int szRight = szNew[i]; /* Size of sibling on the right */
58932 int szLeft = szNew[i-1]; /* Size of sibling on the left */
58933 int r; /* Index of right-most cell in left sibling */
58934 int d; /* Index of first cell to the left of right sibling */
58936 r = cntNew[i-1] - 1;
58937 d = r + 1 - leafData;
58938 assert( d<nMaxCells );
58939 assert( r<nMaxCells );
58940 while( szRight==0
58941 || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
58943 szRight += szCell[d] + 2;
58944 szLeft -= szCell[r] + 2;
58945 cntNew[i-1]--;
58946 r = cntNew[i-1] - 1;
58947 d = r + 1 - leafData;
58949 szNew[i] = szRight;
58950 szNew[i-1] = szLeft;
58953 /* Either we found one or more cells (cntnew[0])>0) or pPage is
58954 ** a virtual root page. A virtual root page is when the real root
58955 ** page is page 1 and we are the only child of that page.
58957 ** UPDATE: The assert() below is not necessarily true if the database
58958 ** file is corrupt. The corruption will be detected and reported later
58959 ** in this procedure so there is no need to act upon it now.
58961 #if 0
58962 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
58963 #endif
58965 TRACE(("BALANCE: old: %d %d %d ",
58966 apOld[0]->pgno,
58967 nOld>=2 ? apOld[1]->pgno : 0,
58968 nOld>=3 ? apOld[2]->pgno : 0
58972 ** Allocate k new pages. Reuse old pages where possible.
58974 if( apOld[0]->pgno<=1 ){
58975 rc = SQLITE_CORRUPT_BKPT;
58976 goto balance_cleanup;
58978 pageFlags = apOld[0]->aData[0];
58979 for(i=0; i<k; i++){
58980 MemPage *pNew;
58981 if( i<nOld ){
58982 pNew = apNew[i] = apOld[i];
58983 apOld[i] = 0;
58984 rc = sqlite3PagerWrite(pNew->pDbPage);
58985 nNew++;
58986 if( rc ) goto balance_cleanup;
58987 }else{
58988 assert( i>0 );
58989 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
58990 if( rc ) goto balance_cleanup;
58991 apNew[i] = pNew;
58992 nNew++;
58994 /* Set the pointer-map entry for the new sibling page. */
58995 if( ISAUTOVACUUM ){
58996 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
58997 if( rc!=SQLITE_OK ){
58998 goto balance_cleanup;
59004 /* Free any old pages that were not reused as new pages.
59006 while( i<nOld ){
59007 freePage(apOld[i], &rc);
59008 if( rc ) goto balance_cleanup;
59009 releasePage(apOld[i]);
59010 apOld[i] = 0;
59011 i++;
59015 ** Put the new pages in ascending order. This helps to
59016 ** keep entries in the disk file in order so that a scan
59017 ** of the table is a linear scan through the file. That
59018 ** in turn helps the operating system to deliver pages
59019 ** from the disk more rapidly.
59021 ** An O(n^2) insertion sort algorithm is used, but since
59022 ** n is never more than NB (a small constant), that should
59023 ** not be a problem.
59025 ** When NB==3, this one optimization makes the database
59026 ** about 25% faster for large insertions and deletions.
59028 for(i=0; i<k-1; i++){
59029 int minV = apNew[i]->pgno;
59030 int minI = i;
59031 for(j=i+1; j<k; j++){
59032 if( apNew[j]->pgno<(unsigned)minV ){
59033 minI = j;
59034 minV = apNew[j]->pgno;
59037 if( minI>i ){
59038 MemPage *pT;
59039 pT = apNew[i];
59040 apNew[i] = apNew[minI];
59041 apNew[minI] = pT;
59044 TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
59045 apNew[0]->pgno, szNew[0],
59046 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
59047 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
59048 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
59049 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
59051 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
59052 put4byte(pRight, apNew[nNew-1]->pgno);
59055 ** Evenly distribute the data in apCell[] across the new pages.
59056 ** Insert divider cells into pParent as necessary.
59058 j = 0;
59059 for(i=0; i<nNew; i++){
59060 /* Assemble the new sibling page. */
59061 MemPage *pNew = apNew[i];
59062 assert( j<nMaxCells );
59063 zeroPage(pNew, pageFlags);
59064 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
59065 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
59066 assert( pNew->nOverflow==0 );
59068 j = cntNew[i];
59070 /* If the sibling page assembled above was not the right-most sibling,
59071 ** insert a divider cell into the parent page.
59073 assert( i<nNew-1 || j==nCell );
59074 if( j<nCell ){
59075 u8 *pCell;
59076 u8 *pTemp;
59077 int sz;
59079 assert( j<nMaxCells );
59080 pCell = apCell[j];
59081 sz = szCell[j] + leafCorrection;
59082 pTemp = &aOvflSpace[iOvflSpace];
59083 if( !pNew->leaf ){
59084 memcpy(&pNew->aData[8], pCell, 4);
59085 }else if( leafData ){
59086 /* If the tree is a leaf-data tree, and the siblings are leaves,
59087 ** then there is no divider cell in apCell[]. Instead, the divider
59088 ** cell consists of the integer key for the right-most cell of
59089 ** the sibling-page assembled above only.
59091 CellInfo info;
59092 j--;
59093 btreeParseCellPtr(pNew, apCell[j], &info);
59094 pCell = pTemp;
59095 sz = 4 + putVarint(&pCell[4], info.nKey);
59096 pTemp = 0;
59097 }else{
59098 pCell -= 4;
59099 /* Obscure case for non-leaf-data trees: If the cell at pCell was
59100 ** previously stored on a leaf node, and its reported size was 4
59101 ** bytes, then it may actually be smaller than this
59102 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
59103 ** any cell). But it is important to pass the correct size to
59104 ** insertCell(), so reparse the cell now.
59106 ** Note that this can never happen in an SQLite data file, as all
59107 ** cells are at least 4 bytes. It only happens in b-trees used
59108 ** to evaluate "IN (SELECT ...)" and similar clauses.
59110 if( szCell[j]==4 ){
59111 assert(leafCorrection==4);
59112 sz = cellSizePtr(pParent, pCell);
59115 iOvflSpace += sz;
59116 assert( sz<=pBt->maxLocal+23 );
59117 assert( iOvflSpace <= (int)pBt->pageSize );
59118 insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
59119 if( rc!=SQLITE_OK ) goto balance_cleanup;
59120 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
59122 j++;
59123 nxDiv++;
59126 assert( j==nCell );
59127 assert( nOld>0 );
59128 assert( nNew>0 );
59129 if( (pageFlags & PTF_LEAF)==0 ){
59130 u8 *zChild = &apCopy[nOld-1]->aData[8];
59131 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
59134 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
59135 /* The root page of the b-tree now contains no cells. The only sibling
59136 ** page is the right-child of the parent. Copy the contents of the
59137 ** child page into the parent, decreasing the overall height of the
59138 ** b-tree structure by one. This is described as the "balance-shallower"
59139 ** sub-algorithm in some documentation.
59141 ** If this is an auto-vacuum database, the call to copyNodeContent()
59142 ** sets all pointer-map entries corresponding to database image pages
59143 ** for which the pointer is stored within the content being copied.
59145 ** The second assert below verifies that the child page is defragmented
59146 ** (it must be, as it was just reconstructed using assemblePage()). This
59147 ** is important if the parent page happens to be page 1 of the database
59148 ** image. */
59149 assert( nNew==1 );
59150 assert( apNew[0]->nFree ==
59151 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
59153 copyNodeContent(apNew[0], pParent, &rc);
59154 freePage(apNew[0], &rc);
59155 }else if( ISAUTOVACUUM ){
59156 /* Fix the pointer-map entries for all the cells that were shifted around.
59157 ** There are several different types of pointer-map entries that need to
59158 ** be dealt with by this routine. Some of these have been set already, but
59159 ** many have not. The following is a summary:
59161 ** 1) The entries associated with new sibling pages that were not
59162 ** siblings when this function was called. These have already
59163 ** been set. We don't need to worry about old siblings that were
59164 ** moved to the free-list - the freePage() code has taken care
59165 ** of those.
59167 ** 2) The pointer-map entries associated with the first overflow
59168 ** page in any overflow chains used by new divider cells. These
59169 ** have also already been taken care of by the insertCell() code.
59171 ** 3) If the sibling pages are not leaves, then the child pages of
59172 ** cells stored on the sibling pages may need to be updated.
59174 ** 4) If the sibling pages are not internal intkey nodes, then any
59175 ** overflow pages used by these cells may need to be updated
59176 ** (internal intkey nodes never contain pointers to overflow pages).
59178 ** 5) If the sibling pages are not leaves, then the pointer-map
59179 ** entries for the right-child pages of each sibling may need
59180 ** to be updated.
59182 ** Cases 1 and 2 are dealt with above by other code. The next
59183 ** block deals with cases 3 and 4 and the one after that, case 5. Since
59184 ** setting a pointer map entry is a relatively expensive operation, this
59185 ** code only sets pointer map entries for child or overflow pages that have
59186 ** actually moved between pages. */
59187 MemPage *pNew = apNew[0];
59188 MemPage *pOld = apCopy[0];
59189 int nOverflow = pOld->nOverflow;
59190 int iNextOld = pOld->nCell + nOverflow;
59191 int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
59192 j = 0; /* Current 'old' sibling page */
59193 k = 0; /* Current 'new' sibling page */
59194 for(i=0; i<nCell; i++){
59195 int isDivider = 0;
59196 while( i==iNextOld ){
59197 /* Cell i is the cell immediately following the last cell on old
59198 ** sibling page j. If the siblings are not leaf pages of an
59199 ** intkey b-tree, then cell i was a divider cell. */
59200 assert( j+1 < ArraySize(apCopy) );
59201 assert( j+1 < nOld );
59202 pOld = apCopy[++j];
59203 iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
59204 if( pOld->nOverflow ){
59205 nOverflow = pOld->nOverflow;
59206 iOverflow = i + !leafData + pOld->aiOvfl[0];
59208 isDivider = !leafData;
59211 assert(nOverflow>0 || iOverflow<i );
59212 assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
59213 assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
59214 if( i==iOverflow ){
59215 isDivider = 1;
59216 if( (--nOverflow)>0 ){
59217 iOverflow++;
59221 if( i==cntNew[k] ){
59222 /* Cell i is the cell immediately following the last cell on new
59223 ** sibling page k. If the siblings are not leaf pages of an
59224 ** intkey b-tree, then cell i is a divider cell. */
59225 pNew = apNew[++k];
59226 if( !leafData ) continue;
59228 assert( j<nOld );
59229 assert( k<nNew );
59231 /* If the cell was originally divider cell (and is not now) or
59232 ** an overflow cell, or if the cell was located on a different sibling
59233 ** page before the balancing, then the pointer map entries associated
59234 ** with any child or overflow pages need to be updated. */
59235 if( isDivider || pOld->pgno!=pNew->pgno ){
59236 if( !leafCorrection ){
59237 ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
59239 if( szCell[i]>pNew->minLocal ){
59240 ptrmapPutOvflPtr(pNew, apCell[i], &rc);
59245 if( !leafCorrection ){
59246 for(i=0; i<nNew; i++){
59247 u32 key = get4byte(&apNew[i]->aData[8]);
59248 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
59252 #if 0
59253 /* The ptrmapCheckPages() contains assert() statements that verify that
59254 ** all pointer map pages are set correctly. This is helpful while
59255 ** debugging. This is usually disabled because a corrupt database may
59256 ** cause an assert() statement to fail. */
59257 ptrmapCheckPages(apNew, nNew);
59258 ptrmapCheckPages(&pParent, 1);
59259 #endif
59262 assert( pParent->isInit );
59263 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
59264 nOld, nNew, nCell));
59267 ** Cleanup before returning.
59269 balance_cleanup:
59270 sqlite3ScratchFree(apCell);
59271 for(i=0; i<nOld; i++){
59272 releasePage(apOld[i]);
59274 for(i=0; i<nNew; i++){
59275 releasePage(apNew[i]);
59278 return rc;
59280 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
59281 #pragma optimize("", on)
59282 #endif
59286 ** This function is called when the root page of a b-tree structure is
59287 ** overfull (has one or more overflow pages).
59289 ** A new child page is allocated and the contents of the current root
59290 ** page, including overflow cells, are copied into the child. The root
59291 ** page is then overwritten to make it an empty page with the right-child
59292 ** pointer pointing to the new page.
59294 ** Before returning, all pointer-map entries corresponding to pages
59295 ** that the new child-page now contains pointers to are updated. The
59296 ** entry corresponding to the new right-child pointer of the root
59297 ** page is also updated.
59299 ** If successful, *ppChild is set to contain a reference to the child
59300 ** page and SQLITE_OK is returned. In this case the caller is required
59301 ** to call releasePage() on *ppChild exactly once. If an error occurs,
59302 ** an error code is returned and *ppChild is set to 0.
59304 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
59305 int rc; /* Return value from subprocedures */
59306 MemPage *pChild = 0; /* Pointer to a new child page */
59307 Pgno pgnoChild = 0; /* Page number of the new child page */
59308 BtShared *pBt = pRoot->pBt; /* The BTree */
59310 assert( pRoot->nOverflow>0 );
59311 assert( sqlite3_mutex_held(pBt->mutex) );
59313 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
59314 ** page that will become the new right-child of pPage. Copy the contents
59315 ** of the node stored on pRoot into the new child page.
59317 rc = sqlite3PagerWrite(pRoot->pDbPage);
59318 if( rc==SQLITE_OK ){
59319 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
59320 copyNodeContent(pRoot, pChild, &rc);
59321 if( ISAUTOVACUUM ){
59322 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
59325 if( rc ){
59326 *ppChild = 0;
59327 releasePage(pChild);
59328 return rc;
59330 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
59331 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
59332 assert( pChild->nCell==pRoot->nCell );
59334 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
59336 /* Copy the overflow cells from pRoot to pChild */
59337 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
59338 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
59339 memcpy(pChild->apOvfl, pRoot->apOvfl,
59340 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
59341 pChild->nOverflow = pRoot->nOverflow;
59343 /* Zero the contents of pRoot. Then install pChild as the right-child. */
59344 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
59345 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
59347 *ppChild = pChild;
59348 return SQLITE_OK;
59352 ** The page that pCur currently points to has just been modified in
59353 ** some way. This function figures out if this modification means the
59354 ** tree needs to be balanced, and if so calls the appropriate balancing
59355 ** routine. Balancing routines are:
59357 ** balance_quick()
59358 ** balance_deeper()
59359 ** balance_nonroot()
59361 static int balance(BtCursor *pCur){
59362 int rc = SQLITE_OK;
59363 const int nMin = pCur->pBt->usableSize * 2 / 3;
59364 u8 aBalanceQuickSpace[13];
59365 u8 *pFree = 0;
59367 TESTONLY( int balance_quick_called = 0 );
59368 TESTONLY( int balance_deeper_called = 0 );
59370 do {
59371 int iPage = pCur->iPage;
59372 MemPage *pPage = pCur->apPage[iPage];
59374 if( iPage==0 ){
59375 if( pPage->nOverflow ){
59376 /* The root page of the b-tree is overfull. In this case call the
59377 ** balance_deeper() function to create a new child for the root-page
59378 ** and copy the current contents of the root-page to it. The
59379 ** next iteration of the do-loop will balance the child page.
59381 assert( (balance_deeper_called++)==0 );
59382 rc = balance_deeper(pPage, &pCur->apPage[1]);
59383 if( rc==SQLITE_OK ){
59384 pCur->iPage = 1;
59385 pCur->aiIdx[0] = 0;
59386 pCur->aiIdx[1] = 0;
59387 assert( pCur->apPage[1]->nOverflow );
59389 }else{
59390 break;
59392 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
59393 break;
59394 }else{
59395 MemPage * const pParent = pCur->apPage[iPage-1];
59396 int const iIdx = pCur->aiIdx[iPage-1];
59398 rc = sqlite3PagerWrite(pParent->pDbPage);
59399 if( rc==SQLITE_OK ){
59400 #ifndef SQLITE_OMIT_QUICKBALANCE
59401 if( pPage->intKeyLeaf
59402 && pPage->nOverflow==1
59403 && pPage->aiOvfl[0]==pPage->nCell
59404 && pParent->pgno!=1
59405 && pParent->nCell==iIdx
59407 /* Call balance_quick() to create a new sibling of pPage on which
59408 ** to store the overflow cell. balance_quick() inserts a new cell
59409 ** into pParent, which may cause pParent overflow. If this
59410 ** happens, the next iteration of the do-loop will balance pParent
59411 ** use either balance_nonroot() or balance_deeper(). Until this
59412 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
59413 ** buffer.
59415 ** The purpose of the following assert() is to check that only a
59416 ** single call to balance_quick() is made for each call to this
59417 ** function. If this were not verified, a subtle bug involving reuse
59418 ** of the aBalanceQuickSpace[] might sneak in.
59420 assert( (balance_quick_called++)==0 );
59421 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
59422 }else
59423 #endif
59425 /* In this case, call balance_nonroot() to redistribute cells
59426 ** between pPage and up to 2 of its sibling pages. This involves
59427 ** modifying the contents of pParent, which may cause pParent to
59428 ** become overfull or underfull. The next iteration of the do-loop
59429 ** will balance the parent page to correct this.
59431 ** If the parent page becomes overfull, the overflow cell or cells
59432 ** are stored in the pSpace buffer allocated immediately below.
59433 ** A subsequent iteration of the do-loop will deal with this by
59434 ** calling balance_nonroot() (balance_deeper() may be called first,
59435 ** but it doesn't deal with overflow cells - just moves them to a
59436 ** different page). Once this subsequent call to balance_nonroot()
59437 ** has completed, it is safe to release the pSpace buffer used by
59438 ** the previous call, as the overflow cell data will have been
59439 ** copied either into the body of a database page or into the new
59440 ** pSpace buffer passed to the latter call to balance_nonroot().
59442 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
59443 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
59444 if( pFree ){
59445 /* If pFree is not NULL, it points to the pSpace buffer used
59446 ** by a previous call to balance_nonroot(). Its contents are
59447 ** now stored either on real database pages or within the
59448 ** new pSpace buffer, so it may be safely freed here. */
59449 sqlite3PageFree(pFree);
59452 /* The pSpace buffer will be freed after the next call to
59453 ** balance_nonroot(), or just before this function returns, whichever
59454 ** comes first. */
59455 pFree = pSpace;
59459 pPage->nOverflow = 0;
59461 /* The next iteration of the do-loop balances the parent page. */
59462 releasePage(pPage);
59463 pCur->iPage--;
59465 }while( rc==SQLITE_OK );
59467 if( pFree ){
59468 sqlite3PageFree(pFree);
59470 return rc;
59475 ** Insert a new record into the BTree. The key is given by (pKey,nKey)
59476 ** and the data is given by (pData,nData). The cursor is used only to
59477 ** define what table the record should be inserted into. The cursor
59478 ** is left pointing at a random location.
59480 ** For an INTKEY table, only the nKey value of the key is used. pKey is
59481 ** ignored. For a ZERODATA table, the pData and nData are both ignored.
59483 ** If the seekResult parameter is non-zero, then a successful call to
59484 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
59485 ** been performed. seekResult is the search result returned (a negative
59486 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
59487 ** a positive value if pCur points at an entry that is larger than
59488 ** (pKey, nKey)).
59490 ** If the seekResult parameter is non-zero, then the caller guarantees that
59491 ** cursor pCur is pointing at the existing copy of a row that is to be
59492 ** overwritten. If the seekResult parameter is 0, then cursor pCur may
59493 ** point to any entry or to no entry at all and so this function has to seek
59494 ** the cursor before the new key can be inserted.
59496 SQLITE_PRIVATE int sqlite3BtreeInsert(
59497 BtCursor *pCur, /* Insert data into the table of this cursor */
59498 const void *pKey, i64 nKey, /* The key of the new record */
59499 const void *pData, int nData, /* The data of the new record */
59500 int nZero, /* Number of extra 0 bytes to append to data */
59501 int appendBias, /* True if this is likely an append */
59502 int seekResult /* Result of prior MovetoUnpacked() call */
59504 int rc;
59505 int loc = seekResult; /* -1: before desired location +1: after */
59506 int szNew = 0;
59507 int idx;
59508 MemPage *pPage;
59509 Btree *p = pCur->pBtree;
59510 BtShared *pBt = p->pBt;
59511 unsigned char *oldCell;
59512 unsigned char *newCell = 0;
59514 if( pCur->eState==CURSOR_FAULT ){
59515 assert( pCur->skipNext!=SQLITE_OK );
59516 return pCur->skipNext;
59519 assert( cursorHoldsMutex(pCur) );
59520 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
59521 && pBt->inTransaction==TRANS_WRITE
59522 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
59523 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
59525 /* Assert that the caller has been consistent. If this cursor was opened
59526 ** expecting an index b-tree, then the caller should be inserting blob
59527 ** keys with no associated data. If the cursor was opened expecting an
59528 ** intkey table, the caller should be inserting integer keys with a
59529 ** blob of associated data. */
59530 assert( (pKey==0)==(pCur->pKeyInfo==0) );
59532 /* Save the positions of any other cursors open on this table.
59534 ** In some cases, the call to btreeMoveto() below is a no-op. For
59535 ** example, when inserting data into a table with auto-generated integer
59536 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
59537 ** integer key to use. It then calls this function to actually insert the
59538 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
59539 ** that the cursor is already where it needs to be and returns without
59540 ** doing any work. To avoid thwarting these optimizations, it is important
59541 ** not to clear the cursor here.
59543 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
59544 if( rc ) return rc;
59546 if( pCur->pKeyInfo==0 ){
59547 /* If this is an insert into a table b-tree, invalidate any incrblob
59548 ** cursors open on the row being replaced */
59549 invalidateIncrblobCursors(p, nKey, 0);
59551 /* If the cursor is currently on the last row and we are appending a
59552 ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto()
59553 ** call */
59554 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
59555 && pCur->info.nKey==nKey-1 ){
59556 loc = -1;
59560 if( !loc ){
59561 rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
59562 if( rc ) return rc;
59564 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
59566 pPage = pCur->apPage[pCur->iPage];
59567 assert( pPage->intKey || nKey>=0 );
59568 assert( pPage->leaf || !pPage->intKey );
59570 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
59571 pCur->pgnoRoot, nKey, nData, pPage->pgno,
59572 loc==0 ? "overwrite" : "new entry"));
59573 assert( pPage->isInit );
59574 newCell = pBt->pTmpSpace;
59575 assert( newCell!=0 );
59576 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
59577 if( rc ) goto end_insert;
59578 assert( szNew==cellSizePtr(pPage, newCell) );
59579 assert( szNew <= MX_CELL_SIZE(pBt) );
59580 idx = pCur->aiIdx[pCur->iPage];
59581 if( loc==0 ){
59582 u16 szOld;
59583 assert( idx<pPage->nCell );
59584 rc = sqlite3PagerWrite(pPage->pDbPage);
59585 if( rc ){
59586 goto end_insert;
59588 oldCell = findCell(pPage, idx);
59589 if( !pPage->leaf ){
59590 memcpy(newCell, oldCell, 4);
59592 rc = clearCell(pPage, oldCell, &szOld);
59593 dropCell(pPage, idx, szOld, &rc);
59594 if( rc ) goto end_insert;
59595 }else if( loc<0 && pPage->nCell>0 ){
59596 assert( pPage->leaf );
59597 idx = ++pCur->aiIdx[pCur->iPage];
59598 }else{
59599 assert( pPage->leaf );
59601 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
59602 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
59604 /* If no error has occurred and pPage has an overflow cell, call balance()
59605 ** to redistribute the cells within the tree. Since balance() may move
59606 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
59607 ** variables.
59609 ** Previous versions of SQLite called moveToRoot() to move the cursor
59610 ** back to the root page as balance() used to invalidate the contents
59611 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
59612 ** set the cursor state to "invalid". This makes common insert operations
59613 ** slightly faster.
59615 ** There is a subtle but important optimization here too. When inserting
59616 ** multiple records into an intkey b-tree using a single cursor (as can
59617 ** happen while processing an "INSERT INTO ... SELECT" statement), it
59618 ** is advantageous to leave the cursor pointing to the last entry in
59619 ** the b-tree if possible. If the cursor is left pointing to the last
59620 ** entry in the table, and the next row inserted has an integer key
59621 ** larger than the largest existing key, it is possible to insert the
59622 ** row without seeking the cursor. This can be a big performance boost.
59624 pCur->info.nSize = 0;
59625 if( rc==SQLITE_OK && pPage->nOverflow ){
59626 pCur->curFlags &= ~(BTCF_ValidNKey);
59627 rc = balance(pCur);
59629 /* Must make sure nOverflow is reset to zero even if the balance()
59630 ** fails. Internal data structure corruption will result otherwise.
59631 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
59632 ** from trying to save the current position of the cursor. */
59633 pCur->apPage[pCur->iPage]->nOverflow = 0;
59634 pCur->eState = CURSOR_INVALID;
59636 assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
59638 end_insert:
59639 return rc;
59643 ** Delete the entry that the cursor is pointing to. The cursor
59644 ** is left pointing at an arbitrary location.
59646 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
59647 Btree *p = pCur->pBtree;
59648 BtShared *pBt = p->pBt;
59649 int rc; /* Return code */
59650 MemPage *pPage; /* Page to delete cell from */
59651 unsigned char *pCell; /* Pointer to cell to delete */
59652 int iCellIdx; /* Index of cell to delete */
59653 int iCellDepth; /* Depth of node containing pCell */
59654 u16 szCell; /* Size of the cell being deleted */
59656 assert( cursorHoldsMutex(pCur) );
59657 assert( pBt->inTransaction==TRANS_WRITE );
59658 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
59659 assert( pCur->curFlags & BTCF_WriteFlag );
59660 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
59661 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
59663 if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
59664 || NEVER(pCur->eState!=CURSOR_VALID)
59666 return SQLITE_ERROR; /* Something has gone awry. */
59669 iCellDepth = pCur->iPage;
59670 iCellIdx = pCur->aiIdx[iCellDepth];
59671 pPage = pCur->apPage[iCellDepth];
59672 pCell = findCell(pPage, iCellIdx);
59674 /* If the page containing the entry to delete is not a leaf page, move
59675 ** the cursor to the largest entry in the tree that is smaller than
59676 ** the entry being deleted. This cell will replace the cell being deleted
59677 ** from the internal node. The 'previous' entry is used for this instead
59678 ** of the 'next' entry, as the previous entry is always a part of the
59679 ** sub-tree headed by the child page of the cell being deleted. This makes
59680 ** balancing the tree following the delete operation easier. */
59681 if( !pPage->leaf ){
59682 int notUsed = 0;
59683 rc = sqlite3BtreePrevious(pCur, &notUsed);
59684 if( rc ) return rc;
59687 /* Save the positions of any other cursors open on this table before
59688 ** making any modifications. Make the page containing the entry to be
59689 ** deleted writable. Then free any overflow pages associated with the
59690 ** entry and finally remove the cell itself from within the page.
59692 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
59693 if( rc ) return rc;
59695 /* If this is a delete operation to remove a row from a table b-tree,
59696 ** invalidate any incrblob cursors open on the row being deleted. */
59697 if( pCur->pKeyInfo==0 ){
59698 invalidateIncrblobCursors(p, pCur->info.nKey, 0);
59701 rc = sqlite3PagerWrite(pPage->pDbPage);
59702 if( rc ) return rc;
59703 rc = clearCell(pPage, pCell, &szCell);
59704 dropCell(pPage, iCellIdx, szCell, &rc);
59705 if( rc ) return rc;
59707 /* If the cell deleted was not located on a leaf page, then the cursor
59708 ** is currently pointing to the largest entry in the sub-tree headed
59709 ** by the child-page of the cell that was just deleted from an internal
59710 ** node. The cell from the leaf node needs to be moved to the internal
59711 ** node to replace the deleted cell. */
59712 if( !pPage->leaf ){
59713 MemPage *pLeaf = pCur->apPage[pCur->iPage];
59714 int nCell;
59715 Pgno n = pCur->apPage[iCellDepth+1]->pgno;
59716 unsigned char *pTmp;
59718 pCell = findCell(pLeaf, pLeaf->nCell-1);
59719 nCell = cellSizePtr(pLeaf, pCell);
59720 assert( MX_CELL_SIZE(pBt) >= nCell );
59721 pTmp = pBt->pTmpSpace;
59722 assert( pTmp!=0 );
59723 rc = sqlite3PagerWrite(pLeaf->pDbPage);
59724 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
59725 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
59726 if( rc ) return rc;
59729 /* Balance the tree. If the entry deleted was located on a leaf page,
59730 ** then the cursor still points to that page. In this case the first
59731 ** call to balance() repairs the tree, and the if(...) condition is
59732 ** never true.
59734 ** Otherwise, if the entry deleted was on an internal node page, then
59735 ** pCur is pointing to the leaf page from which a cell was removed to
59736 ** replace the cell deleted from the internal node. This is slightly
59737 ** tricky as the leaf node may be underfull, and the internal node may
59738 ** be either under or overfull. In this case run the balancing algorithm
59739 ** on the leaf node first. If the balance proceeds far enough up the
59740 ** tree that we can be sure that any problem in the internal node has
59741 ** been corrected, so be it. Otherwise, after balancing the leaf node,
59742 ** walk the cursor up the tree to the internal node and balance it as
59743 ** well. */
59744 rc = balance(pCur);
59745 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
59746 while( pCur->iPage>iCellDepth ){
59747 releasePage(pCur->apPage[pCur->iPage--]);
59749 rc = balance(pCur);
59752 if( rc==SQLITE_OK ){
59753 moveToRoot(pCur);
59755 return rc;
59759 ** Create a new BTree table. Write into *piTable the page
59760 ** number for the root page of the new table.
59762 ** The type of type is determined by the flags parameter. Only the
59763 ** following values of flags are currently in use. Other values for
59764 ** flags might not work:
59766 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
59767 ** BTREE_ZERODATA Used for SQL indices
59769 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
59770 BtShared *pBt = p->pBt;
59771 MemPage *pRoot;
59772 Pgno pgnoRoot;
59773 int rc;
59774 int ptfFlags; /* Page-type flage for the root page of new table */
59776 assert( sqlite3BtreeHoldsMutex(p) );
59777 assert( pBt->inTransaction==TRANS_WRITE );
59778 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
59780 #ifdef SQLITE_OMIT_AUTOVACUUM
59781 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
59782 if( rc ){
59783 return rc;
59785 #else
59786 if( pBt->autoVacuum ){
59787 Pgno pgnoMove; /* Move a page here to make room for the root-page */
59788 MemPage *pPageMove; /* The page to move to. */
59790 /* Creating a new table may probably require moving an existing database
59791 ** to make room for the new tables root page. In case this page turns
59792 ** out to be an overflow page, delete all overflow page-map caches
59793 ** held by open cursors.
59795 invalidateAllOverflowCache(pBt);
59797 /* Read the value of meta[3] from the database to determine where the
59798 ** root page of the new table should go. meta[3] is the largest root-page
59799 ** created so far, so the new root-page is (meta[3]+1).
59801 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
59802 pgnoRoot++;
59804 /* The new root-page may not be allocated on a pointer-map page, or the
59805 ** PENDING_BYTE page.
59807 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
59808 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
59809 pgnoRoot++;
59811 assert( pgnoRoot>=3 );
59813 /* Allocate a page. The page that currently resides at pgnoRoot will
59814 ** be moved to the allocated page (unless the allocated page happens
59815 ** to reside at pgnoRoot).
59817 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
59818 if( rc!=SQLITE_OK ){
59819 return rc;
59822 if( pgnoMove!=pgnoRoot ){
59823 /* pgnoRoot is the page that will be used for the root-page of
59824 ** the new table (assuming an error did not occur). But we were
59825 ** allocated pgnoMove. If required (i.e. if it was not allocated
59826 ** by extending the file), the current page at position pgnoMove
59827 ** is already journaled.
59829 u8 eType = 0;
59830 Pgno iPtrPage = 0;
59832 /* Save the positions of any open cursors. This is required in
59833 ** case they are holding a reference to an xFetch reference
59834 ** corresponding to page pgnoRoot. */
59835 rc = saveAllCursors(pBt, 0, 0);
59836 releasePage(pPageMove);
59837 if( rc!=SQLITE_OK ){
59838 return rc;
59841 /* Move the page currently at pgnoRoot to pgnoMove. */
59842 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
59843 if( rc!=SQLITE_OK ){
59844 return rc;
59846 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
59847 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
59848 rc = SQLITE_CORRUPT_BKPT;
59850 if( rc!=SQLITE_OK ){
59851 releasePage(pRoot);
59852 return rc;
59854 assert( eType!=PTRMAP_ROOTPAGE );
59855 assert( eType!=PTRMAP_FREEPAGE );
59856 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
59857 releasePage(pRoot);
59859 /* Obtain the page at pgnoRoot */
59860 if( rc!=SQLITE_OK ){
59861 return rc;
59863 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
59864 if( rc!=SQLITE_OK ){
59865 return rc;
59867 rc = sqlite3PagerWrite(pRoot->pDbPage);
59868 if( rc!=SQLITE_OK ){
59869 releasePage(pRoot);
59870 return rc;
59872 }else{
59873 pRoot = pPageMove;
59876 /* Update the pointer-map and meta-data with the new root-page number. */
59877 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
59878 if( rc ){
59879 releasePage(pRoot);
59880 return rc;
59883 /* When the new root page was allocated, page 1 was made writable in
59884 ** order either to increase the database filesize, or to decrement the
59885 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
59887 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
59888 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
59889 if( NEVER(rc) ){
59890 releasePage(pRoot);
59891 return rc;
59894 }else{
59895 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
59896 if( rc ) return rc;
59898 #endif
59899 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
59900 if( createTabFlags & BTREE_INTKEY ){
59901 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
59902 }else{
59903 ptfFlags = PTF_ZERODATA | PTF_LEAF;
59905 zeroPage(pRoot, ptfFlags);
59906 sqlite3PagerUnref(pRoot->pDbPage);
59907 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
59908 *piTable = (int)pgnoRoot;
59909 return SQLITE_OK;
59911 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
59912 int rc;
59913 sqlite3BtreeEnter(p);
59914 rc = btreeCreateTable(p, piTable, flags);
59915 sqlite3BtreeLeave(p);
59916 return rc;
59920 ** Erase the given database page and all its children. Return
59921 ** the page to the freelist.
59923 static int clearDatabasePage(
59924 BtShared *pBt, /* The BTree that contains the table */
59925 Pgno pgno, /* Page number to clear */
59926 int freePageFlag, /* Deallocate page if true */
59927 int *pnChange /* Add number of Cells freed to this counter */
59929 MemPage *pPage;
59930 int rc;
59931 unsigned char *pCell;
59932 int i;
59933 int hdr;
59934 u16 szCell;
59936 assert( sqlite3_mutex_held(pBt->mutex) );
59937 if( pgno>btreePagecount(pBt) ){
59938 return SQLITE_CORRUPT_BKPT;
59941 rc = getAndInitPage(pBt, pgno, &pPage, 0);
59942 if( rc ) return rc;
59943 hdr = pPage->hdrOffset;
59944 for(i=0; i<pPage->nCell; i++){
59945 pCell = findCell(pPage, i);
59946 if( !pPage->leaf ){
59947 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
59948 if( rc ) goto cleardatabasepage_out;
59950 rc = clearCell(pPage, pCell, &szCell);
59951 if( rc ) goto cleardatabasepage_out;
59953 if( !pPage->leaf ){
59954 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
59955 if( rc ) goto cleardatabasepage_out;
59956 }else if( pnChange ){
59957 assert( pPage->intKey );
59958 *pnChange += pPage->nCell;
59960 if( freePageFlag ){
59961 freePage(pPage, &rc);
59962 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
59963 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
59966 cleardatabasepage_out:
59967 releasePage(pPage);
59968 return rc;
59972 ** Delete all information from a single table in the database. iTable is
59973 ** the page number of the root of the table. After this routine returns,
59974 ** the root page is empty, but still exists.
59976 ** This routine will fail with SQLITE_LOCKED if there are any open
59977 ** read cursors on the table. Open write cursors are moved to the
59978 ** root of the table.
59980 ** If pnChange is not NULL, then table iTable must be an intkey table. The
59981 ** integer value pointed to by pnChange is incremented by the number of
59982 ** entries in the table.
59984 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
59985 int rc;
59986 BtShared *pBt = p->pBt;
59987 sqlite3BtreeEnter(p);
59988 assert( p->inTrans==TRANS_WRITE );
59990 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
59992 if( SQLITE_OK==rc ){
59993 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
59994 ** is the root of a table b-tree - if it is not, the following call is
59995 ** a no-op). */
59996 invalidateIncrblobCursors(p, 0, 1);
59997 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
59999 sqlite3BtreeLeave(p);
60000 return rc;
60004 ** Delete all information from the single table that pCur is open on.
60006 ** This routine only work for pCur on an ephemeral table.
60008 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
60009 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
60013 ** Erase all information in a table and add the root of the table to
60014 ** the freelist. Except, the root of the principle table (the one on
60015 ** page 1) is never added to the freelist.
60017 ** This routine will fail with SQLITE_LOCKED if there are any open
60018 ** cursors on the table.
60020 ** If AUTOVACUUM is enabled and the page at iTable is not the last
60021 ** root page in the database file, then the last root page
60022 ** in the database file is moved into the slot formerly occupied by
60023 ** iTable and that last slot formerly occupied by the last root page
60024 ** is added to the freelist instead of iTable. In this say, all
60025 ** root pages are kept at the beginning of the database file, which
60026 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
60027 ** page number that used to be the last root page in the file before
60028 ** the move. If no page gets moved, *piMoved is set to 0.
60029 ** The last root page is recorded in meta[3] and the value of
60030 ** meta[3] is updated by this procedure.
60032 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
60033 int rc;
60034 MemPage *pPage = 0;
60035 BtShared *pBt = p->pBt;
60037 assert( sqlite3BtreeHoldsMutex(p) );
60038 assert( p->inTrans==TRANS_WRITE );
60040 /* It is illegal to drop a table if any cursors are open on the
60041 ** database. This is because in auto-vacuum mode the backend may
60042 ** need to move another root-page to fill a gap left by the deleted
60043 ** root page. If an open cursor was using this page a problem would
60044 ** occur.
60046 ** This error is caught long before control reaches this point.
60048 if( NEVER(pBt->pCursor) ){
60049 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
60050 return SQLITE_LOCKED_SHAREDCACHE;
60053 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
60054 if( rc ) return rc;
60055 rc = sqlite3BtreeClearTable(p, iTable, 0);
60056 if( rc ){
60057 releasePage(pPage);
60058 return rc;
60061 *piMoved = 0;
60063 if( iTable>1 ){
60064 #ifdef SQLITE_OMIT_AUTOVACUUM
60065 freePage(pPage, &rc);
60066 releasePage(pPage);
60067 #else
60068 if( pBt->autoVacuum ){
60069 Pgno maxRootPgno;
60070 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
60072 if( iTable==maxRootPgno ){
60073 /* If the table being dropped is the table with the largest root-page
60074 ** number in the database, put the root page on the free list.
60076 freePage(pPage, &rc);
60077 releasePage(pPage);
60078 if( rc!=SQLITE_OK ){
60079 return rc;
60081 }else{
60082 /* The table being dropped does not have the largest root-page
60083 ** number in the database. So move the page that does into the
60084 ** gap left by the deleted root-page.
60086 MemPage *pMove;
60087 releasePage(pPage);
60088 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
60089 if( rc!=SQLITE_OK ){
60090 return rc;
60092 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
60093 releasePage(pMove);
60094 if( rc!=SQLITE_OK ){
60095 return rc;
60097 pMove = 0;
60098 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
60099 freePage(pMove, &rc);
60100 releasePage(pMove);
60101 if( rc!=SQLITE_OK ){
60102 return rc;
60104 *piMoved = maxRootPgno;
60107 /* Set the new 'max-root-page' value in the database header. This
60108 ** is the old value less one, less one more if that happens to
60109 ** be a root-page number, less one again if that is the
60110 ** PENDING_BYTE_PAGE.
60112 maxRootPgno--;
60113 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
60114 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
60115 maxRootPgno--;
60117 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
60119 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
60120 }else{
60121 freePage(pPage, &rc);
60122 releasePage(pPage);
60124 #endif
60125 }else{
60126 /* If sqlite3BtreeDropTable was called on page 1.
60127 ** This really never should happen except in a corrupt
60128 ** database.
60130 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
60131 releasePage(pPage);
60133 return rc;
60135 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
60136 int rc;
60137 sqlite3BtreeEnter(p);
60138 rc = btreeDropTable(p, iTable, piMoved);
60139 sqlite3BtreeLeave(p);
60140 return rc;
60145 ** This function may only be called if the b-tree connection already
60146 ** has a read or write transaction open on the database.
60148 ** Read the meta-information out of a database file. Meta[0]
60149 ** is the number of free pages currently in the database. Meta[1]
60150 ** through meta[15] are available for use by higher layers. Meta[0]
60151 ** is read-only, the others are read/write.
60153 ** The schema layer numbers meta values differently. At the schema
60154 ** layer (and the SetCookie and ReadCookie opcodes) the number of
60155 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
60157 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
60158 BtShared *pBt = p->pBt;
60160 sqlite3BtreeEnter(p);
60161 assert( p->inTrans>TRANS_NONE );
60162 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
60163 assert( pBt->pPage1 );
60164 assert( idx>=0 && idx<=15 );
60166 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
60168 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
60169 ** database, mark the database as read-only. */
60170 #ifdef SQLITE_OMIT_AUTOVACUUM
60171 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
60172 pBt->btsFlags |= BTS_READ_ONLY;
60174 #endif
60176 sqlite3BtreeLeave(p);
60180 ** Write meta-information back into the database. Meta[0] is
60181 ** read-only and may not be written.
60183 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
60184 BtShared *pBt = p->pBt;
60185 unsigned char *pP1;
60186 int rc;
60187 assert( idx>=1 && idx<=15 );
60188 sqlite3BtreeEnter(p);
60189 assert( p->inTrans==TRANS_WRITE );
60190 assert( pBt->pPage1!=0 );
60191 pP1 = pBt->pPage1->aData;
60192 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
60193 if( rc==SQLITE_OK ){
60194 put4byte(&pP1[36 + idx*4], iMeta);
60195 #ifndef SQLITE_OMIT_AUTOVACUUM
60196 if( idx==BTREE_INCR_VACUUM ){
60197 assert( pBt->autoVacuum || iMeta==0 );
60198 assert( iMeta==0 || iMeta==1 );
60199 pBt->incrVacuum = (u8)iMeta;
60201 #endif
60203 sqlite3BtreeLeave(p);
60204 return rc;
60207 #ifndef SQLITE_OMIT_BTREECOUNT
60209 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
60210 ** number of entries in the b-tree and write the result to *pnEntry.
60212 ** SQLITE_OK is returned if the operation is successfully executed.
60213 ** Otherwise, if an error is encountered (i.e. an IO error or database
60214 ** corruption) an SQLite error code is returned.
60216 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
60217 i64 nEntry = 0; /* Value to return in *pnEntry */
60218 int rc; /* Return code */
60220 if( pCur->pgnoRoot==0 ){
60221 *pnEntry = 0;
60222 return SQLITE_OK;
60224 rc = moveToRoot(pCur);
60226 /* Unless an error occurs, the following loop runs one iteration for each
60227 ** page in the B-Tree structure (not including overflow pages).
60229 while( rc==SQLITE_OK ){
60230 int iIdx; /* Index of child node in parent */
60231 MemPage *pPage; /* Current page of the b-tree */
60233 /* If this is a leaf page or the tree is not an int-key tree, then
60234 ** this page contains countable entries. Increment the entry counter
60235 ** accordingly.
60237 pPage = pCur->apPage[pCur->iPage];
60238 if( pPage->leaf || !pPage->intKey ){
60239 nEntry += pPage->nCell;
60242 /* pPage is a leaf node. This loop navigates the cursor so that it
60243 ** points to the first interior cell that it points to the parent of
60244 ** the next page in the tree that has not yet been visited. The
60245 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
60246 ** of the page, or to the number of cells in the page if the next page
60247 ** to visit is the right-child of its parent.
60249 ** If all pages in the tree have been visited, return SQLITE_OK to the
60250 ** caller.
60252 if( pPage->leaf ){
60253 do {
60254 if( pCur->iPage==0 ){
60255 /* All pages of the b-tree have been visited. Return successfully. */
60256 *pnEntry = nEntry;
60257 return SQLITE_OK;
60259 moveToParent(pCur);
60260 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
60262 pCur->aiIdx[pCur->iPage]++;
60263 pPage = pCur->apPage[pCur->iPage];
60266 /* Descend to the child node of the cell that the cursor currently
60267 ** points at. This is the right-child if (iIdx==pPage->nCell).
60269 iIdx = pCur->aiIdx[pCur->iPage];
60270 if( iIdx==pPage->nCell ){
60271 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
60272 }else{
60273 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
60277 /* An error has occurred. Return an error code. */
60278 return rc;
60280 #endif
60283 ** Return the pager associated with a BTree. This routine is used for
60284 ** testing and debugging only.
60286 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
60287 return p->pBt->pPager;
60290 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
60292 ** Append a message to the error message string.
60294 static void checkAppendMsg(
60295 IntegrityCk *pCheck,
60296 const char *zFormat,
60299 va_list ap;
60300 char zBuf[200];
60301 if( !pCheck->mxErr ) return;
60302 pCheck->mxErr--;
60303 pCheck->nErr++;
60304 va_start(ap, zFormat);
60305 if( pCheck->errMsg.nChar ){
60306 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
60308 if( pCheck->zPfx ){
60309 sqlite3_snprintf(sizeof(zBuf), zBuf, pCheck->zPfx, pCheck->v1, pCheck->v2);
60310 sqlite3StrAccumAppendAll(&pCheck->errMsg, zBuf);
60312 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
60313 va_end(ap);
60314 if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
60315 pCheck->mallocFailed = 1;
60318 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
60320 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
60323 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
60324 ** corresponds to page iPg is already set.
60326 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
60327 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
60328 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
60332 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
60334 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
60335 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
60336 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
60341 ** Add 1 to the reference count for page iPage. If this is the second
60342 ** reference to the page, add an error message to pCheck->zErrMsg.
60343 ** Return 1 if there are 2 or more references to the page and 0 if
60344 ** if this is the first reference to the page.
60346 ** Also check that the page number is in bounds.
60348 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
60349 if( iPage==0 ) return 1;
60350 if( iPage>pCheck->nPage ){
60351 checkAppendMsg(pCheck, "invalid page number %d", iPage);
60352 return 1;
60354 if( getPageReferenced(pCheck, iPage) ){
60355 checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
60356 return 1;
60358 setPageReferenced(pCheck, iPage);
60359 return 0;
60362 #ifndef SQLITE_OMIT_AUTOVACUUM
60364 ** Check that the entry in the pointer-map for page iChild maps to
60365 ** page iParent, pointer type ptrType. If not, append an error message
60366 ** to pCheck.
60368 static void checkPtrmap(
60369 IntegrityCk *pCheck, /* Integrity check context */
60370 Pgno iChild, /* Child page number */
60371 u8 eType, /* Expected pointer map type */
60372 Pgno iParent /* Expected pointer map parent page number */
60374 int rc;
60375 u8 ePtrmapType;
60376 Pgno iPtrmapParent;
60378 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
60379 if( rc!=SQLITE_OK ){
60380 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
60381 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
60382 return;
60385 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
60386 checkAppendMsg(pCheck,
60387 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
60388 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
60391 #endif
60394 ** Check the integrity of the freelist or of an overflow page list.
60395 ** Verify that the number of pages on the list is N.
60397 static void checkList(
60398 IntegrityCk *pCheck, /* Integrity checking context */
60399 int isFreeList, /* True for a freelist. False for overflow page list */
60400 int iPage, /* Page number for first page in the list */
60401 int N /* Expected number of pages in the list */
60403 int i;
60404 int expected = N;
60405 int iFirst = iPage;
60406 while( N-- > 0 && pCheck->mxErr ){
60407 DbPage *pOvflPage;
60408 unsigned char *pOvflData;
60409 if( iPage<1 ){
60410 checkAppendMsg(pCheck,
60411 "%d of %d pages missing from overflow list starting at %d",
60412 N+1, expected, iFirst);
60413 break;
60415 if( checkRef(pCheck, iPage) ) break;
60416 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
60417 checkAppendMsg(pCheck, "failed to get page %d", iPage);
60418 break;
60420 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
60421 if( isFreeList ){
60422 int n = get4byte(&pOvflData[4]);
60423 #ifndef SQLITE_OMIT_AUTOVACUUM
60424 if( pCheck->pBt->autoVacuum ){
60425 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
60427 #endif
60428 if( n>(int)pCheck->pBt->usableSize/4-2 ){
60429 checkAppendMsg(pCheck,
60430 "freelist leaf count too big on page %d", iPage);
60431 N--;
60432 }else{
60433 for(i=0; i<n; i++){
60434 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
60435 #ifndef SQLITE_OMIT_AUTOVACUUM
60436 if( pCheck->pBt->autoVacuum ){
60437 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
60439 #endif
60440 checkRef(pCheck, iFreePage);
60442 N -= n;
60445 #ifndef SQLITE_OMIT_AUTOVACUUM
60446 else{
60447 /* If this database supports auto-vacuum and iPage is not the last
60448 ** page in this overflow list, check that the pointer-map entry for
60449 ** the following page matches iPage.
60451 if( pCheck->pBt->autoVacuum && N>0 ){
60452 i = get4byte(pOvflData);
60453 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
60456 #endif
60457 iPage = get4byte(pOvflData);
60458 sqlite3PagerUnref(pOvflPage);
60461 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
60463 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
60465 ** Do various sanity checks on a single page of a tree. Return
60466 ** the tree depth. Root pages return 0. Parents of root pages
60467 ** return 1, and so forth.
60469 ** These checks are done:
60471 ** 1. Make sure that cells and freeblocks do not overlap
60472 ** but combine to completely cover the page.
60473 ** NO 2. Make sure cell keys are in order.
60474 ** NO 3. Make sure no key is less than or equal to zLowerBound.
60475 ** NO 4. Make sure no key is greater than or equal to zUpperBound.
60476 ** 5. Check the integrity of overflow pages.
60477 ** 6. Recursively call checkTreePage on all children.
60478 ** 7. Verify that the depth of all children is the same.
60479 ** 8. Make sure this page is at least 33% full or else it is
60480 ** the root of the tree.
60482 static int checkTreePage(
60483 IntegrityCk *pCheck, /* Context for the sanity check */
60484 int iPage, /* Page number of the page to check */
60485 i64 *pnParentMinKey,
60486 i64 *pnParentMaxKey
60488 MemPage *pPage;
60489 int i, rc, depth, d2, pgno, cnt;
60490 int hdr, cellStart;
60491 int nCell;
60492 u8 *data;
60493 BtShared *pBt;
60494 int usableSize;
60495 char *hit = 0;
60496 i64 nMinKey = 0;
60497 i64 nMaxKey = 0;
60498 const char *saved_zPfx = pCheck->zPfx;
60499 int saved_v1 = pCheck->v1;
60500 int saved_v2 = pCheck->v2;
60502 /* Check that the page exists
60504 pBt = pCheck->pBt;
60505 usableSize = pBt->usableSize;
60506 if( iPage==0 ) return 0;
60507 if( checkRef(pCheck, iPage) ) return 0;
60508 pCheck->zPfx = "Page %d: ";
60509 pCheck->v1 = iPage;
60510 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
60511 checkAppendMsg(pCheck,
60512 "unable to get the page. error code=%d", rc);
60513 depth = -1;
60514 goto end_of_check;
60517 /* Clear MemPage.isInit to make sure the corruption detection code in
60518 ** btreeInitPage() is executed. */
60519 pPage->isInit = 0;
60520 if( (rc = btreeInitPage(pPage))!=0 ){
60521 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
60522 checkAppendMsg(pCheck,
60523 "btreeInitPage() returns error code %d", rc);
60524 releasePage(pPage);
60525 depth = -1;
60526 goto end_of_check;
60529 /* Check out all the cells.
60531 depth = 0;
60532 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
60533 u8 *pCell;
60534 u32 sz;
60535 CellInfo info;
60537 /* Check payload overflow pages
60539 pCheck->zPfx = "On tree page %d cell %d: ";
60540 pCheck->v1 = iPage;
60541 pCheck->v2 = i;
60542 pCell = findCell(pPage,i);
60543 btreeParseCellPtr(pPage, pCell, &info);
60544 sz = info.nPayload;
60545 /* For intKey pages, check that the keys are in order.
60547 if( pPage->intKey ){
60548 if( i==0 ){
60549 nMinKey = nMaxKey = info.nKey;
60550 }else if( info.nKey <= nMaxKey ){
60551 checkAppendMsg(pCheck,
60552 "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
60554 nMaxKey = info.nKey;
60556 if( (sz>info.nLocal)
60557 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
60559 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
60560 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
60561 #ifndef SQLITE_OMIT_AUTOVACUUM
60562 if( pBt->autoVacuum ){
60563 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
60565 #endif
60566 checkList(pCheck, 0, pgnoOvfl, nPage);
60569 /* Check sanity of left child page.
60571 if( !pPage->leaf ){
60572 pgno = get4byte(pCell);
60573 #ifndef SQLITE_OMIT_AUTOVACUUM
60574 if( pBt->autoVacuum ){
60575 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
60577 #endif
60578 d2 = checkTreePage(pCheck, pgno, &nMinKey, i==0?NULL:&nMaxKey);
60579 if( i>0 && d2!=depth ){
60580 checkAppendMsg(pCheck, "Child page depth differs");
60582 depth = d2;
60586 if( !pPage->leaf ){
60587 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
60588 pCheck->zPfx = "On page %d at right child: ";
60589 pCheck->v1 = iPage;
60590 #ifndef SQLITE_OMIT_AUTOVACUUM
60591 if( pBt->autoVacuum ){
60592 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
60594 #endif
60595 checkTreePage(pCheck, pgno, NULL, !pPage->nCell?NULL:&nMaxKey);
60598 /* For intKey leaf pages, check that the min/max keys are in order
60599 ** with any left/parent/right pages.
60601 pCheck->zPfx = "Page %d: ";
60602 pCheck->v1 = iPage;
60603 if( pPage->leaf && pPage->intKey ){
60604 /* if we are a left child page */
60605 if( pnParentMinKey ){
60606 /* if we are the left most child page */
60607 if( !pnParentMaxKey ){
60608 if( nMaxKey > *pnParentMinKey ){
60609 checkAppendMsg(pCheck,
60610 "Rowid %lld out of order (max larger than parent min of %lld)",
60611 nMaxKey, *pnParentMinKey);
60613 }else{
60614 if( nMinKey <= *pnParentMinKey ){
60615 checkAppendMsg(pCheck,
60616 "Rowid %lld out of order (min less than parent min of %lld)",
60617 nMinKey, *pnParentMinKey);
60619 if( nMaxKey > *pnParentMaxKey ){
60620 checkAppendMsg(pCheck,
60621 "Rowid %lld out of order (max larger than parent max of %lld)",
60622 nMaxKey, *pnParentMaxKey);
60624 *pnParentMinKey = nMaxKey;
60626 /* else if we're a right child page */
60627 } else if( pnParentMaxKey ){
60628 if( nMinKey <= *pnParentMaxKey ){
60629 checkAppendMsg(pCheck,
60630 "Rowid %lld out of order (min less than parent max of %lld)",
60631 nMinKey, *pnParentMaxKey);
60636 /* Check for complete coverage of the page
60638 data = pPage->aData;
60639 hdr = pPage->hdrOffset;
60640 hit = sqlite3PageMalloc( pBt->pageSize );
60641 pCheck->zPfx = 0;
60642 if( hit==0 ){
60643 pCheck->mallocFailed = 1;
60644 }else{
60645 int contentOffset = get2byteNotZero(&data[hdr+5]);
60646 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
60647 memset(hit+contentOffset, 0, usableSize-contentOffset);
60648 memset(hit, 1, contentOffset);
60649 nCell = get2byte(&data[hdr+3]);
60650 cellStart = hdr + 12 - 4*pPage->leaf;
60651 for(i=0; i<nCell; i++){
60652 int pc = get2byte(&data[cellStart+i*2]);
60653 u32 size = 65536;
60654 int j;
60655 if( pc<=usableSize-4 ){
60656 size = cellSizePtr(pPage, &data[pc]);
60658 if( (int)(pc+size-1)>=usableSize ){
60659 pCheck->zPfx = 0;
60660 checkAppendMsg(pCheck,
60661 "Corruption detected in cell %d on page %d",i,iPage);
60662 }else{
60663 for(j=pc+size-1; j>=pc; j--) hit[j]++;
60666 i = get2byte(&data[hdr+1]);
60667 while( i>0 ){
60668 int size, j;
60669 assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
60670 size = get2byte(&data[i+2]);
60671 assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
60672 for(j=i+size-1; j>=i; j--) hit[j]++;
60673 j = get2byte(&data[i]);
60674 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
60675 assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
60676 i = j;
60678 for(i=cnt=0; i<usableSize; i++){
60679 if( hit[i]==0 ){
60680 cnt++;
60681 }else if( hit[i]>1 ){
60682 checkAppendMsg(pCheck,
60683 "Multiple uses for byte %d of page %d", i, iPage);
60684 break;
60687 if( cnt!=data[hdr+7] ){
60688 checkAppendMsg(pCheck,
60689 "Fragmentation of %d bytes reported as %d on page %d",
60690 cnt, data[hdr+7], iPage);
60693 sqlite3PageFree(hit);
60694 releasePage(pPage);
60696 end_of_check:
60697 pCheck->zPfx = saved_zPfx;
60698 pCheck->v1 = saved_v1;
60699 pCheck->v2 = saved_v2;
60700 return depth+1;
60702 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
60704 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
60706 ** This routine does a complete check of the given BTree file. aRoot[] is
60707 ** an array of pages numbers were each page number is the root page of
60708 ** a table. nRoot is the number of entries in aRoot.
60710 ** A read-only or read-write transaction must be opened before calling
60711 ** this function.
60713 ** Write the number of error seen in *pnErr. Except for some memory
60714 ** allocation errors, an error message held in memory obtained from
60715 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
60716 ** returned. If a memory allocation error occurs, NULL is returned.
60718 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
60719 Btree *p, /* The btree to be checked */
60720 int *aRoot, /* An array of root pages numbers for individual trees */
60721 int nRoot, /* Number of entries in aRoot[] */
60722 int mxErr, /* Stop reporting errors after this many */
60723 int *pnErr /* Write number of errors seen to this variable */
60725 Pgno i;
60726 int nRef;
60727 IntegrityCk sCheck;
60728 BtShared *pBt = p->pBt;
60729 char zErr[100];
60731 sqlite3BtreeEnter(p);
60732 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
60733 nRef = sqlite3PagerRefcount(pBt->pPager);
60734 sCheck.pBt = pBt;
60735 sCheck.pPager = pBt->pPager;
60736 sCheck.nPage = btreePagecount(sCheck.pBt);
60737 sCheck.mxErr = mxErr;
60738 sCheck.nErr = 0;
60739 sCheck.mallocFailed = 0;
60740 sCheck.zPfx = 0;
60741 sCheck.v1 = 0;
60742 sCheck.v2 = 0;
60743 *pnErr = 0;
60744 if( sCheck.nPage==0 ){
60745 sqlite3BtreeLeave(p);
60746 return 0;
60749 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
60750 if( !sCheck.aPgRef ){
60751 *pnErr = 1;
60752 sqlite3BtreeLeave(p);
60753 return 0;
60755 i = PENDING_BYTE_PAGE(pBt);
60756 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
60757 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
60758 sCheck.errMsg.useMalloc = 2;
60760 /* Check the integrity of the freelist
60762 sCheck.zPfx = "Main freelist: ";
60763 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
60764 get4byte(&pBt->pPage1->aData[36]));
60765 sCheck.zPfx = 0;
60767 /* Check all the tables.
60769 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
60770 if( aRoot[i]==0 ) continue;
60771 #ifndef SQLITE_OMIT_AUTOVACUUM
60772 if( pBt->autoVacuum && aRoot[i]>1 ){
60773 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
60775 #endif
60776 sCheck.zPfx = "List of tree roots: ";
60777 checkTreePage(&sCheck, aRoot[i], NULL, NULL);
60778 sCheck.zPfx = 0;
60781 /* Make sure every page in the file is referenced
60783 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
60784 #ifdef SQLITE_OMIT_AUTOVACUUM
60785 if( getPageReferenced(&sCheck, i)==0 ){
60786 checkAppendMsg(&sCheck, "Page %d is never used", i);
60788 #else
60789 /* If the database supports auto-vacuum, make sure no tables contain
60790 ** references to pointer-map pages.
60792 if( getPageReferenced(&sCheck, i)==0 &&
60793 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
60794 checkAppendMsg(&sCheck, "Page %d is never used", i);
60796 if( getPageReferenced(&sCheck, i)!=0 &&
60797 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
60798 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
60800 #endif
60803 /* Make sure this analysis did not leave any unref() pages.
60804 ** This is an internal consistency check; an integrity check
60805 ** of the integrity check.
60807 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
60808 checkAppendMsg(&sCheck,
60809 "Outstanding page count goes from %d to %d during this analysis",
60810 nRef, sqlite3PagerRefcount(pBt->pPager)
60814 /* Clean up and report errors.
60816 sqlite3BtreeLeave(p);
60817 sqlite3_free(sCheck.aPgRef);
60818 if( sCheck.mallocFailed ){
60819 sqlite3StrAccumReset(&sCheck.errMsg);
60820 *pnErr = sCheck.nErr+1;
60821 return 0;
60823 *pnErr = sCheck.nErr;
60824 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
60825 return sqlite3StrAccumFinish(&sCheck.errMsg);
60827 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
60830 ** Return the full pathname of the underlying database file. Return
60831 ** an empty string if the database is in-memory or a TEMP database.
60833 ** The pager filename is invariant as long as the pager is
60834 ** open so it is safe to access without the BtShared mutex.
60836 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
60837 assert( p->pBt->pPager!=0 );
60838 return sqlite3PagerFilename(p->pBt->pPager, 1);
60842 ** Return the pathname of the journal file for this database. The return
60843 ** value of this routine is the same regardless of whether the journal file
60844 ** has been created or not.
60846 ** The pager journal filename is invariant as long as the pager is
60847 ** open so it is safe to access without the BtShared mutex.
60849 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
60850 assert( p->pBt->pPager!=0 );
60851 return sqlite3PagerJournalname(p->pBt->pPager);
60855 ** Return non-zero if a transaction is active.
60857 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
60858 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
60859 return (p && (p->inTrans==TRANS_WRITE));
60862 #ifndef SQLITE_OMIT_WAL
60864 ** Run a checkpoint on the Btree passed as the first argument.
60866 ** Return SQLITE_LOCKED if this or any other connection has an open
60867 ** transaction on the shared-cache the argument Btree is connected to.
60869 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
60871 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
60872 int rc = SQLITE_OK;
60873 if( p ){
60874 BtShared *pBt = p->pBt;
60875 sqlite3BtreeEnter(p);
60876 if( pBt->inTransaction!=TRANS_NONE ){
60877 rc = SQLITE_LOCKED;
60878 }else{
60879 rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
60881 sqlite3BtreeLeave(p);
60883 return rc;
60885 #endif
60888 ** Return non-zero if a read (or write) transaction is active.
60890 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
60891 assert( p );
60892 assert( sqlite3_mutex_held(p->db->mutex) );
60893 return p->inTrans!=TRANS_NONE;
60896 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
60897 assert( p );
60898 assert( sqlite3_mutex_held(p->db->mutex) );
60899 return p->nBackup!=0;
60903 ** This function returns a pointer to a blob of memory associated with
60904 ** a single shared-btree. The memory is used by client code for its own
60905 ** purposes (for example, to store a high-level schema associated with
60906 ** the shared-btree). The btree layer manages reference counting issues.
60908 ** The first time this is called on a shared-btree, nBytes bytes of memory
60909 ** are allocated, zeroed, and returned to the caller. For each subsequent
60910 ** call the nBytes parameter is ignored and a pointer to the same blob
60911 ** of memory returned.
60913 ** If the nBytes parameter is 0 and the blob of memory has not yet been
60914 ** allocated, a null pointer is returned. If the blob has already been
60915 ** allocated, it is returned as normal.
60917 ** Just before the shared-btree is closed, the function passed as the
60918 ** xFree argument when the memory allocation was made is invoked on the
60919 ** blob of allocated memory. The xFree function should not call sqlite3_free()
60920 ** on the memory, the btree layer does that.
60922 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
60923 BtShared *pBt = p->pBt;
60924 sqlite3BtreeEnter(p);
60925 if( !pBt->pSchema && nBytes ){
60926 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
60927 pBt->xFreeSchema = xFree;
60929 sqlite3BtreeLeave(p);
60930 return pBt->pSchema;
60934 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
60935 ** btree as the argument handle holds an exclusive lock on the
60936 ** sqlite_master table. Otherwise SQLITE_OK.
60938 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
60939 int rc;
60940 assert( sqlite3_mutex_held(p->db->mutex) );
60941 sqlite3BtreeEnter(p);
60942 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
60943 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
60944 sqlite3BtreeLeave(p);
60945 return rc;
60949 #ifndef SQLITE_OMIT_SHARED_CACHE
60951 ** Obtain a lock on the table whose root page is iTab. The
60952 ** lock is a write lock if isWritelock is true or a read lock
60953 ** if it is false.
60955 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
60956 int rc = SQLITE_OK;
60957 assert( p->inTrans!=TRANS_NONE );
60958 if( p->sharable ){
60959 u8 lockType = READ_LOCK + isWriteLock;
60960 assert( READ_LOCK+1==WRITE_LOCK );
60961 assert( isWriteLock==0 || isWriteLock==1 );
60963 sqlite3BtreeEnter(p);
60964 rc = querySharedCacheTableLock(p, iTab, lockType);
60965 if( rc==SQLITE_OK ){
60966 rc = setSharedCacheTableLock(p, iTab, lockType);
60968 sqlite3BtreeLeave(p);
60970 return rc;
60972 #endif
60974 #ifndef SQLITE_OMIT_INCRBLOB
60976 ** Argument pCsr must be a cursor opened for writing on an
60977 ** INTKEY table currently pointing at a valid table entry.
60978 ** This function modifies the data stored as part of that entry.
60980 ** Only the data content may only be modified, it is not possible to
60981 ** change the length of the data stored. If this function is called with
60982 ** parameters that attempt to write past the end of the existing data,
60983 ** no modifications are made and SQLITE_CORRUPT is returned.
60985 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
60986 int rc;
60987 assert( cursorHoldsMutex(pCsr) );
60988 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
60989 assert( pCsr->curFlags & BTCF_Incrblob );
60991 rc = restoreCursorPosition(pCsr);
60992 if( rc!=SQLITE_OK ){
60993 return rc;
60995 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
60996 if( pCsr->eState!=CURSOR_VALID ){
60997 return SQLITE_ABORT;
61000 /* Save the positions of all other cursors open on this table. This is
61001 ** required in case any of them are holding references to an xFetch
61002 ** version of the b-tree page modified by the accessPayload call below.
61004 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
61005 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
61006 ** saveAllCursors can only return SQLITE_OK.
61008 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
61009 assert( rc==SQLITE_OK );
61011 /* Check some assumptions:
61012 ** (a) the cursor is open for writing,
61013 ** (b) there is a read/write transaction open,
61014 ** (c) the connection holds a write-lock on the table (if required),
61015 ** (d) there are no conflicting read-locks, and
61016 ** (e) the cursor points at a valid row of an intKey table.
61018 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
61019 return SQLITE_READONLY;
61021 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
61022 && pCsr->pBt->inTransaction==TRANS_WRITE );
61023 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
61024 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
61025 assert( pCsr->apPage[pCsr->iPage]->intKey );
61027 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
61031 ** Mark this cursor as an incremental blob cursor.
61033 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
61034 pCur->curFlags |= BTCF_Incrblob;
61036 #endif
61039 ** Set both the "read version" (single byte at byte offset 18) and
61040 ** "write version" (single byte at byte offset 19) fields in the database
61041 ** header to iVersion.
61043 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
61044 BtShared *pBt = pBtree->pBt;
61045 int rc; /* Return code */
61047 assert( iVersion==1 || iVersion==2 );
61049 /* If setting the version fields to 1, do not automatically open the
61050 ** WAL connection, even if the version fields are currently set to 2.
61052 pBt->btsFlags &= ~BTS_NO_WAL;
61053 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
61055 rc = sqlite3BtreeBeginTrans(pBtree, 0);
61056 if( rc==SQLITE_OK ){
61057 u8 *aData = pBt->pPage1->aData;
61058 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
61059 rc = sqlite3BtreeBeginTrans(pBtree, 2);
61060 if( rc==SQLITE_OK ){
61061 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
61062 if( rc==SQLITE_OK ){
61063 aData[18] = (u8)iVersion;
61064 aData[19] = (u8)iVersion;
61070 pBt->btsFlags &= ~BTS_NO_WAL;
61071 return rc;
61075 ** set the mask of hint flags for cursor pCsr. Currently the only valid
61076 ** values are 0 and BTREE_BULKLOAD.
61078 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
61079 assert( mask==BTREE_BULKLOAD || mask==0 );
61080 pCsr->hints = mask;
61084 ** Return true if the given Btree is read-only.
61086 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
61087 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
61090 /************** End of btree.c ***********************************************/
61091 /************** Begin file backup.c ******************************************/
61093 ** 2009 January 28
61095 ** The author disclaims copyright to this source code. In place of
61096 ** a legal notice, here is a blessing:
61098 ** May you do good and not evil.
61099 ** May you find forgiveness for yourself and forgive others.
61100 ** May you share freely, never taking more than you give.
61102 *************************************************************************
61103 ** This file contains the implementation of the sqlite3_backup_XXX()
61104 ** API functions and the related features.
61108 ** Structure allocated for each backup operation.
61110 struct sqlite3_backup {
61111 sqlite3* pDestDb; /* Destination database handle */
61112 Btree *pDest; /* Destination b-tree file */
61113 u32 iDestSchema; /* Original schema cookie in destination */
61114 int bDestLocked; /* True once a write-transaction is open on pDest */
61116 Pgno iNext; /* Page number of the next source page to copy */
61117 sqlite3* pSrcDb; /* Source database handle */
61118 Btree *pSrc; /* Source b-tree file */
61120 int rc; /* Backup process error code */
61122 /* These two variables are set by every call to backup_step(). They are
61123 ** read by calls to backup_remaining() and backup_pagecount().
61125 Pgno nRemaining; /* Number of pages left to copy */
61126 Pgno nPagecount; /* Total number of pages to copy */
61128 int isAttached; /* True once backup has been registered with pager */
61129 sqlite3_backup *pNext; /* Next backup associated with source pager */
61133 ** THREAD SAFETY NOTES:
61135 ** Once it has been created using backup_init(), a single sqlite3_backup
61136 ** structure may be accessed via two groups of thread-safe entry points:
61138 ** * Via the sqlite3_backup_XXX() API function backup_step() and
61139 ** backup_finish(). Both these functions obtain the source database
61140 ** handle mutex and the mutex associated with the source BtShared
61141 ** structure, in that order.
61143 ** * Via the BackupUpdate() and BackupRestart() functions, which are
61144 ** invoked by the pager layer to report various state changes in
61145 ** the page cache associated with the source database. The mutex
61146 ** associated with the source database BtShared structure will always
61147 ** be held when either of these functions are invoked.
61149 ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
61150 ** backup_pagecount() are not thread-safe functions. If they are called
61151 ** while some other thread is calling backup_step() or backup_finish(),
61152 ** the values returned may be invalid. There is no way for a call to
61153 ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
61154 ** or backup_pagecount().
61156 ** Depending on the SQLite configuration, the database handles and/or
61157 ** the Btree objects may have their own mutexes that require locking.
61158 ** Non-sharable Btrees (in-memory databases for example), do not have
61159 ** associated mutexes.
61163 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
61164 ** in connection handle pDb. If such a database cannot be found, return
61165 ** a NULL pointer and write an error message to pErrorDb.
61167 ** If the "temp" database is requested, it may need to be opened by this
61168 ** function. If an error occurs while doing so, return 0 and write an
61169 ** error message to pErrorDb.
61171 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
61172 int i = sqlite3FindDbName(pDb, zDb);
61174 if( i==1 ){
61175 Parse *pParse;
61176 int rc = 0;
61177 pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
61178 if( pParse==0 ){
61179 sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
61180 rc = SQLITE_NOMEM;
61181 }else{
61182 pParse->db = pDb;
61183 if( sqlite3OpenTempDatabase(pParse) ){
61184 sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
61185 rc = SQLITE_ERROR;
61187 sqlite3DbFree(pErrorDb, pParse->zErrMsg);
61188 sqlite3ParserReset(pParse);
61189 sqlite3StackFree(pErrorDb, pParse);
61191 if( rc ){
61192 return 0;
61196 if( i<0 ){
61197 sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
61198 return 0;
61201 return pDb->aDb[i].pBt;
61205 ** Attempt to set the page size of the destination to match the page size
61206 ** of the source.
61208 static int setDestPgsz(sqlite3_backup *p){
61209 int rc;
61210 rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
61211 return rc;
61215 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
61216 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
61217 ** a pointer to the new sqlite3_backup object.
61219 ** If an error occurs, NULL is returned and an error code and error message
61220 ** stored in database handle pDestDb.
61222 SQLITE_API sqlite3_backup *sqlite3_backup_init(
61223 sqlite3* pDestDb, /* Database to write to */
61224 const char *zDestDb, /* Name of database within pDestDb */
61225 sqlite3* pSrcDb, /* Database connection to read from */
61226 const char *zSrcDb /* Name of database within pSrcDb */
61228 sqlite3_backup *p; /* Value to return */
61230 /* Lock the source database handle. The destination database
61231 ** handle is not locked in this routine, but it is locked in
61232 ** sqlite3_backup_step(). The user is required to ensure that no
61233 ** other thread accesses the destination handle for the duration
61234 ** of the backup operation. Any attempt to use the destination
61235 ** database connection while a backup is in progress may cause
61236 ** a malfunction or a deadlock.
61238 sqlite3_mutex_enter(pSrcDb->mutex);
61239 sqlite3_mutex_enter(pDestDb->mutex);
61241 if( pSrcDb==pDestDb ){
61242 sqlite3ErrorWithMsg(
61243 pDestDb, SQLITE_ERROR, "source and destination must be distinct"
61245 p = 0;
61246 }else {
61247 /* Allocate space for a new sqlite3_backup object...
61248 ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
61249 ** call to sqlite3_backup_init() and is destroyed by a call to
61250 ** sqlite3_backup_finish(). */
61251 p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
61252 if( !p ){
61253 sqlite3Error(pDestDb, SQLITE_NOMEM);
61257 /* If the allocation succeeded, populate the new object. */
61258 if( p ){
61259 p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
61260 p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
61261 p->pDestDb = pDestDb;
61262 p->pSrcDb = pSrcDb;
61263 p->iNext = 1;
61264 p->isAttached = 0;
61266 if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
61267 /* One (or both) of the named databases did not exist or an OOM
61268 ** error was hit. The error has already been written into the
61269 ** pDestDb handle. All that is left to do here is free the
61270 ** sqlite3_backup structure.
61272 sqlite3_free(p);
61273 p = 0;
61276 if( p ){
61277 p->pSrc->nBackup++;
61280 sqlite3_mutex_leave(pDestDb->mutex);
61281 sqlite3_mutex_leave(pSrcDb->mutex);
61282 return p;
61286 ** Argument rc is an SQLite error code. Return true if this error is
61287 ** considered fatal if encountered during a backup operation. All errors
61288 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
61290 static int isFatalError(int rc){
61291 return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
61295 ** Parameter zSrcData points to a buffer containing the data for
61296 ** page iSrcPg from the source database. Copy this data into the
61297 ** destination database.
61299 static int backupOnePage(
61300 sqlite3_backup *p, /* Backup handle */
61301 Pgno iSrcPg, /* Source database page to backup */
61302 const u8 *zSrcData, /* Source database page data */
61303 int bUpdate /* True for an update, false otherwise */
61305 Pager * const pDestPager = sqlite3BtreePager(p->pDest);
61306 const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
61307 int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
61308 const int nCopy = MIN(nSrcPgsz, nDestPgsz);
61309 const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
61310 #ifdef SQLITE_HAS_CODEC
61311 /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
61312 ** guaranteed that the shared-mutex is held by this thread, handle
61313 ** p->pSrc may not actually be the owner. */
61314 int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
61315 int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
61316 #endif
61317 int rc = SQLITE_OK;
61318 i64 iOff;
61320 assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
61321 assert( p->bDestLocked );
61322 assert( !isFatalError(p->rc) );
61323 assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
61324 assert( zSrcData );
61326 /* Catch the case where the destination is an in-memory database and the
61327 ** page sizes of the source and destination differ.
61329 if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
61330 rc = SQLITE_READONLY;
61333 #ifdef SQLITE_HAS_CODEC
61334 /* Backup is not possible if the page size of the destination is changing
61335 ** and a codec is in use.
61337 if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
61338 rc = SQLITE_READONLY;
61341 /* Backup is not possible if the number of bytes of reserve space differ
61342 ** between source and destination. If there is a difference, try to
61343 ** fix the destination to agree with the source. If that is not possible,
61344 ** then the backup cannot proceed.
61346 if( nSrcReserve!=nDestReserve ){
61347 u32 newPgsz = nSrcPgsz;
61348 rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
61349 if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
61351 #endif
61353 /* This loop runs once for each destination page spanned by the source
61354 ** page. For each iteration, variable iOff is set to the byte offset
61355 ** of the destination page.
61357 for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
61358 DbPage *pDestPg = 0;
61359 Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
61360 if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
61361 if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
61362 && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
61364 const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
61365 u8 *zDestData = sqlite3PagerGetData(pDestPg);
61366 u8 *zOut = &zDestData[iOff%nDestPgsz];
61368 /* Copy the data from the source page into the destination page.
61369 ** Then clear the Btree layer MemPage.isInit flag. Both this module
61370 ** and the pager code use this trick (clearing the first byte
61371 ** of the page 'extra' space to invalidate the Btree layers
61372 ** cached parse of the page). MemPage.isInit is marked
61373 ** "MUST BE FIRST" for this purpose.
61375 memcpy(zOut, zIn, nCopy);
61376 ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
61377 if( iOff==0 && bUpdate==0 ){
61378 sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
61381 sqlite3PagerUnref(pDestPg);
61384 return rc;
61388 ** If pFile is currently larger than iSize bytes, then truncate it to
61389 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
61390 ** this function is a no-op.
61392 ** Return SQLITE_OK if everything is successful, or an SQLite error
61393 ** code if an error occurs.
61395 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
61396 i64 iCurrent;
61397 int rc = sqlite3OsFileSize(pFile, &iCurrent);
61398 if( rc==SQLITE_OK && iCurrent>iSize ){
61399 rc = sqlite3OsTruncate(pFile, iSize);
61401 return rc;
61405 ** Register this backup object with the associated source pager for
61406 ** callbacks when pages are changed or the cache invalidated.
61408 static void attachBackupObject(sqlite3_backup *p){
61409 sqlite3_backup **pp;
61410 assert( sqlite3BtreeHoldsMutex(p->pSrc) );
61411 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
61412 p->pNext = *pp;
61413 *pp = p;
61414 p->isAttached = 1;
61418 ** Copy nPage pages from the source b-tree to the destination.
61420 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
61421 int rc;
61422 int destMode; /* Destination journal mode */
61423 int pgszSrc = 0; /* Source page size */
61424 int pgszDest = 0; /* Destination page size */
61426 sqlite3_mutex_enter(p->pSrcDb->mutex);
61427 sqlite3BtreeEnter(p->pSrc);
61428 if( p->pDestDb ){
61429 sqlite3_mutex_enter(p->pDestDb->mutex);
61432 rc = p->rc;
61433 if( !isFatalError(rc) ){
61434 Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
61435 Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
61436 int ii; /* Iterator variable */
61437 int nSrcPage = -1; /* Size of source db in pages */
61438 int bCloseTrans = 0; /* True if src db requires unlocking */
61440 /* If the source pager is currently in a write-transaction, return
61441 ** SQLITE_BUSY immediately.
61443 if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
61444 rc = SQLITE_BUSY;
61445 }else{
61446 rc = SQLITE_OK;
61449 /* Lock the destination database, if it is not locked already. */
61450 if( SQLITE_OK==rc && p->bDestLocked==0
61451 && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
61453 p->bDestLocked = 1;
61454 sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
61457 /* If there is no open read-transaction on the source database, open
61458 ** one now. If a transaction is opened here, then it will be closed
61459 ** before this function exits.
61461 if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
61462 rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
61463 bCloseTrans = 1;
61466 /* Do not allow backup if the destination database is in WAL mode
61467 ** and the page sizes are different between source and destination */
61468 pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
61469 pgszDest = sqlite3BtreeGetPageSize(p->pDest);
61470 destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
61471 if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
61472 rc = SQLITE_READONLY;
61475 /* Now that there is a read-lock on the source database, query the
61476 ** source pager for the number of pages in the database.
61478 nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
61479 assert( nSrcPage>=0 );
61480 for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
61481 const Pgno iSrcPg = p->iNext; /* Source page number */
61482 if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
61483 DbPage *pSrcPg; /* Source page object */
61484 rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
61485 PAGER_GET_READONLY);
61486 if( rc==SQLITE_OK ){
61487 rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
61488 sqlite3PagerUnref(pSrcPg);
61491 p->iNext++;
61493 if( rc==SQLITE_OK ){
61494 p->nPagecount = nSrcPage;
61495 p->nRemaining = nSrcPage+1-p->iNext;
61496 if( p->iNext>(Pgno)nSrcPage ){
61497 rc = SQLITE_DONE;
61498 }else if( !p->isAttached ){
61499 attachBackupObject(p);
61503 /* Update the schema version field in the destination database. This
61504 ** is to make sure that the schema-version really does change in
61505 ** the case where the source and destination databases have the
61506 ** same schema version.
61508 if( rc==SQLITE_DONE ){
61509 if( nSrcPage==0 ){
61510 rc = sqlite3BtreeNewDb(p->pDest);
61511 nSrcPage = 1;
61513 if( rc==SQLITE_OK || rc==SQLITE_DONE ){
61514 rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
61516 if( rc==SQLITE_OK ){
61517 if( p->pDestDb ){
61518 sqlite3ResetAllSchemasOfConnection(p->pDestDb);
61520 if( destMode==PAGER_JOURNALMODE_WAL ){
61521 rc = sqlite3BtreeSetVersion(p->pDest, 2);
61524 if( rc==SQLITE_OK ){
61525 int nDestTruncate;
61526 /* Set nDestTruncate to the final number of pages in the destination
61527 ** database. The complication here is that the destination page
61528 ** size may be different to the source page size.
61530 ** If the source page size is smaller than the destination page size,
61531 ** round up. In this case the call to sqlite3OsTruncate() below will
61532 ** fix the size of the file. However it is important to call
61533 ** sqlite3PagerTruncateImage() here so that any pages in the
61534 ** destination file that lie beyond the nDestTruncate page mark are
61535 ** journalled by PagerCommitPhaseOne() before they are destroyed
61536 ** by the file truncation.
61538 assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
61539 assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
61540 if( pgszSrc<pgszDest ){
61541 int ratio = pgszDest/pgszSrc;
61542 nDestTruncate = (nSrcPage+ratio-1)/ratio;
61543 if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
61544 nDestTruncate--;
61546 }else{
61547 nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
61549 assert( nDestTruncate>0 );
61551 if( pgszSrc<pgszDest ){
61552 /* If the source page-size is smaller than the destination page-size,
61553 ** two extra things may need to happen:
61555 ** * The destination may need to be truncated, and
61557 ** * Data stored on the pages immediately following the
61558 ** pending-byte page in the source database may need to be
61559 ** copied into the destination database.
61561 const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
61562 sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
61563 Pgno iPg;
61564 int nDstPage;
61565 i64 iOff;
61566 i64 iEnd;
61568 assert( pFile );
61569 assert( nDestTruncate==0
61570 || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
61571 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
61572 && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
61575 /* This block ensures that all data required to recreate the original
61576 ** database has been stored in the journal for pDestPager and the
61577 ** journal synced to disk. So at this point we may safely modify
61578 ** the database file in any way, knowing that if a power failure
61579 ** occurs, the original database will be reconstructed from the
61580 ** journal file. */
61581 sqlite3PagerPagecount(pDestPager, &nDstPage);
61582 for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
61583 if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
61584 DbPage *pPg;
61585 rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
61586 if( rc==SQLITE_OK ){
61587 rc = sqlite3PagerWrite(pPg);
61588 sqlite3PagerUnref(pPg);
61592 if( rc==SQLITE_OK ){
61593 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
61596 /* Write the extra pages and truncate the database file as required */
61597 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
61598 for(
61599 iOff=PENDING_BYTE+pgszSrc;
61600 rc==SQLITE_OK && iOff<iEnd;
61601 iOff+=pgszSrc
61603 PgHdr *pSrcPg = 0;
61604 const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
61605 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
61606 if( rc==SQLITE_OK ){
61607 u8 *zData = sqlite3PagerGetData(pSrcPg);
61608 rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
61610 sqlite3PagerUnref(pSrcPg);
61612 if( rc==SQLITE_OK ){
61613 rc = backupTruncateFile(pFile, iSize);
61616 /* Sync the database file to disk. */
61617 if( rc==SQLITE_OK ){
61618 rc = sqlite3PagerSync(pDestPager, 0);
61620 }else{
61621 sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
61622 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
61625 /* Finish committing the transaction to the destination database. */
61626 if( SQLITE_OK==rc
61627 && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
61629 rc = SQLITE_DONE;
61634 /* If bCloseTrans is true, then this function opened a read transaction
61635 ** on the source database. Close the read transaction here. There is
61636 ** no need to check the return values of the btree methods here, as
61637 ** "committing" a read-only transaction cannot fail.
61639 if( bCloseTrans ){
61640 TESTONLY( int rc2 );
61641 TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
61642 TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
61643 assert( rc2==SQLITE_OK );
61646 if( rc==SQLITE_IOERR_NOMEM ){
61647 rc = SQLITE_NOMEM;
61649 p->rc = rc;
61651 if( p->pDestDb ){
61652 sqlite3_mutex_leave(p->pDestDb->mutex);
61654 sqlite3BtreeLeave(p->pSrc);
61655 sqlite3_mutex_leave(p->pSrcDb->mutex);
61656 return rc;
61660 ** Release all resources associated with an sqlite3_backup* handle.
61662 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
61663 sqlite3_backup **pp; /* Ptr to head of pagers backup list */
61664 sqlite3 *pSrcDb; /* Source database connection */
61665 int rc; /* Value to return */
61667 /* Enter the mutexes */
61668 if( p==0 ) return SQLITE_OK;
61669 pSrcDb = p->pSrcDb;
61670 sqlite3_mutex_enter(pSrcDb->mutex);
61671 sqlite3BtreeEnter(p->pSrc);
61672 if( p->pDestDb ){
61673 sqlite3_mutex_enter(p->pDestDb->mutex);
61676 /* Detach this backup from the source pager. */
61677 if( p->pDestDb ){
61678 p->pSrc->nBackup--;
61680 if( p->isAttached ){
61681 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
61682 while( *pp!=p ){
61683 pp = &(*pp)->pNext;
61685 *pp = p->pNext;
61688 /* If a transaction is still open on the Btree, roll it back. */
61689 sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
61691 /* Set the error code of the destination database handle. */
61692 rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
61693 if( p->pDestDb ){
61694 sqlite3Error(p->pDestDb, rc);
61696 /* Exit the mutexes and free the backup context structure. */
61697 sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
61699 sqlite3BtreeLeave(p->pSrc);
61700 if( p->pDestDb ){
61701 /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
61702 ** call to sqlite3_backup_init() and is destroyed by a call to
61703 ** sqlite3_backup_finish(). */
61704 sqlite3_free(p);
61706 sqlite3LeaveMutexAndCloseZombie(pSrcDb);
61707 return rc;
61711 ** Return the number of pages still to be backed up as of the most recent
61712 ** call to sqlite3_backup_step().
61714 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
61715 return p->nRemaining;
61719 ** Return the total number of pages in the source database as of the most
61720 ** recent call to sqlite3_backup_step().
61722 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
61723 return p->nPagecount;
61727 ** This function is called after the contents of page iPage of the
61728 ** source database have been modified. If page iPage has already been
61729 ** copied into the destination database, then the data written to the
61730 ** destination is now invalidated. The destination copy of iPage needs
61731 ** to be updated with the new data before the backup operation is
61732 ** complete.
61734 ** It is assumed that the mutex associated with the BtShared object
61735 ** corresponding to the source database is held when this function is
61736 ** called.
61738 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
61739 sqlite3_backup *p; /* Iterator variable */
61740 for(p=pBackup; p; p=p->pNext){
61741 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
61742 if( !isFatalError(p->rc) && iPage<p->iNext ){
61743 /* The backup process p has already copied page iPage. But now it
61744 ** has been modified by a transaction on the source pager. Copy
61745 ** the new data into the backup.
61747 int rc;
61748 assert( p->pDestDb );
61749 sqlite3_mutex_enter(p->pDestDb->mutex);
61750 rc = backupOnePage(p, iPage, aData, 1);
61751 sqlite3_mutex_leave(p->pDestDb->mutex);
61752 assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
61753 if( rc!=SQLITE_OK ){
61754 p->rc = rc;
61761 ** Restart the backup process. This is called when the pager layer
61762 ** detects that the database has been modified by an external database
61763 ** connection. In this case there is no way of knowing which of the
61764 ** pages that have been copied into the destination database are still
61765 ** valid and which are not, so the entire process needs to be restarted.
61767 ** It is assumed that the mutex associated with the BtShared object
61768 ** corresponding to the source database is held when this function is
61769 ** called.
61771 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
61772 sqlite3_backup *p; /* Iterator variable */
61773 for(p=pBackup; p; p=p->pNext){
61774 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
61775 p->iNext = 1;
61779 #ifndef SQLITE_OMIT_VACUUM
61781 ** Copy the complete content of pBtFrom into pBtTo. A transaction
61782 ** must be active for both files.
61784 ** The size of file pTo may be reduced by this operation. If anything
61785 ** goes wrong, the transaction on pTo is rolled back. If successful, the
61786 ** transaction is committed before returning.
61788 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
61789 int rc;
61790 sqlite3_file *pFd; /* File descriptor for database pTo */
61791 sqlite3_backup b;
61792 sqlite3BtreeEnter(pTo);
61793 sqlite3BtreeEnter(pFrom);
61795 assert( sqlite3BtreeIsInTrans(pTo) );
61796 pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
61797 if( pFd->pMethods ){
61798 i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
61799 rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
61800 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
61801 if( rc ) goto copy_finished;
61804 /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
61805 ** to 0. This is used by the implementations of sqlite3_backup_step()
61806 ** and sqlite3_backup_finish() to detect that they are being called
61807 ** from this function, not directly by the user.
61809 memset(&b, 0, sizeof(b));
61810 b.pSrcDb = pFrom->db;
61811 b.pSrc = pFrom;
61812 b.pDest = pTo;
61813 b.iNext = 1;
61815 /* 0x7FFFFFFF is the hard limit for the number of pages in a database
61816 ** file. By passing this as the number of pages to copy to
61817 ** sqlite3_backup_step(), we can guarantee that the copy finishes
61818 ** within a single call (unless an error occurs). The assert() statement
61819 ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
61820 ** or an error code.
61822 sqlite3_backup_step(&b, 0x7FFFFFFF);
61823 assert( b.rc!=SQLITE_OK );
61824 rc = sqlite3_backup_finish(&b);
61825 if( rc==SQLITE_OK ){
61826 pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
61827 }else{
61828 sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
61831 assert( sqlite3BtreeIsInTrans(pTo)==0 );
61832 copy_finished:
61833 sqlite3BtreeLeave(pFrom);
61834 sqlite3BtreeLeave(pTo);
61835 return rc;
61837 #endif /* SQLITE_OMIT_VACUUM */
61839 /************** End of backup.c **********************************************/
61840 /************** Begin file vdbemem.c *****************************************/
61842 ** 2004 May 26
61844 ** The author disclaims copyright to this source code. In place of
61845 ** a legal notice, here is a blessing:
61847 ** May you do good and not evil.
61848 ** May you find forgiveness for yourself and forgive others.
61849 ** May you share freely, never taking more than you give.
61851 *************************************************************************
61853 ** This file contains code use to manipulate "Mem" structure. A "Mem"
61854 ** stores a single value in the VDBE. Mem is an opaque structure visible
61855 ** only within the VDBE. Interface routines refer to a Mem using the
61856 ** name sqlite_value
61859 #ifdef SQLITE_DEBUG
61861 ** Check invariants on a Mem object.
61863 ** This routine is intended for use inside of assert() statements, like
61864 ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
61866 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
61867 /* If MEM_Dyn is set then Mem.xDel!=0.
61868 ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
61870 assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
61872 /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
61873 ** ensure that if Mem.szMalloc>0 then it is safe to do
61874 ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
61875 ** That saves a few cycles in inner loops. */
61876 assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
61878 /* Cannot be both MEM_Int and MEM_Real at the same time */
61879 assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
61881 /* The szMalloc field holds the correct memory allocation size */
61882 assert( p->szMalloc==0
61883 || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
61885 /* If p holds a string or blob, the Mem.z must point to exactly
61886 ** one of the following:
61888 ** (1) Memory in Mem.zMalloc and managed by the Mem object
61889 ** (2) Memory to be freed using Mem.xDel
61890 ** (3) An ephemeral string or blob
61891 ** (4) A static string or blob
61893 if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
61894 assert(
61895 ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
61896 ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
61897 ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
61898 ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
61901 return 1;
61903 #endif
61907 ** If pMem is an object with a valid string representation, this routine
61908 ** ensures the internal encoding for the string representation is
61909 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
61911 ** If pMem is not a string object, or the encoding of the string
61912 ** representation is already stored using the requested encoding, then this
61913 ** routine is a no-op.
61915 ** SQLITE_OK is returned if the conversion is successful (or not required).
61916 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
61917 ** between formats.
61919 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
61920 #ifndef SQLITE_OMIT_UTF16
61921 int rc;
61922 #endif
61923 assert( (pMem->flags&MEM_RowSet)==0 );
61924 assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
61925 || desiredEnc==SQLITE_UTF16BE );
61926 if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
61927 return SQLITE_OK;
61929 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
61930 #ifdef SQLITE_OMIT_UTF16
61931 return SQLITE_ERROR;
61932 #else
61934 /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
61935 ** then the encoding of the value may not have changed.
61937 rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
61938 assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
61939 assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
61940 assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
61941 return rc;
61942 #endif
61946 ** Make sure pMem->z points to a writable allocation of at least
61947 ** min(n,32) bytes.
61949 ** If the bPreserve argument is true, then copy of the content of
61950 ** pMem->z into the new allocation. pMem must be either a string or
61951 ** blob if bPreserve is true. If bPreserve is false, any prior content
61952 ** in pMem->z is discarded.
61954 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
61955 assert( sqlite3VdbeCheckMemInvariants(pMem) );
61956 assert( (pMem->flags&MEM_RowSet)==0 );
61958 /* If the bPreserve flag is set to true, then the memory cell must already
61959 ** contain a valid string or blob value. */
61960 assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
61961 testcase( bPreserve && pMem->z==0 );
61963 assert( pMem->szMalloc==0
61964 || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
61965 if( pMem->szMalloc<n ){
61966 if( n<32 ) n = 32;
61967 if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
61968 pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
61969 bPreserve = 0;
61970 }else{
61971 if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
61972 pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
61974 if( pMem->zMalloc==0 ){
61975 sqlite3VdbeMemSetNull(pMem);
61976 pMem->z = 0;
61977 pMem->szMalloc = 0;
61978 return SQLITE_NOMEM;
61979 }else{
61980 pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
61984 if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
61985 memcpy(pMem->zMalloc, pMem->z, pMem->n);
61987 if( (pMem->flags&MEM_Dyn)!=0 ){
61988 assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
61989 pMem->xDel((void *)(pMem->z));
61992 pMem->z = pMem->zMalloc;
61993 pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
61994 return SQLITE_OK;
61998 ** Change the pMem->zMalloc allocation to be at least szNew bytes.
61999 ** If pMem->zMalloc already meets or exceeds the requested size, this
62000 ** routine is a no-op.
62002 ** Any prior string or blob content in the pMem object may be discarded.
62003 ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
62004 ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
62005 ** values are preserved.
62007 ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
62008 ** if unable to complete the resizing.
62010 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
62011 assert( szNew>0 );
62012 assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
62013 if( pMem->szMalloc<szNew ){
62014 return sqlite3VdbeMemGrow(pMem, szNew, 0);
62016 assert( (pMem->flags & MEM_Dyn)==0 );
62017 pMem->z = pMem->zMalloc;
62018 pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
62019 return SQLITE_OK;
62023 ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
62024 ** MEM.zMalloc, where it can be safely written.
62026 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
62028 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
62029 int f;
62030 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62031 assert( (pMem->flags&MEM_RowSet)==0 );
62032 ExpandBlob(pMem);
62033 f = pMem->flags;
62034 if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
62035 if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
62036 return SQLITE_NOMEM;
62038 pMem->z[pMem->n] = 0;
62039 pMem->z[pMem->n+1] = 0;
62040 pMem->flags |= MEM_Term;
62041 #ifdef SQLITE_DEBUG
62042 pMem->pScopyFrom = 0;
62043 #endif
62046 return SQLITE_OK;
62050 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
62051 ** blob stored in dynamically allocated space.
62053 #ifndef SQLITE_OMIT_INCRBLOB
62054 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
62055 if( pMem->flags & MEM_Zero ){
62056 int nByte;
62057 assert( pMem->flags&MEM_Blob );
62058 assert( (pMem->flags&MEM_RowSet)==0 );
62059 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62061 /* Set nByte to the number of bytes required to store the expanded blob. */
62062 nByte = pMem->n + pMem->u.nZero;
62063 if( nByte<=0 ){
62064 nByte = 1;
62066 if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
62067 return SQLITE_NOMEM;
62070 memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
62071 pMem->n += pMem->u.nZero;
62072 pMem->flags &= ~(MEM_Zero|MEM_Term);
62074 return SQLITE_OK;
62076 #endif
62079 ** It is already known that pMem contains an unterminated string.
62080 ** Add the zero terminator.
62082 static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
62083 if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
62084 return SQLITE_NOMEM;
62086 pMem->z[pMem->n] = 0;
62087 pMem->z[pMem->n+1] = 0;
62088 pMem->flags |= MEM_Term;
62089 return SQLITE_OK;
62093 ** Make sure the given Mem is \u0000 terminated.
62095 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
62096 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62097 testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
62098 testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
62099 if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
62100 return SQLITE_OK; /* Nothing to do */
62101 }else{
62102 return vdbeMemAddTerminator(pMem);
62107 ** Add MEM_Str to the set of representations for the given Mem. Numbers
62108 ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
62109 ** is a no-op.
62111 ** Existing representations MEM_Int and MEM_Real are invalidated if
62112 ** bForce is true but are retained if bForce is false.
62114 ** A MEM_Null value will never be passed to this function. This function is
62115 ** used for converting values to text for returning to the user (i.e. via
62116 ** sqlite3_value_text()), or for ensuring that values to be used as btree
62117 ** keys are strings. In the former case a NULL pointer is returned the
62118 ** user and the latter is an internal programming error.
62120 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
62121 int fg = pMem->flags;
62122 const int nByte = 32;
62124 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62125 assert( !(fg&MEM_Zero) );
62126 assert( !(fg&(MEM_Str|MEM_Blob)) );
62127 assert( fg&(MEM_Int|MEM_Real) );
62128 assert( (pMem->flags&MEM_RowSet)==0 );
62129 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62132 if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
62133 return SQLITE_NOMEM;
62136 /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
62137 ** string representation of the value. Then, if the required encoding
62138 ** is UTF-16le or UTF-16be do a translation.
62140 ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
62142 if( fg & MEM_Int ){
62143 sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
62144 }else{
62145 assert( fg & MEM_Real );
62146 sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
62148 pMem->n = sqlite3Strlen30(pMem->z);
62149 pMem->enc = SQLITE_UTF8;
62150 pMem->flags |= MEM_Str|MEM_Term;
62151 if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
62152 sqlite3VdbeChangeEncoding(pMem, enc);
62153 return SQLITE_OK;
62157 ** Memory cell pMem contains the context of an aggregate function.
62158 ** This routine calls the finalize method for that function. The
62159 ** result of the aggregate is stored back into pMem.
62161 ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
62162 ** otherwise.
62164 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
62165 int rc = SQLITE_OK;
62166 if( ALWAYS(pFunc && pFunc->xFinalize) ){
62167 sqlite3_context ctx;
62168 Mem t;
62169 assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
62170 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62171 memset(&ctx, 0, sizeof(ctx));
62172 memset(&t, 0, sizeof(t));
62173 t.flags = MEM_Null;
62174 t.db = pMem->db;
62175 ctx.pOut = &t;
62176 ctx.pMem = pMem;
62177 ctx.pFunc = pFunc;
62178 pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
62179 assert( (pMem->flags & MEM_Dyn)==0 );
62180 if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
62181 memcpy(pMem, &t, sizeof(t));
62182 rc = ctx.isError;
62184 return rc;
62188 ** If the memory cell contains a value that must be freed by
62189 ** invoking the external callback in Mem.xDel, then this routine
62190 ** will free that value. It also sets Mem.flags to MEM_Null.
62192 ** This is a helper routine for sqlite3VdbeMemSetNull() and
62193 ** for sqlite3VdbeMemRelease(). Use those other routines as the
62194 ** entry point for releasing Mem resources.
62196 static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
62197 assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
62198 assert( VdbeMemDynamic(p) );
62199 if( p->flags&MEM_Agg ){
62200 sqlite3VdbeMemFinalize(p, p->u.pDef);
62201 assert( (p->flags & MEM_Agg)==0 );
62202 testcase( p->flags & MEM_Dyn );
62204 if( p->flags&MEM_Dyn ){
62205 assert( (p->flags&MEM_RowSet)==0 );
62206 assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
62207 p->xDel((void *)p->z);
62208 }else if( p->flags&MEM_RowSet ){
62209 sqlite3RowSetClear(p->u.pRowSet);
62210 }else if( p->flags&MEM_Frame ){
62211 VdbeFrame *pFrame = p->u.pFrame;
62212 pFrame->pParent = pFrame->v->pDelFrame;
62213 pFrame->v->pDelFrame = pFrame;
62215 p->flags = MEM_Null;
62219 ** Release memory held by the Mem p, both external memory cleared
62220 ** by p->xDel and memory in p->zMalloc.
62222 ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
62223 ** the unusual case where there really is memory in p that needs
62224 ** to be freed.
62226 static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
62227 if( VdbeMemDynamic(p) ){
62228 vdbeMemClearExternAndSetNull(p);
62230 if( p->szMalloc ){
62231 sqlite3DbFree(p->db, p->zMalloc);
62232 p->szMalloc = 0;
62234 p->z = 0;
62238 ** Release any memory resources held by the Mem. Both the memory that is
62239 ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
62241 ** Use this routine prior to clean up prior to abandoning a Mem, or to
62242 ** reset a Mem back to its minimum memory utilization.
62244 ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
62245 ** prior to inserting new content into the Mem.
62247 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
62248 assert( sqlite3VdbeCheckMemInvariants(p) );
62249 if( VdbeMemDynamic(p) || p->szMalloc ){
62250 vdbeMemClear(p);
62255 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
62256 ** If the double is out of range of a 64-bit signed integer then
62257 ** return the closest available 64-bit signed integer.
62259 static i64 doubleToInt64(double r){
62260 #ifdef SQLITE_OMIT_FLOATING_POINT
62261 /* When floating-point is omitted, double and int64 are the same thing */
62262 return r;
62263 #else
62265 ** Many compilers we encounter do not define constants for the
62266 ** minimum and maximum 64-bit integers, or they define them
62267 ** inconsistently. And many do not understand the "LL" notation.
62268 ** So we define our own static constants here using nothing
62269 ** larger than a 32-bit integer constant.
62271 static const i64 maxInt = LARGEST_INT64;
62272 static const i64 minInt = SMALLEST_INT64;
62274 if( r<=(double)minInt ){
62275 return minInt;
62276 }else if( r>=(double)maxInt ){
62277 return maxInt;
62278 }else{
62279 return (i64)r;
62281 #endif
62285 ** Return some kind of integer value which is the best we can do
62286 ** at representing the value that *pMem describes as an integer.
62287 ** If pMem is an integer, then the value is exact. If pMem is
62288 ** a floating-point then the value returned is the integer part.
62289 ** If pMem is a string or blob, then we make an attempt to convert
62290 ** it into an integer and return that. If pMem represents an
62291 ** an SQL-NULL value, return 0.
62293 ** If pMem represents a string value, its encoding might be changed.
62295 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
62296 int flags;
62297 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62298 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62299 flags = pMem->flags;
62300 if( flags & MEM_Int ){
62301 return pMem->u.i;
62302 }else if( flags & MEM_Real ){
62303 return doubleToInt64(pMem->u.r);
62304 }else if( flags & (MEM_Str|MEM_Blob) ){
62305 i64 value = 0;
62306 assert( pMem->z || pMem->n==0 );
62307 sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
62308 return value;
62309 }else{
62310 return 0;
62315 ** Return the best representation of pMem that we can get into a
62316 ** double. If pMem is already a double or an integer, return its
62317 ** value. If it is a string or blob, try to convert it to a double.
62318 ** If it is a NULL, return 0.0.
62320 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
62321 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62322 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62323 if( pMem->flags & MEM_Real ){
62324 return pMem->u.r;
62325 }else if( pMem->flags & MEM_Int ){
62326 return (double)pMem->u.i;
62327 }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
62328 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
62329 double val = (double)0;
62330 sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
62331 return val;
62332 }else{
62333 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
62334 return (double)0;
62339 ** The MEM structure is already a MEM_Real. Try to also make it a
62340 ** MEM_Int if we can.
62342 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
62343 i64 ix;
62344 assert( pMem->flags & MEM_Real );
62345 assert( (pMem->flags & MEM_RowSet)==0 );
62346 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62347 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62349 ix = doubleToInt64(pMem->u.r);
62351 /* Only mark the value as an integer if
62353 ** (1) the round-trip conversion real->int->real is a no-op, and
62354 ** (2) The integer is neither the largest nor the smallest
62355 ** possible integer (ticket #3922)
62357 ** The second and third terms in the following conditional enforces
62358 ** the second condition under the assumption that addition overflow causes
62359 ** values to wrap around.
62361 if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
62362 pMem->u.i = ix;
62363 MemSetTypeFlag(pMem, MEM_Int);
62368 ** Convert pMem to type integer. Invalidate any prior representations.
62370 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
62371 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62372 assert( (pMem->flags & MEM_RowSet)==0 );
62373 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62375 pMem->u.i = sqlite3VdbeIntValue(pMem);
62376 MemSetTypeFlag(pMem, MEM_Int);
62377 return SQLITE_OK;
62381 ** Convert pMem so that it is of type MEM_Real.
62382 ** Invalidate any prior representations.
62384 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
62385 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62386 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62388 pMem->u.r = sqlite3VdbeRealValue(pMem);
62389 MemSetTypeFlag(pMem, MEM_Real);
62390 return SQLITE_OK;
62394 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
62395 ** Invalidate any prior representations.
62397 ** Every effort is made to force the conversion, even if the input
62398 ** is a string that does not look completely like a number. Convert
62399 ** as much of the string as we can and ignore the rest.
62401 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
62402 if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
62403 assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
62404 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62405 if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
62406 MemSetTypeFlag(pMem, MEM_Int);
62407 }else{
62408 pMem->u.r = sqlite3VdbeRealValue(pMem);
62409 MemSetTypeFlag(pMem, MEM_Real);
62410 sqlite3VdbeIntegerAffinity(pMem);
62413 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
62414 pMem->flags &= ~(MEM_Str|MEM_Blob);
62415 return SQLITE_OK;
62419 ** Cast the datatype of the value in pMem according to the affinity
62420 ** "aff". Casting is different from applying affinity in that a cast
62421 ** is forced. In other words, the value is converted into the desired
62422 ** affinity even if that results in loss of data. This routine is
62423 ** used (for example) to implement the SQL "cast()" operator.
62425 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
62426 if( pMem->flags & MEM_Null ) return;
62427 switch( aff ){
62428 case SQLITE_AFF_NONE: { /* Really a cast to BLOB */
62429 if( (pMem->flags & MEM_Blob)==0 ){
62430 sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
62431 assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
62432 MemSetTypeFlag(pMem, MEM_Blob);
62433 }else{
62434 pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
62436 break;
62438 case SQLITE_AFF_NUMERIC: {
62439 sqlite3VdbeMemNumerify(pMem);
62440 break;
62442 case SQLITE_AFF_INTEGER: {
62443 sqlite3VdbeMemIntegerify(pMem);
62444 break;
62446 case SQLITE_AFF_REAL: {
62447 sqlite3VdbeMemRealify(pMem);
62448 break;
62450 default: {
62451 assert( aff==SQLITE_AFF_TEXT );
62452 assert( MEM_Str==(MEM_Blob>>3) );
62453 pMem->flags |= (pMem->flags&MEM_Blob)>>3;
62454 sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
62455 assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
62456 pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
62457 break;
62463 ** Initialize bulk memory to be a consistent Mem object.
62465 ** The minimum amount of initialization feasible is performed.
62467 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
62468 assert( (flags & ~MEM_TypeMask)==0 );
62469 pMem->flags = flags;
62470 pMem->db = db;
62471 pMem->szMalloc = 0;
62476 ** Delete any previous value and set the value stored in *pMem to NULL.
62478 ** This routine calls the Mem.xDel destructor to dispose of values that
62479 ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
62480 ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
62481 ** routine to invoke the destructor and deallocates Mem.zMalloc.
62483 ** Use this routine to reset the Mem prior to insert a new value.
62485 ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
62487 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
62488 if( VdbeMemDynamic(pMem) ){
62489 vdbeMemClearExternAndSetNull(pMem);
62490 }else{
62491 pMem->flags = MEM_Null;
62494 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
62495 sqlite3VdbeMemSetNull((Mem*)p);
62499 ** Delete any previous value and set the value to be a BLOB of length
62500 ** n containing all zeros.
62502 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
62503 sqlite3VdbeMemRelease(pMem);
62504 pMem->flags = MEM_Blob|MEM_Zero;
62505 pMem->n = 0;
62506 if( n<0 ) n = 0;
62507 pMem->u.nZero = n;
62508 pMem->enc = SQLITE_UTF8;
62509 pMem->z = 0;
62513 ** The pMem is known to contain content that needs to be destroyed prior
62514 ** to a value change. So invoke the destructor, then set the value to
62515 ** a 64-bit integer.
62517 static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
62518 sqlite3VdbeMemSetNull(pMem);
62519 pMem->u.i = val;
62520 pMem->flags = MEM_Int;
62524 ** Delete any previous value and set the value stored in *pMem to val,
62525 ** manifest type INTEGER.
62527 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
62528 if( VdbeMemDynamic(pMem) ){
62529 vdbeReleaseAndSetInt64(pMem, val);
62530 }else{
62531 pMem->u.i = val;
62532 pMem->flags = MEM_Int;
62536 #ifndef SQLITE_OMIT_FLOATING_POINT
62538 ** Delete any previous value and set the value stored in *pMem to val,
62539 ** manifest type REAL.
62541 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
62542 sqlite3VdbeMemSetNull(pMem);
62543 if( !sqlite3IsNaN(val) ){
62544 pMem->u.r = val;
62545 pMem->flags = MEM_Real;
62548 #endif
62551 ** Delete any previous value and set the value of pMem to be an
62552 ** empty boolean index.
62554 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
62555 sqlite3 *db = pMem->db;
62556 assert( db!=0 );
62557 assert( (pMem->flags & MEM_RowSet)==0 );
62558 sqlite3VdbeMemRelease(pMem);
62559 pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
62560 if( db->mallocFailed ){
62561 pMem->flags = MEM_Null;
62562 pMem->szMalloc = 0;
62563 }else{
62564 assert( pMem->zMalloc );
62565 pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
62566 pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
62567 assert( pMem->u.pRowSet!=0 );
62568 pMem->flags = MEM_RowSet;
62573 ** Return true if the Mem object contains a TEXT or BLOB that is
62574 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
62576 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
62577 assert( p->db!=0 );
62578 if( p->flags & (MEM_Str|MEM_Blob) ){
62579 int n = p->n;
62580 if( p->flags & MEM_Zero ){
62581 n += p->u.nZero;
62583 return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
62585 return 0;
62588 #ifdef SQLITE_DEBUG
62590 ** This routine prepares a memory cell for modification by breaking
62591 ** its link to a shallow copy and by marking any current shallow
62592 ** copies of this cell as invalid.
62594 ** This is used for testing and debugging only - to make sure shallow
62595 ** copies are not misused.
62597 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
62598 int i;
62599 Mem *pX;
62600 for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
62601 if( pX->pScopyFrom==pMem ){
62602 pX->flags |= MEM_Undefined;
62603 pX->pScopyFrom = 0;
62606 pMem->pScopyFrom = 0;
62608 #endif /* SQLITE_DEBUG */
62611 ** Size of struct Mem not including the Mem.zMalloc member.
62613 #define MEMCELLSIZE offsetof(Mem,zMalloc)
62616 ** Make an shallow copy of pFrom into pTo. Prior contents of
62617 ** pTo are freed. The pFrom->z field is not duplicated. If
62618 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
62619 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
62621 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
62622 assert( (pFrom->flags & MEM_RowSet)==0 );
62623 assert( pTo->db==pFrom->db );
62624 if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
62625 memcpy(pTo, pFrom, MEMCELLSIZE);
62626 if( (pFrom->flags&MEM_Static)==0 ){
62627 pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
62628 assert( srcType==MEM_Ephem || srcType==MEM_Static );
62629 pTo->flags |= srcType;
62634 ** Make a full copy of pFrom into pTo. Prior contents of pTo are
62635 ** freed before the copy is made.
62637 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
62638 int rc = SQLITE_OK;
62640 assert( pTo->db==pFrom->db );
62641 assert( (pFrom->flags & MEM_RowSet)==0 );
62642 if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
62643 memcpy(pTo, pFrom, MEMCELLSIZE);
62644 pTo->flags &= ~MEM_Dyn;
62645 if( pTo->flags&(MEM_Str|MEM_Blob) ){
62646 if( 0==(pFrom->flags&MEM_Static) ){
62647 pTo->flags |= MEM_Ephem;
62648 rc = sqlite3VdbeMemMakeWriteable(pTo);
62652 return rc;
62656 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
62657 ** freed. If pFrom contains ephemeral data, a copy is made.
62659 ** pFrom contains an SQL NULL when this routine returns.
62661 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
62662 assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
62663 assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
62664 assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
62666 sqlite3VdbeMemRelease(pTo);
62667 memcpy(pTo, pFrom, sizeof(Mem));
62668 pFrom->flags = MEM_Null;
62669 pFrom->szMalloc = 0;
62673 ** Change the value of a Mem to be a string or a BLOB.
62675 ** The memory management strategy depends on the value of the xDel
62676 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
62677 ** string is copied into a (possibly existing) buffer managed by the
62678 ** Mem structure. Otherwise, any existing buffer is freed and the
62679 ** pointer copied.
62681 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
62682 ** size limit) then no memory allocation occurs. If the string can be
62683 ** stored without allocating memory, then it is. If a memory allocation
62684 ** is required to store the string, then value of pMem is unchanged. In
62685 ** either case, SQLITE_TOOBIG is returned.
62687 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
62688 Mem *pMem, /* Memory cell to set to string value */
62689 const char *z, /* String pointer */
62690 int n, /* Bytes in string, or negative */
62691 u8 enc, /* Encoding of z. 0 for BLOBs */
62692 void (*xDel)(void*) /* Destructor function */
62694 int nByte = n; /* New value for pMem->n */
62695 int iLimit; /* Maximum allowed string or blob size */
62696 u16 flags = 0; /* New value for pMem->flags */
62698 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62699 assert( (pMem->flags & MEM_RowSet)==0 );
62701 /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
62702 if( !z ){
62703 sqlite3VdbeMemSetNull(pMem);
62704 return SQLITE_OK;
62707 if( pMem->db ){
62708 iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
62709 }else{
62710 iLimit = SQLITE_MAX_LENGTH;
62712 flags = (enc==0?MEM_Blob:MEM_Str);
62713 if( nByte<0 ){
62714 assert( enc!=0 );
62715 if( enc==SQLITE_UTF8 ){
62716 nByte = sqlite3Strlen30(z);
62717 if( nByte>iLimit ) nByte = iLimit+1;
62718 }else{
62719 for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
62721 flags |= MEM_Term;
62724 /* The following block sets the new values of Mem.z and Mem.xDel. It
62725 ** also sets a flag in local variable "flags" to indicate the memory
62726 ** management (one of MEM_Dyn or MEM_Static).
62728 if( xDel==SQLITE_TRANSIENT ){
62729 int nAlloc = nByte;
62730 if( flags&MEM_Term ){
62731 nAlloc += (enc==SQLITE_UTF8?1:2);
62733 if( nByte>iLimit ){
62734 return SQLITE_TOOBIG;
62736 testcase( nAlloc==0 );
62737 testcase( nAlloc==31 );
62738 testcase( nAlloc==32 );
62739 if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
62740 return SQLITE_NOMEM;
62742 memcpy(pMem->z, z, nAlloc);
62743 }else if( xDel==SQLITE_DYNAMIC ){
62744 sqlite3VdbeMemRelease(pMem);
62745 pMem->zMalloc = pMem->z = (char *)z;
62746 pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
62747 }else{
62748 sqlite3VdbeMemRelease(pMem);
62749 pMem->z = (char *)z;
62750 pMem->xDel = xDel;
62751 flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
62754 pMem->n = nByte;
62755 pMem->flags = flags;
62756 pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
62758 #ifndef SQLITE_OMIT_UTF16
62759 if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
62760 return SQLITE_NOMEM;
62762 #endif
62764 if( nByte>iLimit ){
62765 return SQLITE_TOOBIG;
62768 return SQLITE_OK;
62772 ** Move data out of a btree key or data field and into a Mem structure.
62773 ** The data or key is taken from the entry that pCur is currently pointing
62774 ** to. offset and amt determine what portion of the data or key to retrieve.
62775 ** key is true to get the key or false to get data. The result is written
62776 ** into the pMem element.
62778 ** The pMem object must have been initialized. This routine will use
62779 ** pMem->zMalloc to hold the content from the btree, if possible. New
62780 ** pMem->zMalloc space will be allocated if necessary. The calling routine
62781 ** is responsible for making sure that the pMem object is eventually
62782 ** destroyed.
62784 ** If this routine fails for any reason (malloc returns NULL or unable
62785 ** to read from the disk) then the pMem is left in an inconsistent state.
62787 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
62788 BtCursor *pCur, /* Cursor pointing at record to retrieve. */
62789 u32 offset, /* Offset from the start of data to return bytes from. */
62790 u32 amt, /* Number of bytes to return. */
62791 int key, /* If true, retrieve from the btree key, not data. */
62792 Mem *pMem /* OUT: Return data in this Mem structure. */
62794 char *zData; /* Data from the btree layer */
62795 u32 available = 0; /* Number of bytes available on the local btree page */
62796 int rc = SQLITE_OK; /* Return code */
62798 assert( sqlite3BtreeCursorIsValid(pCur) );
62799 assert( !VdbeMemDynamic(pMem) );
62801 /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
62802 ** that both the BtShared and database handle mutexes are held. */
62803 assert( (pMem->flags & MEM_RowSet)==0 );
62804 if( key ){
62805 zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
62806 }else{
62807 zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
62809 assert( zData!=0 );
62811 if( offset+amt<=available ){
62812 pMem->z = &zData[offset];
62813 pMem->flags = MEM_Blob|MEM_Ephem;
62814 pMem->n = (int)amt;
62815 }else{
62816 pMem->flags = MEM_Null;
62817 if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
62818 if( key ){
62819 rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
62820 }else{
62821 rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
62823 if( rc==SQLITE_OK ){
62824 pMem->z[amt] = 0;
62825 pMem->z[amt+1] = 0;
62826 pMem->flags = MEM_Blob|MEM_Term;
62827 pMem->n = (int)amt;
62828 }else{
62829 sqlite3VdbeMemRelease(pMem);
62834 return rc;
62838 ** The pVal argument is known to be a value other than NULL.
62839 ** Convert it into a string with encoding enc and return a pointer
62840 ** to a zero-terminated version of that string.
62842 static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
62843 assert( pVal!=0 );
62844 assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
62845 assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
62846 assert( (pVal->flags & MEM_RowSet)==0 );
62847 assert( (pVal->flags & (MEM_Null))==0 );
62848 if( pVal->flags & (MEM_Blob|MEM_Str) ){
62849 pVal->flags |= MEM_Str;
62850 if( pVal->flags & MEM_Zero ){
62851 sqlite3VdbeMemExpandBlob(pVal);
62853 if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
62854 sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
62856 if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
62857 assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
62858 if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
62859 return 0;
62862 sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
62863 }else{
62864 sqlite3VdbeMemStringify(pVal, enc, 0);
62865 assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
62867 assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
62868 || pVal->db->mallocFailed );
62869 if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
62870 return pVal->z;
62871 }else{
62872 return 0;
62876 /* This function is only available internally, it is not part of the
62877 ** external API. It works in a similar way to sqlite3_value_text(),
62878 ** except the data returned is in the encoding specified by the second
62879 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
62880 ** SQLITE_UTF8.
62882 ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
62883 ** If that is the case, then the result must be aligned on an even byte
62884 ** boundary.
62886 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
62887 if( !pVal ) return 0;
62888 assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
62889 assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
62890 assert( (pVal->flags & MEM_RowSet)==0 );
62891 if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
62892 return pVal->z;
62894 if( pVal->flags&MEM_Null ){
62895 return 0;
62897 return valueToText(pVal, enc);
62901 ** Create a new sqlite3_value object.
62903 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
62904 Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
62905 if( p ){
62906 p->flags = MEM_Null;
62907 p->db = db;
62909 return p;
62913 ** Context object passed by sqlite3Stat4ProbeSetValue() through to
62914 ** valueNew(). See comments above valueNew() for details.
62916 struct ValueNewStat4Ctx {
62917 Parse *pParse;
62918 Index *pIdx;
62919 UnpackedRecord **ppRec;
62920 int iVal;
62924 ** Allocate and return a pointer to a new sqlite3_value object. If
62925 ** the second argument to this function is NULL, the object is allocated
62926 ** by calling sqlite3ValueNew().
62928 ** Otherwise, if the second argument is non-zero, then this function is
62929 ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
62930 ** already been allocated, allocate the UnpackedRecord structure that
62931 ** that function will return to its caller here. Then return a pointer
62932 ** an sqlite3_value within the UnpackedRecord.a[] array.
62934 static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
62935 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
62936 if( p ){
62937 UnpackedRecord *pRec = p->ppRec[0];
62939 if( pRec==0 ){
62940 Index *pIdx = p->pIdx; /* Index being probed */
62941 int nByte; /* Bytes of space to allocate */
62942 int i; /* Counter variable */
62943 int nCol = pIdx->nColumn; /* Number of index columns including rowid */
62945 nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
62946 pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
62947 if( pRec ){
62948 pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
62949 if( pRec->pKeyInfo ){
62950 assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
62951 assert( pRec->pKeyInfo->enc==ENC(db) );
62952 pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
62953 for(i=0; i<nCol; i++){
62954 pRec->aMem[i].flags = MEM_Null;
62955 pRec->aMem[i].db = db;
62957 }else{
62958 sqlite3DbFree(db, pRec);
62959 pRec = 0;
62962 if( pRec==0 ) return 0;
62963 p->ppRec[0] = pRec;
62966 pRec->nField = p->iVal+1;
62967 return &pRec->aMem[p->iVal];
62969 #else
62970 UNUSED_PARAMETER(p);
62971 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
62972 return sqlite3ValueNew(db);
62976 ** Extract a value from the supplied expression in the manner described
62977 ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
62978 ** using valueNew().
62980 ** If pCtx is NULL and an error occurs after the sqlite3_value object
62981 ** has been allocated, it is freed before returning. Or, if pCtx is not
62982 ** NULL, it is assumed that the caller will free any allocated object
62983 ** in all cases.
62985 static int valueFromExpr(
62986 sqlite3 *db, /* The database connection */
62987 Expr *pExpr, /* The expression to evaluate */
62988 u8 enc, /* Encoding to use */
62989 u8 affinity, /* Affinity to use */
62990 sqlite3_value **ppVal, /* Write the new value here */
62991 struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
62993 int op;
62994 char *zVal = 0;
62995 sqlite3_value *pVal = 0;
62996 int negInt = 1;
62997 const char *zNeg = "";
62998 int rc = SQLITE_OK;
63000 if( !pExpr ){
63001 *ppVal = 0;
63002 return SQLITE_OK;
63004 while( (op = pExpr->op)==TK_UPLUS ) pExpr = pExpr->pLeft;
63005 if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
63007 if( op==TK_CAST ){
63008 u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
63009 rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
63010 testcase( rc!=SQLITE_OK );
63011 if( *ppVal ){
63012 sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
63013 sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
63015 return rc;
63018 /* Handle negative integers in a single step. This is needed in the
63019 ** case when the value is -9223372036854775808.
63021 if( op==TK_UMINUS
63022 && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
63023 pExpr = pExpr->pLeft;
63024 op = pExpr->op;
63025 negInt = -1;
63026 zNeg = "-";
63029 if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
63030 pVal = valueNew(db, pCtx);
63031 if( pVal==0 ) goto no_mem;
63032 if( ExprHasProperty(pExpr, EP_IntValue) ){
63033 sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
63034 }else{
63035 zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
63036 if( zVal==0 ) goto no_mem;
63037 sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
63039 if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
63040 sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
63041 }else{
63042 sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
63044 if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
63045 if( enc!=SQLITE_UTF8 ){
63046 rc = sqlite3VdbeChangeEncoding(pVal, enc);
63048 }else if( op==TK_UMINUS ) {
63049 /* This branch happens for multiple negative signs. Ex: -(-5) */
63050 if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
63051 && pVal!=0
63053 sqlite3VdbeMemNumerify(pVal);
63054 if( pVal->flags & MEM_Real ){
63055 pVal->u.r = -pVal->u.r;
63056 }else if( pVal->u.i==SMALLEST_INT64 ){
63057 pVal->u.r = -(double)SMALLEST_INT64;
63058 MemSetTypeFlag(pVal, MEM_Real);
63059 }else{
63060 pVal->u.i = -pVal->u.i;
63062 sqlite3ValueApplyAffinity(pVal, affinity, enc);
63064 }else if( op==TK_NULL ){
63065 pVal = valueNew(db, pCtx);
63066 if( pVal==0 ) goto no_mem;
63068 #ifndef SQLITE_OMIT_BLOB_LITERAL
63069 else if( op==TK_BLOB ){
63070 int nVal;
63071 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
63072 assert( pExpr->u.zToken[1]=='\'' );
63073 pVal = valueNew(db, pCtx);
63074 if( !pVal ) goto no_mem;
63075 zVal = &pExpr->u.zToken[2];
63076 nVal = sqlite3Strlen30(zVal)-1;
63077 assert( zVal[nVal]=='\'' );
63078 sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
63079 0, SQLITE_DYNAMIC);
63081 #endif
63083 *ppVal = pVal;
63084 return rc;
63086 no_mem:
63087 db->mallocFailed = 1;
63088 sqlite3DbFree(db, zVal);
63089 assert( *ppVal==0 );
63090 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
63091 if( pCtx==0 ) sqlite3ValueFree(pVal);
63092 #else
63093 assert( pCtx==0 ); sqlite3ValueFree(pVal);
63094 #endif
63095 return SQLITE_NOMEM;
63099 ** Create a new sqlite3_value object, containing the value of pExpr.
63101 ** This only works for very simple expressions that consist of one constant
63102 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
63103 ** be converted directly into a value, then the value is allocated and
63104 ** a pointer written to *ppVal. The caller is responsible for deallocating
63105 ** the value by passing it to sqlite3ValueFree() later on. If the expression
63106 ** cannot be converted to a value, then *ppVal is set to NULL.
63108 SQLITE_PRIVATE int sqlite3ValueFromExpr(
63109 sqlite3 *db, /* The database connection */
63110 Expr *pExpr, /* The expression to evaluate */
63111 u8 enc, /* Encoding to use */
63112 u8 affinity, /* Affinity to use */
63113 sqlite3_value **ppVal /* Write the new value here */
63115 return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
63118 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
63120 ** The implementation of the sqlite_record() function. This function accepts
63121 ** a single argument of any type. The return value is a formatted database
63122 ** record (a blob) containing the argument value.
63124 ** This is used to convert the value stored in the 'sample' column of the
63125 ** sqlite_stat3 table to the record format SQLite uses internally.
63127 static void recordFunc(
63128 sqlite3_context *context,
63129 int argc,
63130 sqlite3_value **argv
63132 const int file_format = 1;
63133 int iSerial; /* Serial type */
63134 int nSerial; /* Bytes of space for iSerial as varint */
63135 int nVal; /* Bytes of space required for argv[0] */
63136 int nRet;
63137 sqlite3 *db;
63138 u8 *aRet;
63140 UNUSED_PARAMETER( argc );
63141 iSerial = sqlite3VdbeSerialType(argv[0], file_format);
63142 nSerial = sqlite3VarintLen(iSerial);
63143 nVal = sqlite3VdbeSerialTypeLen(iSerial);
63144 db = sqlite3_context_db_handle(context);
63146 nRet = 1 + nSerial + nVal;
63147 aRet = sqlite3DbMallocRaw(db, nRet);
63148 if( aRet==0 ){
63149 sqlite3_result_error_nomem(context);
63150 }else{
63151 aRet[0] = nSerial+1;
63152 putVarint32(&aRet[1], iSerial);
63153 sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
63154 sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
63155 sqlite3DbFree(db, aRet);
63160 ** Register built-in functions used to help read ANALYZE data.
63162 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
63163 static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
63164 FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
63166 int i;
63167 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
63168 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
63169 for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
63170 sqlite3FuncDefInsert(pHash, &aFunc[i]);
63175 ** Attempt to extract a value from pExpr and use it to construct *ppVal.
63177 ** If pAlloc is not NULL, then an UnpackedRecord object is created for
63178 ** pAlloc if one does not exist and the new value is added to the
63179 ** UnpackedRecord object.
63181 ** A value is extracted in the following cases:
63183 ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
63185 ** * The expression is a bound variable, and this is a reprepare, or
63187 ** * The expression is a literal value.
63189 ** On success, *ppVal is made to point to the extracted value. The caller
63190 ** is responsible for ensuring that the value is eventually freed.
63192 static int stat4ValueFromExpr(
63193 Parse *pParse, /* Parse context */
63194 Expr *pExpr, /* The expression to extract a value from */
63195 u8 affinity, /* Affinity to use */
63196 struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
63197 sqlite3_value **ppVal /* OUT: New value object (or NULL) */
63199 int rc = SQLITE_OK;
63200 sqlite3_value *pVal = 0;
63201 sqlite3 *db = pParse->db;
63203 /* Skip over any TK_COLLATE nodes */
63204 pExpr = sqlite3ExprSkipCollate(pExpr);
63206 if( !pExpr ){
63207 pVal = valueNew(db, pAlloc);
63208 if( pVal ){
63209 sqlite3VdbeMemSetNull((Mem*)pVal);
63211 }else if( pExpr->op==TK_VARIABLE
63212 || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
63214 Vdbe *v;
63215 int iBindVar = pExpr->iColumn;
63216 sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
63217 if( (v = pParse->pReprepare)!=0 ){
63218 pVal = valueNew(db, pAlloc);
63219 if( pVal ){
63220 rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
63221 if( rc==SQLITE_OK ){
63222 sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
63224 pVal->db = pParse->db;
63227 }else{
63228 rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
63231 assert( pVal==0 || pVal->db==db );
63232 *ppVal = pVal;
63233 return rc;
63237 ** This function is used to allocate and populate UnpackedRecord
63238 ** structures intended to be compared against sample index keys stored
63239 ** in the sqlite_stat4 table.
63241 ** A single call to this function attempts to populates field iVal (leftmost
63242 ** is 0 etc.) of the unpacked record with a value extracted from expression
63243 ** pExpr. Extraction of values is possible if:
63245 ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
63247 ** * The expression is a bound variable, and this is a reprepare, or
63249 ** * The sqlite3ValueFromExpr() function is able to extract a value
63250 ** from the expression (i.e. the expression is a literal value).
63252 ** If a value can be extracted, the affinity passed as the 5th argument
63253 ** is applied to it before it is copied into the UnpackedRecord. Output
63254 ** parameter *pbOk is set to true if a value is extracted, or false
63255 ** otherwise.
63257 ** When this function is called, *ppRec must either point to an object
63258 ** allocated by an earlier call to this function, or must be NULL. If it
63259 ** is NULL and a value can be successfully extracted, a new UnpackedRecord
63260 ** is allocated (and *ppRec set to point to it) before returning.
63262 ** Unless an error is encountered, SQLITE_OK is returned. It is not an
63263 ** error if a value cannot be extracted from pExpr. If an error does
63264 ** occur, an SQLite error code is returned.
63266 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
63267 Parse *pParse, /* Parse context */
63268 Index *pIdx, /* Index being probed */
63269 UnpackedRecord **ppRec, /* IN/OUT: Probe record */
63270 Expr *pExpr, /* The expression to extract a value from */
63271 u8 affinity, /* Affinity to use */
63272 int iVal, /* Array element to populate */
63273 int *pbOk /* OUT: True if value was extracted */
63275 int rc;
63276 sqlite3_value *pVal = 0;
63277 struct ValueNewStat4Ctx alloc;
63279 alloc.pParse = pParse;
63280 alloc.pIdx = pIdx;
63281 alloc.ppRec = ppRec;
63282 alloc.iVal = iVal;
63284 rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
63285 assert( pVal==0 || pVal->db==pParse->db );
63286 *pbOk = (pVal!=0);
63287 return rc;
63291 ** Attempt to extract a value from expression pExpr using the methods
63292 ** as described for sqlite3Stat4ProbeSetValue() above.
63294 ** If successful, set *ppVal to point to a new value object and return
63295 ** SQLITE_OK. If no value can be extracted, but no other error occurs
63296 ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
63297 ** does occur, return an SQLite error code. The final value of *ppVal
63298 ** is undefined in this case.
63300 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
63301 Parse *pParse, /* Parse context */
63302 Expr *pExpr, /* The expression to extract a value from */
63303 u8 affinity, /* Affinity to use */
63304 sqlite3_value **ppVal /* OUT: New value object (or NULL) */
63306 return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
63310 ** Extract the iCol-th column from the nRec-byte record in pRec. Write
63311 ** the column value into *ppVal. If *ppVal is initially NULL then a new
63312 ** sqlite3_value object is allocated.
63314 ** If *ppVal is initially NULL then the caller is responsible for
63315 ** ensuring that the value written into *ppVal is eventually freed.
63317 SQLITE_PRIVATE int sqlite3Stat4Column(
63318 sqlite3 *db, /* Database handle */
63319 const void *pRec, /* Pointer to buffer containing record */
63320 int nRec, /* Size of buffer pRec in bytes */
63321 int iCol, /* Column to extract */
63322 sqlite3_value **ppVal /* OUT: Extracted value */
63324 u32 t; /* a column type code */
63325 int nHdr; /* Size of the header in the record */
63326 int iHdr; /* Next unread header byte */
63327 int iField; /* Next unread data byte */
63328 int szField; /* Size of the current data field */
63329 int i; /* Column index */
63330 u8 *a = (u8*)pRec; /* Typecast byte array */
63331 Mem *pMem = *ppVal; /* Write result into this Mem object */
63333 assert( iCol>0 );
63334 iHdr = getVarint32(a, nHdr);
63335 if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
63336 iField = nHdr;
63337 for(i=0; i<=iCol; i++){
63338 iHdr += getVarint32(&a[iHdr], t);
63339 testcase( iHdr==nHdr );
63340 testcase( iHdr==nHdr+1 );
63341 if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
63342 szField = sqlite3VdbeSerialTypeLen(t);
63343 iField += szField;
63345 testcase( iField==nRec );
63346 testcase( iField==nRec+1 );
63347 if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
63348 if( pMem==0 ){
63349 pMem = *ppVal = sqlite3ValueNew(db);
63350 if( pMem==0 ) return SQLITE_NOMEM;
63352 sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
63353 pMem->enc = ENC(db);
63354 return SQLITE_OK;
63358 ** Unless it is NULL, the argument must be an UnpackedRecord object returned
63359 ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
63360 ** the object.
63362 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
63363 if( pRec ){
63364 int i;
63365 int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
63366 Mem *aMem = pRec->aMem;
63367 sqlite3 *db = aMem[0].db;
63368 for(i=0; i<nCol; i++){
63369 if( aMem[i].szMalloc ) sqlite3DbFree(db, aMem[i].zMalloc);
63371 sqlite3KeyInfoUnref(pRec->pKeyInfo);
63372 sqlite3DbFree(db, pRec);
63375 #endif /* ifdef SQLITE_ENABLE_STAT4 */
63378 ** Change the string value of an sqlite3_value object
63380 SQLITE_PRIVATE void sqlite3ValueSetStr(
63381 sqlite3_value *v, /* Value to be set */
63382 int n, /* Length of string z */
63383 const void *z, /* Text of the new string */
63384 u8 enc, /* Encoding to use */
63385 void (*xDel)(void*) /* Destructor for the string */
63387 if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
63391 ** Free an sqlite3_value object
63393 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
63394 if( !v ) return;
63395 sqlite3VdbeMemRelease((Mem *)v);
63396 sqlite3DbFree(((Mem*)v)->db, v);
63400 ** Return the number of bytes in the sqlite3_value object assuming
63401 ** that it uses the encoding "enc"
63403 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
63404 Mem *p = (Mem*)pVal;
63405 if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
63406 if( p->flags & MEM_Zero ){
63407 return p->n + p->u.nZero;
63408 }else{
63409 return p->n;
63412 return 0;
63415 /************** End of vdbemem.c *********************************************/
63416 /************** Begin file vdbeaux.c *****************************************/
63418 ** 2003 September 6
63420 ** The author disclaims copyright to this source code. In place of
63421 ** a legal notice, here is a blessing:
63423 ** May you do good and not evil.
63424 ** May you find forgiveness for yourself and forgive others.
63425 ** May you share freely, never taking more than you give.
63427 *************************************************************************
63428 ** This file contains code used for creating, destroying, and populating
63429 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
63433 ** Create a new virtual database engine.
63435 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
63436 sqlite3 *db = pParse->db;
63437 Vdbe *p;
63438 p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
63439 if( p==0 ) return 0;
63440 p->db = db;
63441 if( db->pVdbe ){
63442 db->pVdbe->pPrev = p;
63444 p->pNext = db->pVdbe;
63445 p->pPrev = 0;
63446 db->pVdbe = p;
63447 p->magic = VDBE_MAGIC_INIT;
63448 p->pParse = pParse;
63449 assert( pParse->aLabel==0 );
63450 assert( pParse->nLabel==0 );
63451 assert( pParse->nOpAlloc==0 );
63452 return p;
63456 ** Remember the SQL string for a prepared statement.
63458 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
63459 assert( isPrepareV2==1 || isPrepareV2==0 );
63460 if( p==0 ) return;
63461 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
63462 if( !isPrepareV2 ) return;
63463 #endif
63464 assert( p->zSql==0 );
63465 p->zSql = sqlite3DbStrNDup(p->db, z, n);
63466 p->isPrepareV2 = (u8)isPrepareV2;
63470 ** Return the SQL associated with a prepared statement
63472 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
63473 Vdbe *p = (Vdbe *)pStmt;
63474 return (p && p->isPrepareV2) ? p->zSql : 0;
63478 ** Swap all content between two VDBE structures.
63480 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
63481 Vdbe tmp, *pTmp;
63482 char *zTmp;
63483 tmp = *pA;
63484 *pA = *pB;
63485 *pB = tmp;
63486 pTmp = pA->pNext;
63487 pA->pNext = pB->pNext;
63488 pB->pNext = pTmp;
63489 pTmp = pA->pPrev;
63490 pA->pPrev = pB->pPrev;
63491 pB->pPrev = pTmp;
63492 zTmp = pA->zSql;
63493 pA->zSql = pB->zSql;
63494 pB->zSql = zTmp;
63495 pB->isPrepareV2 = pA->isPrepareV2;
63499 ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
63500 ** than its current size. nOp is guaranteed to be less than or equal
63501 ** to 1024/sizeof(Op).
63503 ** If an out-of-memory error occurs while resizing the array, return
63504 ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
63505 ** unchanged (this is so that any opcodes already allocated can be
63506 ** correctly deallocated along with the rest of the Vdbe).
63508 static int growOpArray(Vdbe *v, int nOp){
63509 VdbeOp *pNew;
63510 Parse *p = v->pParse;
63512 /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
63513 ** more frequent reallocs and hence provide more opportunities for
63514 ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
63515 ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
63516 ** by the minimum* amount required until the size reaches 512. Normal
63517 ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
63518 ** size of the op array or add 1KB of space, whichever is smaller. */
63519 #ifdef SQLITE_TEST_REALLOC_STRESS
63520 int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
63521 #else
63522 int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
63523 UNUSED_PARAMETER(nOp);
63524 #endif
63526 assert( nOp<=(1024/sizeof(Op)) );
63527 assert( nNew>=(p->nOpAlloc+nOp) );
63528 pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
63529 if( pNew ){
63530 p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
63531 v->aOp = pNew;
63533 return (pNew ? SQLITE_OK : SQLITE_NOMEM);
63536 #ifdef SQLITE_DEBUG
63537 /* This routine is just a convenient place to set a breakpoint that will
63538 ** fire after each opcode is inserted and displayed using
63539 ** "PRAGMA vdbe_addoptrace=on".
63541 static void test_addop_breakpoint(void){
63542 static int n = 0;
63543 n++;
63545 #endif
63548 ** Add a new instruction to the list of instructions current in the
63549 ** VDBE. Return the address of the new instruction.
63551 ** Parameters:
63553 ** p Pointer to the VDBE
63555 ** op The opcode for this instruction
63557 ** p1, p2, p3 Operands
63559 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
63560 ** the sqlite3VdbeChangeP4() function to change the value of the P4
63561 ** operand.
63563 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
63564 int i;
63565 VdbeOp *pOp;
63567 i = p->nOp;
63568 assert( p->magic==VDBE_MAGIC_INIT );
63569 assert( op>0 && op<0xff );
63570 if( p->pParse->nOpAlloc<=i ){
63571 if( growOpArray(p, 1) ){
63572 return 1;
63575 p->nOp++;
63576 pOp = &p->aOp[i];
63577 pOp->opcode = (u8)op;
63578 pOp->p5 = 0;
63579 pOp->p1 = p1;
63580 pOp->p2 = p2;
63581 pOp->p3 = p3;
63582 pOp->p4.p = 0;
63583 pOp->p4type = P4_NOTUSED;
63584 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
63585 pOp->zComment = 0;
63586 #endif
63587 #ifdef SQLITE_DEBUG
63588 if( p->db->flags & SQLITE_VdbeAddopTrace ){
63589 int jj, kk;
63590 Parse *pParse = p->pParse;
63591 for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
63592 struct yColCache *x = pParse->aColCache + jj;
63593 if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
63594 printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
63595 kk++;
63597 if( kk ) printf("\n");
63598 sqlite3VdbePrintOp(0, i, &p->aOp[i]);
63599 test_addop_breakpoint();
63601 #endif
63602 #ifdef VDBE_PROFILE
63603 pOp->cycles = 0;
63604 pOp->cnt = 0;
63605 #endif
63606 #ifdef SQLITE_VDBE_COVERAGE
63607 pOp->iSrcLine = 0;
63608 #endif
63609 return i;
63611 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
63612 return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
63614 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
63615 return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
63617 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
63618 return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
63623 ** Add an opcode that includes the p4 value as a pointer.
63625 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
63626 Vdbe *p, /* Add the opcode to this VM */
63627 int op, /* The new opcode */
63628 int p1, /* The P1 operand */
63629 int p2, /* The P2 operand */
63630 int p3, /* The P3 operand */
63631 const char *zP4, /* The P4 operand */
63632 int p4type /* P4 operand type */
63634 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
63635 sqlite3VdbeChangeP4(p, addr, zP4, p4type);
63636 return addr;
63640 ** Add an OP_ParseSchema opcode. This routine is broken out from
63641 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
63642 ** as having been used.
63644 ** The zWhere string must have been obtained from sqlite3_malloc().
63645 ** This routine will take ownership of the allocated memory.
63647 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
63648 int j;
63649 int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
63650 sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
63651 for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
63655 ** Add an opcode that includes the p4 value as an integer.
63657 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
63658 Vdbe *p, /* Add the opcode to this VM */
63659 int op, /* The new opcode */
63660 int p1, /* The P1 operand */
63661 int p2, /* The P2 operand */
63662 int p3, /* The P3 operand */
63663 int p4 /* The P4 operand as an integer */
63665 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
63666 sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
63667 return addr;
63671 ** Create a new symbolic label for an instruction that has yet to be
63672 ** coded. The symbolic label is really just a negative number. The
63673 ** label can be used as the P2 value of an operation. Later, when
63674 ** the label is resolved to a specific address, the VDBE will scan
63675 ** through its operation list and change all values of P2 which match
63676 ** the label into the resolved address.
63678 ** The VDBE knows that a P2 value is a label because labels are
63679 ** always negative and P2 values are suppose to be non-negative.
63680 ** Hence, a negative P2 value is a label that has yet to be resolved.
63682 ** Zero is returned if a malloc() fails.
63684 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
63685 Parse *p = v->pParse;
63686 int i = p->nLabel++;
63687 assert( v->magic==VDBE_MAGIC_INIT );
63688 if( (i & (i-1))==0 ){
63689 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
63690 (i*2+1)*sizeof(p->aLabel[0]));
63692 if( p->aLabel ){
63693 p->aLabel[i] = -1;
63695 return -1-i;
63699 ** Resolve label "x" to be the address of the next instruction to
63700 ** be inserted. The parameter "x" must have been obtained from
63701 ** a prior call to sqlite3VdbeMakeLabel().
63703 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
63704 Parse *p = v->pParse;
63705 int j = -1-x;
63706 assert( v->magic==VDBE_MAGIC_INIT );
63707 assert( j<p->nLabel );
63708 if( ALWAYS(j>=0) && p->aLabel ){
63709 p->aLabel[j] = v->nOp;
63711 p->iFixedOp = v->nOp - 1;
63715 ** Mark the VDBE as one that can only be run one time.
63717 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
63718 p->runOnlyOnce = 1;
63721 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
63724 ** The following type and function are used to iterate through all opcodes
63725 ** in a Vdbe main program and each of the sub-programs (triggers) it may
63726 ** invoke directly or indirectly. It should be used as follows:
63728 ** Op *pOp;
63729 ** VdbeOpIter sIter;
63731 ** memset(&sIter, 0, sizeof(sIter));
63732 ** sIter.v = v; // v is of type Vdbe*
63733 ** while( (pOp = opIterNext(&sIter)) ){
63734 ** // Do something with pOp
63735 ** }
63736 ** sqlite3DbFree(v->db, sIter.apSub);
63739 typedef struct VdbeOpIter VdbeOpIter;
63740 struct VdbeOpIter {
63741 Vdbe *v; /* Vdbe to iterate through the opcodes of */
63742 SubProgram **apSub; /* Array of subprograms */
63743 int nSub; /* Number of entries in apSub */
63744 int iAddr; /* Address of next instruction to return */
63745 int iSub; /* 0 = main program, 1 = first sub-program etc. */
63747 static Op *opIterNext(VdbeOpIter *p){
63748 Vdbe *v = p->v;
63749 Op *pRet = 0;
63750 Op *aOp;
63751 int nOp;
63753 if( p->iSub<=p->nSub ){
63755 if( p->iSub==0 ){
63756 aOp = v->aOp;
63757 nOp = v->nOp;
63758 }else{
63759 aOp = p->apSub[p->iSub-1]->aOp;
63760 nOp = p->apSub[p->iSub-1]->nOp;
63762 assert( p->iAddr<nOp );
63764 pRet = &aOp[p->iAddr];
63765 p->iAddr++;
63766 if( p->iAddr==nOp ){
63767 p->iSub++;
63768 p->iAddr = 0;
63771 if( pRet->p4type==P4_SUBPROGRAM ){
63772 int nByte = (p->nSub+1)*sizeof(SubProgram*);
63773 int j;
63774 for(j=0; j<p->nSub; j++){
63775 if( p->apSub[j]==pRet->p4.pProgram ) break;
63777 if( j==p->nSub ){
63778 p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
63779 if( !p->apSub ){
63780 pRet = 0;
63781 }else{
63782 p->apSub[p->nSub++] = pRet->p4.pProgram;
63788 return pRet;
63792 ** Check if the program stored in the VM associated with pParse may
63793 ** throw an ABORT exception (causing the statement, but not entire transaction
63794 ** to be rolled back). This condition is true if the main program or any
63795 ** sub-programs contains any of the following:
63797 ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
63798 ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
63799 ** * OP_Destroy
63800 ** * OP_VUpdate
63801 ** * OP_VRename
63802 ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
63804 ** Then check that the value of Parse.mayAbort is true if an
63805 ** ABORT may be thrown, or false otherwise. Return true if it does
63806 ** match, or false otherwise. This function is intended to be used as
63807 ** part of an assert statement in the compiler. Similar to:
63809 ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
63811 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
63812 int hasAbort = 0;
63813 Op *pOp;
63814 VdbeOpIter sIter;
63815 memset(&sIter, 0, sizeof(sIter));
63816 sIter.v = v;
63818 while( (pOp = opIterNext(&sIter))!=0 ){
63819 int opcode = pOp->opcode;
63820 if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
63821 #ifndef SQLITE_OMIT_FOREIGN_KEY
63822 || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
63823 #endif
63824 || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
63825 && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
63827 hasAbort = 1;
63828 break;
63831 sqlite3DbFree(v->db, sIter.apSub);
63833 /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
63834 ** If malloc failed, then the while() loop above may not have iterated
63835 ** through all opcodes and hasAbort may be set incorrectly. Return
63836 ** true for this case to prevent the assert() in the callers frame
63837 ** from failing. */
63838 return ( v->db->mallocFailed || hasAbort==mayAbort );
63840 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
63843 ** Loop through the program looking for P2 values that are negative
63844 ** on jump instructions. Each such value is a label. Resolve the
63845 ** label by setting the P2 value to its correct non-zero value.
63847 ** This routine is called once after all opcodes have been inserted.
63849 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
63850 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
63851 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
63853 ** The Op.opflags field is set on all opcodes.
63855 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
63856 int i;
63857 int nMaxArgs = *pMaxFuncArgs;
63858 Op *pOp;
63859 Parse *pParse = p->pParse;
63860 int *aLabel = pParse->aLabel;
63861 p->readOnly = 1;
63862 p->bIsReader = 0;
63863 for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
63864 u8 opcode = pOp->opcode;
63866 /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
63867 ** cases from this switch! */
63868 switch( opcode ){
63869 case OP_Function:
63870 case OP_AggStep: {
63871 if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
63872 break;
63874 case OP_Transaction: {
63875 if( pOp->p2!=0 ) p->readOnly = 0;
63876 /* fall thru */
63878 case OP_AutoCommit:
63879 case OP_Savepoint: {
63880 p->bIsReader = 1;
63881 break;
63883 #ifndef SQLITE_OMIT_WAL
63884 case OP_Checkpoint:
63885 #endif
63886 case OP_Vacuum:
63887 case OP_JournalMode: {
63888 p->readOnly = 0;
63889 p->bIsReader = 1;
63890 break;
63892 #ifndef SQLITE_OMIT_VIRTUALTABLE
63893 case OP_VUpdate: {
63894 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
63895 break;
63897 case OP_VFilter: {
63898 int n;
63899 assert( p->nOp - i >= 3 );
63900 assert( pOp[-1].opcode==OP_Integer );
63901 n = pOp[-1].p1;
63902 if( n>nMaxArgs ) nMaxArgs = n;
63903 break;
63905 #endif
63906 case OP_Next:
63907 case OP_NextIfOpen:
63908 case OP_SorterNext: {
63909 pOp->p4.xAdvance = sqlite3BtreeNext;
63910 pOp->p4type = P4_ADVANCE;
63911 break;
63913 case OP_Prev:
63914 case OP_PrevIfOpen: {
63915 pOp->p4.xAdvance = sqlite3BtreePrevious;
63916 pOp->p4type = P4_ADVANCE;
63917 break;
63921 pOp->opflags = sqlite3OpcodeProperty[opcode];
63922 if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
63923 assert( -1-pOp->p2<pParse->nLabel );
63924 pOp->p2 = aLabel[-1-pOp->p2];
63927 sqlite3DbFree(p->db, pParse->aLabel);
63928 pParse->aLabel = 0;
63929 pParse->nLabel = 0;
63930 *pMaxFuncArgs = nMaxArgs;
63931 assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
63935 ** Return the address of the next instruction to be inserted.
63937 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
63938 assert( p->magic==VDBE_MAGIC_INIT );
63939 return p->nOp;
63943 ** This function returns a pointer to the array of opcodes associated with
63944 ** the Vdbe passed as the first argument. It is the callers responsibility
63945 ** to arrange for the returned array to be eventually freed using the
63946 ** vdbeFreeOpArray() function.
63948 ** Before returning, *pnOp is set to the number of entries in the returned
63949 ** array. Also, *pnMaxArg is set to the larger of its current value and
63950 ** the number of entries in the Vdbe.apArg[] array required to execute the
63951 ** returned program.
63953 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
63954 VdbeOp *aOp = p->aOp;
63955 assert( aOp && !p->db->mallocFailed );
63957 /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
63958 assert( DbMaskAllZero(p->btreeMask) );
63960 resolveP2Values(p, pnMaxArg);
63961 *pnOp = p->nOp;
63962 p->aOp = 0;
63963 return aOp;
63967 ** Add a whole list of operations to the operation stack. Return the
63968 ** address of the first operation added.
63970 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
63971 int addr;
63972 assert( p->magic==VDBE_MAGIC_INIT );
63973 if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
63974 return 0;
63976 addr = p->nOp;
63977 if( ALWAYS(nOp>0) ){
63978 int i;
63979 VdbeOpList const *pIn = aOp;
63980 for(i=0; i<nOp; i++, pIn++){
63981 int p2 = pIn->p2;
63982 VdbeOp *pOut = &p->aOp[i+addr];
63983 pOut->opcode = pIn->opcode;
63984 pOut->p1 = pIn->p1;
63985 if( p2<0 ){
63986 assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
63987 pOut->p2 = addr + ADDR(p2);
63988 }else{
63989 pOut->p2 = p2;
63991 pOut->p3 = pIn->p3;
63992 pOut->p4type = P4_NOTUSED;
63993 pOut->p4.p = 0;
63994 pOut->p5 = 0;
63995 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
63996 pOut->zComment = 0;
63997 #endif
63998 #ifdef SQLITE_VDBE_COVERAGE
63999 pOut->iSrcLine = iLineno+i;
64000 #else
64001 (void)iLineno;
64002 #endif
64003 #ifdef SQLITE_DEBUG
64004 if( p->db->flags & SQLITE_VdbeAddopTrace ){
64005 sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
64007 #endif
64009 p->nOp += nOp;
64011 return addr;
64015 ** Change the value of the P1 operand for a specific instruction.
64016 ** This routine is useful when a large program is loaded from a
64017 ** static array using sqlite3VdbeAddOpList but we want to make a
64018 ** few minor changes to the program.
64020 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
64021 assert( p!=0 );
64022 if( ((u32)p->nOp)>addr ){
64023 p->aOp[addr].p1 = val;
64028 ** Change the value of the P2 operand for a specific instruction.
64029 ** This routine is useful for setting a jump destination.
64031 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
64032 assert( p!=0 );
64033 if( ((u32)p->nOp)>addr ){
64034 p->aOp[addr].p2 = val;
64039 ** Change the value of the P3 operand for a specific instruction.
64041 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
64042 assert( p!=0 );
64043 if( ((u32)p->nOp)>addr ){
64044 p->aOp[addr].p3 = val;
64049 ** Change the value of the P5 operand for the most recently
64050 ** added operation.
64052 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
64053 assert( p!=0 );
64054 if( p->aOp ){
64055 assert( p->nOp>0 );
64056 p->aOp[p->nOp-1].p5 = val;
64061 ** Change the P2 operand of instruction addr so that it points to
64062 ** the address of the next instruction to be coded.
64064 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
64065 sqlite3VdbeChangeP2(p, addr, p->nOp);
64066 p->pParse->iFixedOp = p->nOp - 1;
64071 ** If the input FuncDef structure is ephemeral, then free it. If
64072 ** the FuncDef is not ephermal, then do nothing.
64074 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
64075 if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
64076 sqlite3DbFree(db, pDef);
64080 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
64083 ** Delete a P4 value if necessary.
64085 static void freeP4(sqlite3 *db, int p4type, void *p4){
64086 if( p4 ){
64087 assert( db );
64088 switch( p4type ){
64089 case P4_REAL:
64090 case P4_INT64:
64091 case P4_DYNAMIC:
64092 case P4_INTARRAY: {
64093 sqlite3DbFree(db, p4);
64094 break;
64096 case P4_KEYINFO: {
64097 if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
64098 break;
64100 case P4_MPRINTF: {
64101 if( db->pnBytesFreed==0 ) sqlite3_free(p4);
64102 break;
64104 case P4_FUNCDEF: {
64105 freeEphemeralFunction(db, (FuncDef*)p4);
64106 break;
64108 case P4_MEM: {
64109 if( db->pnBytesFreed==0 ){
64110 sqlite3ValueFree((sqlite3_value*)p4);
64111 }else{
64112 Mem *p = (Mem*)p4;
64113 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
64114 sqlite3DbFree(db, p);
64116 break;
64118 case P4_VTAB : {
64119 if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
64120 break;
64127 ** Free the space allocated for aOp and any p4 values allocated for the
64128 ** opcodes contained within. If aOp is not NULL it is assumed to contain
64129 ** nOp entries.
64131 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
64132 if( aOp ){
64133 Op *pOp;
64134 for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
64135 freeP4(db, pOp->p4type, pOp->p4.p);
64136 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
64137 sqlite3DbFree(db, pOp->zComment);
64138 #endif
64141 sqlite3DbFree(db, aOp);
64145 ** Link the SubProgram object passed as the second argument into the linked
64146 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
64147 ** objects when the VM is no longer required.
64149 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
64150 p->pNext = pVdbe->pProgram;
64151 pVdbe->pProgram = p;
64155 ** Change the opcode at addr into OP_Noop
64157 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
64158 if( addr<p->nOp ){
64159 VdbeOp *pOp = &p->aOp[addr];
64160 sqlite3 *db = p->db;
64161 freeP4(db, pOp->p4type, pOp->p4.p);
64162 memset(pOp, 0, sizeof(pOp[0]));
64163 pOp->opcode = OP_Noop;
64164 if( addr==p->nOp-1 ) p->nOp--;
64169 ** If the last opcode is "op" and it is not a jump destination,
64170 ** then remove it. Return true if and only if an opcode was removed.
64172 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
64173 if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
64174 sqlite3VdbeChangeToNoop(p, p->nOp-1);
64175 return 1;
64176 }else{
64177 return 0;
64182 ** Change the value of the P4 operand for a specific instruction.
64183 ** This routine is useful when a large program is loaded from a
64184 ** static array using sqlite3VdbeAddOpList but we want to make a
64185 ** few minor changes to the program.
64187 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
64188 ** the string is made into memory obtained from sqlite3_malloc().
64189 ** A value of n==0 means copy bytes of zP4 up to and including the
64190 ** first null byte. If n>0 then copy n+1 bytes of zP4.
64192 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
64193 ** to a string or structure that is guaranteed to exist for the lifetime of
64194 ** the Vdbe. In these cases we can just copy the pointer.
64196 ** If addr<0 then change P4 on the most recently inserted instruction.
64198 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
64199 Op *pOp;
64200 sqlite3 *db;
64201 assert( p!=0 );
64202 db = p->db;
64203 assert( p->magic==VDBE_MAGIC_INIT );
64204 if( p->aOp==0 || db->mallocFailed ){
64205 if( n!=P4_VTAB ){
64206 freeP4(db, n, (void*)*(char**)&zP4);
64208 return;
64210 assert( p->nOp>0 );
64211 assert( addr<p->nOp );
64212 if( addr<0 ){
64213 addr = p->nOp - 1;
64215 pOp = &p->aOp[addr];
64216 assert( pOp->p4type==P4_NOTUSED
64217 || pOp->p4type==P4_INT32
64218 || pOp->p4type==P4_KEYINFO );
64219 freeP4(db, pOp->p4type, pOp->p4.p);
64220 pOp->p4.p = 0;
64221 if( n==P4_INT32 ){
64222 /* Note: this cast is safe, because the origin data point was an int
64223 ** that was cast to a (const char *). */
64224 pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
64225 pOp->p4type = P4_INT32;
64226 }else if( zP4==0 ){
64227 pOp->p4.p = 0;
64228 pOp->p4type = P4_NOTUSED;
64229 }else if( n==P4_KEYINFO ){
64230 pOp->p4.p = (void*)zP4;
64231 pOp->p4type = P4_KEYINFO;
64232 }else if( n==P4_VTAB ){
64233 pOp->p4.p = (void*)zP4;
64234 pOp->p4type = P4_VTAB;
64235 sqlite3VtabLock((VTable *)zP4);
64236 assert( ((VTable *)zP4)->db==p->db );
64237 }else if( n<0 ){
64238 pOp->p4.p = (void*)zP4;
64239 pOp->p4type = (signed char)n;
64240 }else{
64241 if( n==0 ) n = sqlite3Strlen30(zP4);
64242 pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
64243 pOp->p4type = P4_DYNAMIC;
64248 ** Set the P4 on the most recently added opcode to the KeyInfo for the
64249 ** index given.
64251 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
64252 Vdbe *v = pParse->pVdbe;
64253 assert( v!=0 );
64254 assert( pIdx!=0 );
64255 sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
64256 P4_KEYINFO);
64259 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
64261 ** Change the comment on the most recently coded instruction. Or
64262 ** insert a No-op and add the comment to that new instruction. This
64263 ** makes the code easier to read during debugging. None of this happens
64264 ** in a production build.
64266 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
64267 assert( p->nOp>0 || p->aOp==0 );
64268 assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
64269 if( p->nOp ){
64270 assert( p->aOp );
64271 sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
64272 p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
64275 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
64276 va_list ap;
64277 if( p ){
64278 va_start(ap, zFormat);
64279 vdbeVComment(p, zFormat, ap);
64280 va_end(ap);
64283 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
64284 va_list ap;
64285 if( p ){
64286 sqlite3VdbeAddOp0(p, OP_Noop);
64287 va_start(ap, zFormat);
64288 vdbeVComment(p, zFormat, ap);
64289 va_end(ap);
64292 #endif /* NDEBUG */
64294 #ifdef SQLITE_VDBE_COVERAGE
64296 ** Set the value if the iSrcLine field for the previously coded instruction.
64298 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
64299 sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
64301 #endif /* SQLITE_VDBE_COVERAGE */
64304 ** Return the opcode for a given address. If the address is -1, then
64305 ** return the most recently inserted opcode.
64307 ** If a memory allocation error has occurred prior to the calling of this
64308 ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
64309 ** is readable but not writable, though it is cast to a writable value.
64310 ** The return of a dummy opcode allows the call to continue functioning
64311 ** after an OOM fault without having to check to see if the return from
64312 ** this routine is a valid pointer. But because the dummy.opcode is 0,
64313 ** dummy will never be written to. This is verified by code inspection and
64314 ** by running with Valgrind.
64316 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
64317 /* C89 specifies that the constant "dummy" will be initialized to all
64318 ** zeros, which is correct. MSVC generates a warning, nevertheless. */
64319 static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
64320 assert( p->magic==VDBE_MAGIC_INIT );
64321 if( addr<0 ){
64322 addr = p->nOp - 1;
64324 assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
64325 if( p->db->mallocFailed ){
64326 return (VdbeOp*)&dummy;
64327 }else{
64328 return &p->aOp[addr];
64332 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
64334 ** Return an integer value for one of the parameters to the opcode pOp
64335 ** determined by character c.
64337 static int translateP(char c, const Op *pOp){
64338 if( c=='1' ) return pOp->p1;
64339 if( c=='2' ) return pOp->p2;
64340 if( c=='3' ) return pOp->p3;
64341 if( c=='4' ) return pOp->p4.i;
64342 return pOp->p5;
64346 ** Compute a string for the "comment" field of a VDBE opcode listing.
64348 ** The Synopsis: field in comments in the vdbe.c source file gets converted
64349 ** to an extra string that is appended to the sqlite3OpcodeName(). In the
64350 ** absence of other comments, this synopsis becomes the comment on the opcode.
64351 ** Some translation occurs:
64353 ** "PX" -> "r[X]"
64354 ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
64355 ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
64356 ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
64358 static int displayComment(
64359 const Op *pOp, /* The opcode to be commented */
64360 const char *zP4, /* Previously obtained value for P4 */
64361 char *zTemp, /* Write result here */
64362 int nTemp /* Space available in zTemp[] */
64364 const char *zOpName;
64365 const char *zSynopsis;
64366 int nOpName;
64367 int ii, jj;
64368 zOpName = sqlite3OpcodeName(pOp->opcode);
64369 nOpName = sqlite3Strlen30(zOpName);
64370 if( zOpName[nOpName+1] ){
64371 int seenCom = 0;
64372 char c;
64373 zSynopsis = zOpName += nOpName + 1;
64374 for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
64375 if( c=='P' ){
64376 c = zSynopsis[++ii];
64377 if( c=='4' ){
64378 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
64379 }else if( c=='X' ){
64380 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
64381 seenCom = 1;
64382 }else{
64383 int v1 = translateP(c, pOp);
64384 int v2;
64385 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
64386 if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
64387 ii += 3;
64388 jj += sqlite3Strlen30(zTemp+jj);
64389 v2 = translateP(zSynopsis[ii], pOp);
64390 if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
64391 ii += 2;
64392 v2++;
64394 if( v2>1 ){
64395 sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
64397 }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
64398 ii += 4;
64401 jj += sqlite3Strlen30(zTemp+jj);
64402 }else{
64403 zTemp[jj++] = c;
64406 if( !seenCom && jj<nTemp-5 && pOp->zComment ){
64407 sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
64408 jj += sqlite3Strlen30(zTemp+jj);
64410 if( jj<nTemp ) zTemp[jj] = 0;
64411 }else if( pOp->zComment ){
64412 sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
64413 jj = sqlite3Strlen30(zTemp);
64414 }else{
64415 zTemp[0] = 0;
64416 jj = 0;
64418 return jj;
64420 #endif /* SQLITE_DEBUG */
64423 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
64424 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
64426 ** Compute a string that describes the P4 parameter for an opcode.
64427 ** Use zTemp for any required temporary buffer space.
64429 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
64430 char *zP4 = zTemp;
64431 assert( nTemp>=20 );
64432 switch( pOp->p4type ){
64433 case P4_KEYINFO: {
64434 int i, j;
64435 KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
64436 assert( pKeyInfo->aSortOrder!=0 );
64437 sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
64438 i = sqlite3Strlen30(zTemp);
64439 for(j=0; j<pKeyInfo->nField; j++){
64440 CollSeq *pColl = pKeyInfo->aColl[j];
64441 const char *zColl = pColl ? pColl->zName : "nil";
64442 int n = sqlite3Strlen30(zColl);
64443 if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
64444 zColl = "B";
64445 n = 1;
64447 if( i+n>nTemp-6 ){
64448 memcpy(&zTemp[i],",...",4);
64449 break;
64451 zTemp[i++] = ',';
64452 if( pKeyInfo->aSortOrder[j] ){
64453 zTemp[i++] = '-';
64455 memcpy(&zTemp[i], zColl, n+1);
64456 i += n;
64458 zTemp[i++] = ')';
64459 zTemp[i] = 0;
64460 assert( i<nTemp );
64461 break;
64463 case P4_COLLSEQ: {
64464 CollSeq *pColl = pOp->p4.pColl;
64465 sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
64466 break;
64468 case P4_FUNCDEF: {
64469 FuncDef *pDef = pOp->p4.pFunc;
64470 sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
64471 break;
64473 case P4_INT64: {
64474 sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
64475 break;
64477 case P4_INT32: {
64478 sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
64479 break;
64481 case P4_REAL: {
64482 sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
64483 break;
64485 case P4_MEM: {
64486 Mem *pMem = pOp->p4.pMem;
64487 if( pMem->flags & MEM_Str ){
64488 zP4 = pMem->z;
64489 }else if( pMem->flags & MEM_Int ){
64490 sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
64491 }else if( pMem->flags & MEM_Real ){
64492 sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->u.r);
64493 }else if( pMem->flags & MEM_Null ){
64494 sqlite3_snprintf(nTemp, zTemp, "NULL");
64495 }else{
64496 assert( pMem->flags & MEM_Blob );
64497 zP4 = "(blob)";
64499 break;
64501 #ifndef SQLITE_OMIT_VIRTUALTABLE
64502 case P4_VTAB: {
64503 sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
64504 sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
64505 break;
64507 #endif
64508 case P4_INTARRAY: {
64509 sqlite3_snprintf(nTemp, zTemp, "intarray");
64510 break;
64512 case P4_SUBPROGRAM: {
64513 sqlite3_snprintf(nTemp, zTemp, "program");
64514 break;
64516 case P4_ADVANCE: {
64517 zTemp[0] = 0;
64518 break;
64520 default: {
64521 zP4 = pOp->p4.z;
64522 if( zP4==0 ){
64523 zP4 = zTemp;
64524 zTemp[0] = 0;
64528 assert( zP4!=0 );
64529 return zP4;
64531 #endif
64534 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
64536 ** The prepared statements need to know in advance the complete set of
64537 ** attached databases that will be use. A mask of these databases
64538 ** is maintained in p->btreeMask. The p->lockMask value is the subset of
64539 ** p->btreeMask of databases that will require a lock.
64541 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
64542 assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
64543 assert( i<(int)sizeof(p->btreeMask)*8 );
64544 DbMaskSet(p->btreeMask, i);
64545 if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
64546 DbMaskSet(p->lockMask, i);
64550 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
64552 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
64553 ** this routine obtains the mutex associated with each BtShared structure
64554 ** that may be accessed by the VM passed as an argument. In doing so it also
64555 ** sets the BtShared.db member of each of the BtShared structures, ensuring
64556 ** that the correct busy-handler callback is invoked if required.
64558 ** If SQLite is not threadsafe but does support shared-cache mode, then
64559 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
64560 ** of all of BtShared structures accessible via the database handle
64561 ** associated with the VM.
64563 ** If SQLite is not threadsafe and does not support shared-cache mode, this
64564 ** function is a no-op.
64566 ** The p->btreeMask field is a bitmask of all btrees that the prepared
64567 ** statement p will ever use. Let N be the number of bits in p->btreeMask
64568 ** corresponding to btrees that use shared cache. Then the runtime of
64569 ** this routine is N*N. But as N is rarely more than 1, this should not
64570 ** be a problem.
64572 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
64573 int i;
64574 sqlite3 *db;
64575 Db *aDb;
64576 int nDb;
64577 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
64578 db = p->db;
64579 aDb = db->aDb;
64580 nDb = db->nDb;
64581 for(i=0; i<nDb; i++){
64582 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
64583 sqlite3BtreeEnter(aDb[i].pBt);
64587 #endif
64589 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
64591 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
64593 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
64594 int i;
64595 sqlite3 *db;
64596 Db *aDb;
64597 int nDb;
64598 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
64599 db = p->db;
64600 aDb = db->aDb;
64601 nDb = db->nDb;
64602 for(i=0; i<nDb; i++){
64603 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
64604 sqlite3BtreeLeave(aDb[i].pBt);
64608 #endif
64610 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
64612 ** Print a single opcode. This routine is used for debugging only.
64614 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
64615 char *zP4;
64616 char zPtr[50];
64617 char zCom[100];
64618 static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
64619 if( pOut==0 ) pOut = stdout;
64620 zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
64621 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
64622 displayComment(pOp, zP4, zCom, sizeof(zCom));
64623 #else
64624 zCom[0] = 0;
64625 #endif
64626 /* NB: The sqlite3OpcodeName() function is implemented by code created
64627 ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
64628 ** information from the vdbe.c source text */
64629 fprintf(pOut, zFormat1, pc,
64630 sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
64631 zCom
64633 fflush(pOut);
64635 #endif
64638 ** Release an array of N Mem elements
64640 static void releaseMemArray(Mem *p, int N){
64641 if( p && N ){
64642 Mem *pEnd = &p[N];
64643 sqlite3 *db = p->db;
64644 u8 malloc_failed = db->mallocFailed;
64645 if( db->pnBytesFreed ){
64647 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
64648 }while( (++p)<pEnd );
64649 return;
64652 assert( (&p[1])==pEnd || p[0].db==p[1].db );
64653 assert( sqlite3VdbeCheckMemInvariants(p) );
64655 /* This block is really an inlined version of sqlite3VdbeMemRelease()
64656 ** that takes advantage of the fact that the memory cell value is
64657 ** being set to NULL after releasing any dynamic resources.
64659 ** The justification for duplicating code is that according to
64660 ** callgrind, this causes a certain test case to hit the CPU 4.7
64661 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
64662 ** sqlite3MemRelease() were called from here. With -O2, this jumps
64663 ** to 6.6 percent. The test case is inserting 1000 rows into a table
64664 ** with no indexes using a single prepared INSERT statement, bind()
64665 ** and reset(). Inserts are grouped into a transaction.
64667 testcase( p->flags & MEM_Agg );
64668 testcase( p->flags & MEM_Dyn );
64669 testcase( p->flags & MEM_Frame );
64670 testcase( p->flags & MEM_RowSet );
64671 if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
64672 sqlite3VdbeMemRelease(p);
64673 }else if( p->szMalloc ){
64674 sqlite3DbFree(db, p->zMalloc);
64675 p->szMalloc = 0;
64678 p->flags = MEM_Undefined;
64679 }while( (++p)<pEnd );
64680 db->mallocFailed = malloc_failed;
64685 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
64686 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
64688 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
64689 int i;
64690 Mem *aMem = VdbeFrameMem(p);
64691 VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
64692 for(i=0; i<p->nChildCsr; i++){
64693 sqlite3VdbeFreeCursor(p->v, apCsr[i]);
64695 releaseMemArray(aMem, p->nChildMem);
64696 sqlite3DbFree(p->v->db, p);
64699 #ifndef SQLITE_OMIT_EXPLAIN
64701 ** Give a listing of the program in the virtual machine.
64703 ** The interface is the same as sqlite3VdbeExec(). But instead of
64704 ** running the code, it invokes the callback once for each instruction.
64705 ** This feature is used to implement "EXPLAIN".
64707 ** When p->explain==1, each instruction is listed. When
64708 ** p->explain==2, only OP_Explain instructions are listed and these
64709 ** are shown in a different format. p->explain==2 is used to implement
64710 ** EXPLAIN QUERY PLAN.
64712 ** When p->explain==1, first the main program is listed, then each of
64713 ** the trigger subprograms are listed one by one.
64715 SQLITE_PRIVATE int sqlite3VdbeList(
64716 Vdbe *p /* The VDBE */
64718 int nRow; /* Stop when row count reaches this */
64719 int nSub = 0; /* Number of sub-vdbes seen so far */
64720 SubProgram **apSub = 0; /* Array of sub-vdbes */
64721 Mem *pSub = 0; /* Memory cell hold array of subprogs */
64722 sqlite3 *db = p->db; /* The database connection */
64723 int i; /* Loop counter */
64724 int rc = SQLITE_OK; /* Return code */
64725 Mem *pMem = &p->aMem[1]; /* First Mem of result set */
64727 assert( p->explain );
64728 assert( p->magic==VDBE_MAGIC_RUN );
64729 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
64731 /* Even though this opcode does not use dynamic strings for
64732 ** the result, result columns may become dynamic if the user calls
64733 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
64735 releaseMemArray(pMem, 8);
64736 p->pResultSet = 0;
64738 if( p->rc==SQLITE_NOMEM ){
64739 /* This happens if a malloc() inside a call to sqlite3_column_text() or
64740 ** sqlite3_column_text16() failed. */
64741 db->mallocFailed = 1;
64742 return SQLITE_ERROR;
64745 /* When the number of output rows reaches nRow, that means the
64746 ** listing has finished and sqlite3_step() should return SQLITE_DONE.
64747 ** nRow is the sum of the number of rows in the main program, plus
64748 ** the sum of the number of rows in all trigger subprograms encountered
64749 ** so far. The nRow value will increase as new trigger subprograms are
64750 ** encountered, but p->pc will eventually catch up to nRow.
64752 nRow = p->nOp;
64753 if( p->explain==1 ){
64754 /* The first 8 memory cells are used for the result set. So we will
64755 ** commandeer the 9th cell to use as storage for an array of pointers
64756 ** to trigger subprograms. The VDBE is guaranteed to have at least 9
64757 ** cells. */
64758 assert( p->nMem>9 );
64759 pSub = &p->aMem[9];
64760 if( pSub->flags&MEM_Blob ){
64761 /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
64762 ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
64763 nSub = pSub->n/sizeof(Vdbe*);
64764 apSub = (SubProgram **)pSub->z;
64766 for(i=0; i<nSub; i++){
64767 nRow += apSub[i]->nOp;
64772 i = p->pc++;
64773 }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
64774 if( i>=nRow ){
64775 p->rc = SQLITE_OK;
64776 rc = SQLITE_DONE;
64777 }else if( db->u1.isInterrupted ){
64778 p->rc = SQLITE_INTERRUPT;
64779 rc = SQLITE_ERROR;
64780 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
64781 }else{
64782 char *zP4;
64783 Op *pOp;
64784 if( i<p->nOp ){
64785 /* The output line number is small enough that we are still in the
64786 ** main program. */
64787 pOp = &p->aOp[i];
64788 }else{
64789 /* We are currently listing subprograms. Figure out which one and
64790 ** pick up the appropriate opcode. */
64791 int j;
64792 i -= p->nOp;
64793 for(j=0; i>=apSub[j]->nOp; j++){
64794 i -= apSub[j]->nOp;
64796 pOp = &apSub[j]->aOp[i];
64798 if( p->explain==1 ){
64799 pMem->flags = MEM_Int;
64800 pMem->u.i = i; /* Program counter */
64801 pMem++;
64803 pMem->flags = MEM_Static|MEM_Str|MEM_Term;
64804 pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
64805 assert( pMem->z!=0 );
64806 pMem->n = sqlite3Strlen30(pMem->z);
64807 pMem->enc = SQLITE_UTF8;
64808 pMem++;
64810 /* When an OP_Program opcode is encounter (the only opcode that has
64811 ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
64812 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
64813 ** has not already been seen.
64815 if( pOp->p4type==P4_SUBPROGRAM ){
64816 int nByte = (nSub+1)*sizeof(SubProgram*);
64817 int j;
64818 for(j=0; j<nSub; j++){
64819 if( apSub[j]==pOp->p4.pProgram ) break;
64821 if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
64822 apSub = (SubProgram **)pSub->z;
64823 apSub[nSub++] = pOp->p4.pProgram;
64824 pSub->flags |= MEM_Blob;
64825 pSub->n = nSub*sizeof(SubProgram*);
64830 pMem->flags = MEM_Int;
64831 pMem->u.i = pOp->p1; /* P1 */
64832 pMem++;
64834 pMem->flags = MEM_Int;
64835 pMem->u.i = pOp->p2; /* P2 */
64836 pMem++;
64838 pMem->flags = MEM_Int;
64839 pMem->u.i = pOp->p3; /* P3 */
64840 pMem++;
64842 if( sqlite3VdbeMemClearAndResize(pMem, 32) ){ /* P4 */
64843 assert( p->db->mallocFailed );
64844 return SQLITE_ERROR;
64846 pMem->flags = MEM_Str|MEM_Term;
64847 zP4 = displayP4(pOp, pMem->z, 32);
64848 if( zP4!=pMem->z ){
64849 sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
64850 }else{
64851 assert( pMem->z!=0 );
64852 pMem->n = sqlite3Strlen30(pMem->z);
64853 pMem->enc = SQLITE_UTF8;
64855 pMem++;
64857 if( p->explain==1 ){
64858 if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
64859 assert( p->db->mallocFailed );
64860 return SQLITE_ERROR;
64862 pMem->flags = MEM_Str|MEM_Term;
64863 pMem->n = 2;
64864 sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
64865 pMem->enc = SQLITE_UTF8;
64866 pMem++;
64868 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
64869 if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
64870 assert( p->db->mallocFailed );
64871 return SQLITE_ERROR;
64873 pMem->flags = MEM_Str|MEM_Term;
64874 pMem->n = displayComment(pOp, zP4, pMem->z, 500);
64875 pMem->enc = SQLITE_UTF8;
64876 #else
64877 pMem->flags = MEM_Null; /* Comment */
64878 #endif
64881 p->nResColumn = 8 - 4*(p->explain-1);
64882 p->pResultSet = &p->aMem[1];
64883 p->rc = SQLITE_OK;
64884 rc = SQLITE_ROW;
64886 return rc;
64888 #endif /* SQLITE_OMIT_EXPLAIN */
64890 #ifdef SQLITE_DEBUG
64892 ** Print the SQL that was used to generate a VDBE program.
64894 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
64895 const char *z = 0;
64896 if( p->zSql ){
64897 z = p->zSql;
64898 }else if( p->nOp>=1 ){
64899 const VdbeOp *pOp = &p->aOp[0];
64900 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
64901 z = pOp->p4.z;
64902 while( sqlite3Isspace(*z) ) z++;
64905 if( z ) printf("SQL: [%s]\n", z);
64907 #endif
64909 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
64911 ** Print an IOTRACE message showing SQL content.
64913 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
64914 int nOp = p->nOp;
64915 VdbeOp *pOp;
64916 if( sqlite3IoTrace==0 ) return;
64917 if( nOp<1 ) return;
64918 pOp = &p->aOp[0];
64919 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
64920 int i, j;
64921 char z[1000];
64922 sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
64923 for(i=0; sqlite3Isspace(z[i]); i++){}
64924 for(j=0; z[i]; i++){
64925 if( sqlite3Isspace(z[i]) ){
64926 if( z[i-1]!=' ' ){
64927 z[j++] = ' ';
64929 }else{
64930 z[j++] = z[i];
64933 z[j] = 0;
64934 sqlite3IoTrace("SQL %s\n", z);
64937 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
64940 ** Allocate space from a fixed size buffer and return a pointer to
64941 ** that space. If insufficient space is available, return NULL.
64943 ** The pBuf parameter is the initial value of a pointer which will
64944 ** receive the new memory. pBuf is normally NULL. If pBuf is not
64945 ** NULL, it means that memory space has already been allocated and that
64946 ** this routine should not allocate any new memory. When pBuf is not
64947 ** NULL simply return pBuf. Only allocate new memory space when pBuf
64948 ** is NULL.
64950 ** nByte is the number of bytes of space needed.
64952 ** *ppFrom points to available space and pEnd points to the end of the
64953 ** available space. When space is allocated, *ppFrom is advanced past
64954 ** the end of the allocated space.
64956 ** *pnByte is a counter of the number of bytes of space that have failed
64957 ** to allocate. If there is insufficient space in *ppFrom to satisfy the
64958 ** request, then increment *pnByte by the amount of the request.
64960 static void *allocSpace(
64961 void *pBuf, /* Where return pointer will be stored */
64962 int nByte, /* Number of bytes to allocate */
64963 u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
64964 u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
64965 int *pnByte /* If allocation cannot be made, increment *pnByte */
64967 assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
64968 if( pBuf ) return pBuf;
64969 nByte = ROUND8(nByte);
64970 if( &(*ppFrom)[nByte] <= pEnd ){
64971 pBuf = (void*)*ppFrom;
64972 *ppFrom += nByte;
64973 }else{
64974 *pnByte += nByte;
64976 return pBuf;
64980 ** Rewind the VDBE back to the beginning in preparation for
64981 ** running it.
64983 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
64984 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
64985 int i;
64986 #endif
64987 assert( p!=0 );
64988 assert( p->magic==VDBE_MAGIC_INIT );
64990 /* There should be at least one opcode.
64992 assert( p->nOp>0 );
64994 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
64995 p->magic = VDBE_MAGIC_RUN;
64997 #ifdef SQLITE_DEBUG
64998 for(i=1; i<p->nMem; i++){
64999 assert( p->aMem[i].db==p->db );
65001 #endif
65002 p->pc = -1;
65003 p->rc = SQLITE_OK;
65004 p->errorAction = OE_Abort;
65005 p->magic = VDBE_MAGIC_RUN;
65006 p->nChange = 0;
65007 p->cacheCtr = 1;
65008 p->minWriteFileFormat = 255;
65009 p->iStatement = 0;
65010 p->nFkConstraint = 0;
65011 #ifdef VDBE_PROFILE
65012 for(i=0; i<p->nOp; i++){
65013 p->aOp[i].cnt = 0;
65014 p->aOp[i].cycles = 0;
65016 #endif
65020 ** Prepare a virtual machine for execution for the first time after
65021 ** creating the virtual machine. This involves things such
65022 ** as allocating registers and initializing the program counter.
65023 ** After the VDBE has be prepped, it can be executed by one or more
65024 ** calls to sqlite3VdbeExec().
65026 ** This function may be called exactly once on each virtual machine.
65027 ** After this routine is called the VM has been "packaged" and is ready
65028 ** to run. After this routine is called, further calls to
65029 ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
65030 ** the Vdbe from the Parse object that helped generate it so that the
65031 ** the Vdbe becomes an independent entity and the Parse object can be
65032 ** destroyed.
65034 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
65035 ** to its initial state after it has been run.
65037 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
65038 Vdbe *p, /* The VDBE */
65039 Parse *pParse /* Parsing context */
65041 sqlite3 *db; /* The database connection */
65042 int nVar; /* Number of parameters */
65043 int nMem; /* Number of VM memory registers */
65044 int nCursor; /* Number of cursors required */
65045 int nArg; /* Number of arguments in subprograms */
65046 int nOnce; /* Number of OP_Once instructions */
65047 int n; /* Loop counter */
65048 u8 *zCsr; /* Memory available for allocation */
65049 u8 *zEnd; /* First byte past allocated memory */
65050 int nByte; /* How much extra memory is needed */
65052 assert( p!=0 );
65053 assert( p->nOp>0 );
65054 assert( pParse!=0 );
65055 assert( p->magic==VDBE_MAGIC_INIT );
65056 assert( pParse==p->pParse );
65057 db = p->db;
65058 assert( db->mallocFailed==0 );
65059 nVar = pParse->nVar;
65060 nMem = pParse->nMem;
65061 nCursor = pParse->nTab;
65062 nArg = pParse->nMaxArg;
65063 nOnce = pParse->nOnce;
65064 if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
65066 /* For each cursor required, also allocate a memory cell. Memory
65067 ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
65068 ** the vdbe program. Instead they are used to allocate space for
65069 ** VdbeCursor/BtCursor structures. The blob of memory associated with
65070 ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
65071 ** stores the blob of memory associated with cursor 1, etc.
65073 ** See also: allocateCursor().
65075 nMem += nCursor;
65077 /* Allocate space for memory registers, SQL variables, VDBE cursors and
65078 ** an array to marshal SQL function arguments in.
65080 zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
65081 zEnd = (u8*)&p->aOp[pParse->nOpAlloc]; /* First byte past end of zCsr[] */
65083 resolveP2Values(p, &nArg);
65084 p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
65085 if( pParse->explain && nMem<10 ){
65086 nMem = 10;
65088 memset(zCsr, 0, zEnd-zCsr);
65089 zCsr += (zCsr - (u8*)0)&7;
65090 assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
65091 p->expired = 0;
65093 /* Memory for registers, parameters, cursor, etc, is allocated in two
65094 ** passes. On the first pass, we try to reuse unused space at the
65095 ** end of the opcode array. If we are unable to satisfy all memory
65096 ** requirements by reusing the opcode array tail, then the second
65097 ** pass will fill in the rest using a fresh allocation.
65099 ** This two-pass approach that reuses as much memory as possible from
65100 ** the leftover space at the end of the opcode array can significantly
65101 ** reduce the amount of memory held by a prepared statement.
65103 do {
65104 nByte = 0;
65105 p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
65106 p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
65107 p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
65108 p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
65109 p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
65110 &zCsr, zEnd, &nByte);
65111 p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
65112 if( nByte ){
65113 p->pFree = sqlite3DbMallocZero(db, nByte);
65115 zCsr = p->pFree;
65116 zEnd = &zCsr[nByte];
65117 }while( nByte && !db->mallocFailed );
65119 p->nCursor = nCursor;
65120 p->nOnceFlag = nOnce;
65121 if( p->aVar ){
65122 p->nVar = (ynVar)nVar;
65123 for(n=0; n<nVar; n++){
65124 p->aVar[n].flags = MEM_Null;
65125 p->aVar[n].db = db;
65128 if( p->azVar ){
65129 p->nzVar = pParse->nzVar;
65130 memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
65131 memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
65133 if( p->aMem ){
65134 p->aMem--; /* aMem[] goes from 1..nMem */
65135 p->nMem = nMem; /* not from 0..nMem-1 */
65136 for(n=1; n<=nMem; n++){
65137 p->aMem[n].flags = MEM_Undefined;
65138 p->aMem[n].db = db;
65141 p->explain = pParse->explain;
65142 sqlite3VdbeRewind(p);
65146 ** Close a VDBE cursor and release all the resources that cursor
65147 ** happens to hold.
65149 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
65150 if( pCx==0 ){
65151 return;
65153 sqlite3VdbeSorterClose(p->db, pCx);
65154 if( pCx->pBt ){
65155 sqlite3BtreeClose(pCx->pBt);
65156 /* The pCx->pCursor will be close automatically, if it exists, by
65157 ** the call above. */
65158 }else if( pCx->pCursor ){
65159 sqlite3BtreeCloseCursor(pCx->pCursor);
65161 #ifndef SQLITE_OMIT_VIRTUALTABLE
65162 else if( pCx->pVtabCursor ){
65163 sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
65164 const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
65165 p->inVtabMethod = 1;
65166 pModule->xClose(pVtabCursor);
65167 p->inVtabMethod = 0;
65169 #endif
65173 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
65174 ** is used, for example, when a trigger sub-program is halted to restore
65175 ** control to the main program.
65177 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
65178 Vdbe *v = pFrame->v;
65179 v->aOnceFlag = pFrame->aOnceFlag;
65180 v->nOnceFlag = pFrame->nOnceFlag;
65181 v->aOp = pFrame->aOp;
65182 v->nOp = pFrame->nOp;
65183 v->aMem = pFrame->aMem;
65184 v->nMem = pFrame->nMem;
65185 v->apCsr = pFrame->apCsr;
65186 v->nCursor = pFrame->nCursor;
65187 v->db->lastRowid = pFrame->lastRowid;
65188 v->nChange = pFrame->nChange;
65189 return pFrame->pc;
65193 ** Close all cursors.
65195 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
65196 ** cell array. This is necessary as the memory cell array may contain
65197 ** pointers to VdbeFrame objects, which may in turn contain pointers to
65198 ** open cursors.
65200 static void closeAllCursors(Vdbe *p){
65201 if( p->pFrame ){
65202 VdbeFrame *pFrame;
65203 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
65204 sqlite3VdbeFrameRestore(pFrame);
65205 p->pFrame = 0;
65206 p->nFrame = 0;
65208 assert( p->nFrame==0 );
65210 if( p->apCsr ){
65211 int i;
65212 for(i=0; i<p->nCursor; i++){
65213 VdbeCursor *pC = p->apCsr[i];
65214 if( pC ){
65215 sqlite3VdbeFreeCursor(p, pC);
65216 p->apCsr[i] = 0;
65220 if( p->aMem ){
65221 releaseMemArray(&p->aMem[1], p->nMem);
65223 while( p->pDelFrame ){
65224 VdbeFrame *pDel = p->pDelFrame;
65225 p->pDelFrame = pDel->pParent;
65226 sqlite3VdbeFrameDelete(pDel);
65229 /* Delete any auxdata allocations made by the VM */
65230 if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p, -1, 0);
65231 assert( p->pAuxData==0 );
65235 ** Clean up the VM after a single run.
65237 static void Cleanup(Vdbe *p){
65238 sqlite3 *db = p->db;
65240 #ifdef SQLITE_DEBUG
65241 /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
65242 ** Vdbe.aMem[] arrays have already been cleaned up. */
65243 int i;
65244 if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
65245 if( p->aMem ){
65246 for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
65248 #endif
65250 sqlite3DbFree(db, p->zErrMsg);
65251 p->zErrMsg = 0;
65252 p->pResultSet = 0;
65256 ** Set the number of result columns that will be returned by this SQL
65257 ** statement. This is now set at compile time, rather than during
65258 ** execution of the vdbe program so that sqlite3_column_count() can
65259 ** be called on an SQL statement before sqlite3_step().
65261 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
65262 Mem *pColName;
65263 int n;
65264 sqlite3 *db = p->db;
65266 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
65267 sqlite3DbFree(db, p->aColName);
65268 n = nResColumn*COLNAME_N;
65269 p->nResColumn = (u16)nResColumn;
65270 p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
65271 if( p->aColName==0 ) return;
65272 while( n-- > 0 ){
65273 pColName->flags = MEM_Null;
65274 pColName->db = p->db;
65275 pColName++;
65280 ** Set the name of the idx'th column to be returned by the SQL statement.
65281 ** zName must be a pointer to a nul terminated string.
65283 ** This call must be made after a call to sqlite3VdbeSetNumCols().
65285 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
65286 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
65287 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
65289 SQLITE_PRIVATE int sqlite3VdbeSetColName(
65290 Vdbe *p, /* Vdbe being configured */
65291 int idx, /* Index of column zName applies to */
65292 int var, /* One of the COLNAME_* constants */
65293 const char *zName, /* Pointer to buffer containing name */
65294 void (*xDel)(void*) /* Memory management strategy for zName */
65296 int rc;
65297 Mem *pColName;
65298 assert( idx<p->nResColumn );
65299 assert( var<COLNAME_N );
65300 if( p->db->mallocFailed ){
65301 assert( !zName || xDel!=SQLITE_DYNAMIC );
65302 return SQLITE_NOMEM;
65304 assert( p->aColName!=0 );
65305 pColName = &(p->aColName[idx+var*p->nResColumn]);
65306 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
65307 assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
65308 return rc;
65312 ** A read or write transaction may or may not be active on database handle
65313 ** db. If a transaction is active, commit it. If there is a
65314 ** write-transaction spanning more than one database file, this routine
65315 ** takes care of the master journal trickery.
65317 static int vdbeCommit(sqlite3 *db, Vdbe *p){
65318 int i;
65319 int nTrans = 0; /* Number of databases with an active write-transaction */
65320 int rc = SQLITE_OK;
65321 int needXcommit = 0;
65323 #ifdef SQLITE_OMIT_VIRTUALTABLE
65324 /* With this option, sqlite3VtabSync() is defined to be simply
65325 ** SQLITE_OK so p is not used.
65327 UNUSED_PARAMETER(p);
65328 #endif
65330 /* Before doing anything else, call the xSync() callback for any
65331 ** virtual module tables written in this transaction. This has to
65332 ** be done before determining whether a master journal file is
65333 ** required, as an xSync() callback may add an attached database
65334 ** to the transaction.
65336 rc = sqlite3VtabSync(db, p);
65338 /* This loop determines (a) if the commit hook should be invoked and
65339 ** (b) how many database files have open write transactions, not
65340 ** including the temp database. (b) is important because if more than
65341 ** one database file has an open write transaction, a master journal
65342 ** file is required for an atomic commit.
65344 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
65345 Btree *pBt = db->aDb[i].pBt;
65346 if( sqlite3BtreeIsInTrans(pBt) ){
65347 needXcommit = 1;
65348 if( i!=1 ) nTrans++;
65349 sqlite3BtreeEnter(pBt);
65350 rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
65351 sqlite3BtreeLeave(pBt);
65354 if( rc!=SQLITE_OK ){
65355 return rc;
65358 /* If there are any write-transactions at all, invoke the commit hook */
65359 if( needXcommit && db->xCommitCallback ){
65360 rc = db->xCommitCallback(db->pCommitArg);
65361 if( rc ){
65362 return SQLITE_CONSTRAINT_COMMITHOOK;
65366 /* The simple case - no more than one database file (not counting the
65367 ** TEMP database) has a transaction active. There is no need for the
65368 ** master-journal.
65370 ** If the return value of sqlite3BtreeGetFilename() is a zero length
65371 ** string, it means the main database is :memory: or a temp file. In
65372 ** that case we do not support atomic multi-file commits, so use the
65373 ** simple case then too.
65375 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
65376 || nTrans<=1
65378 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
65379 Btree *pBt = db->aDb[i].pBt;
65380 if( pBt ){
65381 rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
65385 /* Do the commit only if all databases successfully complete phase 1.
65386 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
65387 ** IO error while deleting or truncating a journal file. It is unlikely,
65388 ** but could happen. In this case abandon processing and return the error.
65390 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
65391 Btree *pBt = db->aDb[i].pBt;
65392 if( pBt ){
65393 rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
65396 if( rc==SQLITE_OK ){
65397 sqlite3VtabCommit(db);
65401 /* The complex case - There is a multi-file write-transaction active.
65402 ** This requires a master journal file to ensure the transaction is
65403 ** committed atomically.
65405 #ifndef SQLITE_OMIT_DISKIO
65406 else{
65407 sqlite3_vfs *pVfs = db->pVfs;
65408 int needSync = 0;
65409 char *zMaster = 0; /* File-name for the master journal */
65410 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
65411 sqlite3_file *pMaster = 0;
65412 i64 offset = 0;
65413 int res;
65414 int retryCount = 0;
65415 int nMainFile;
65417 /* Select a master journal file name */
65418 nMainFile = sqlite3Strlen30(zMainFile);
65419 zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
65420 if( zMaster==0 ) return SQLITE_NOMEM;
65421 do {
65422 u32 iRandom;
65423 if( retryCount ){
65424 if( retryCount>100 ){
65425 sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
65426 sqlite3OsDelete(pVfs, zMaster, 0);
65427 break;
65428 }else if( retryCount==1 ){
65429 sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
65432 retryCount++;
65433 sqlite3_randomness(sizeof(iRandom), &iRandom);
65434 sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
65435 (iRandom>>8)&0xffffff, iRandom&0xff);
65436 /* The antipenultimate character of the master journal name must
65437 ** be "9" to avoid name collisions when using 8+3 filenames. */
65438 assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
65439 sqlite3FileSuffix3(zMainFile, zMaster);
65440 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
65441 }while( rc==SQLITE_OK && res );
65442 if( rc==SQLITE_OK ){
65443 /* Open the master journal. */
65444 rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
65445 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
65446 SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
65449 if( rc!=SQLITE_OK ){
65450 sqlite3DbFree(db, zMaster);
65451 return rc;
65454 /* Write the name of each database file in the transaction into the new
65455 ** master journal file. If an error occurs at this point close
65456 ** and delete the master journal file. All the individual journal files
65457 ** still have 'null' as the master journal pointer, so they will roll
65458 ** back independently if a failure occurs.
65460 for(i=0; i<db->nDb; i++){
65461 Btree *pBt = db->aDb[i].pBt;
65462 if( sqlite3BtreeIsInTrans(pBt) ){
65463 char const *zFile = sqlite3BtreeGetJournalname(pBt);
65464 if( zFile==0 ){
65465 continue; /* Ignore TEMP and :memory: databases */
65467 assert( zFile[0]!=0 );
65468 if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
65469 needSync = 1;
65471 rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
65472 offset += sqlite3Strlen30(zFile)+1;
65473 if( rc!=SQLITE_OK ){
65474 sqlite3OsCloseFree(pMaster);
65475 sqlite3OsDelete(pVfs, zMaster, 0);
65476 sqlite3DbFree(db, zMaster);
65477 return rc;
65482 /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
65483 ** flag is set this is not required.
65485 if( needSync
65486 && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
65487 && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
65489 sqlite3OsCloseFree(pMaster);
65490 sqlite3OsDelete(pVfs, zMaster, 0);
65491 sqlite3DbFree(db, zMaster);
65492 return rc;
65495 /* Sync all the db files involved in the transaction. The same call
65496 ** sets the master journal pointer in each individual journal. If
65497 ** an error occurs here, do not delete the master journal file.
65499 ** If the error occurs during the first call to
65500 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
65501 ** master journal file will be orphaned. But we cannot delete it,
65502 ** in case the master journal file name was written into the journal
65503 ** file before the failure occurred.
65505 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
65506 Btree *pBt = db->aDb[i].pBt;
65507 if( pBt ){
65508 rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
65511 sqlite3OsCloseFree(pMaster);
65512 assert( rc!=SQLITE_BUSY );
65513 if( rc!=SQLITE_OK ){
65514 sqlite3DbFree(db, zMaster);
65515 return rc;
65518 /* Delete the master journal file. This commits the transaction. After
65519 ** doing this the directory is synced again before any individual
65520 ** transaction files are deleted.
65522 rc = sqlite3OsDelete(pVfs, zMaster, 1);
65523 sqlite3DbFree(db, zMaster);
65524 zMaster = 0;
65525 if( rc ){
65526 return rc;
65529 /* All files and directories have already been synced, so the following
65530 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
65531 ** deleting or truncating journals. If something goes wrong while
65532 ** this is happening we don't really care. The integrity of the
65533 ** transaction is already guaranteed, but some stray 'cold' journals
65534 ** may be lying around. Returning an error code won't help matters.
65536 disable_simulated_io_errors();
65537 sqlite3BeginBenignMalloc();
65538 for(i=0; i<db->nDb; i++){
65539 Btree *pBt = db->aDb[i].pBt;
65540 if( pBt ){
65541 sqlite3BtreeCommitPhaseTwo(pBt, 1);
65544 sqlite3EndBenignMalloc();
65545 enable_simulated_io_errors();
65547 sqlite3VtabCommit(db);
65549 #endif
65551 return rc;
65555 ** This routine checks that the sqlite3.nVdbeActive count variable
65556 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
65557 ** currently active. An assertion fails if the two counts do not match.
65558 ** This is an internal self-check only - it is not an essential processing
65559 ** step.
65561 ** This is a no-op if NDEBUG is defined.
65563 #ifndef NDEBUG
65564 static void checkActiveVdbeCnt(sqlite3 *db){
65565 Vdbe *p;
65566 int cnt = 0;
65567 int nWrite = 0;
65568 int nRead = 0;
65569 p = db->pVdbe;
65570 while( p ){
65571 if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
65572 cnt++;
65573 if( p->readOnly==0 ) nWrite++;
65574 if( p->bIsReader ) nRead++;
65576 p = p->pNext;
65578 assert( cnt==db->nVdbeActive );
65579 assert( nWrite==db->nVdbeWrite );
65580 assert( nRead==db->nVdbeRead );
65582 #else
65583 #define checkActiveVdbeCnt(x)
65584 #endif
65587 ** If the Vdbe passed as the first argument opened a statement-transaction,
65588 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
65589 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
65590 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
65591 ** statement transaction is committed.
65593 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
65594 ** Otherwise SQLITE_OK.
65596 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
65597 sqlite3 *const db = p->db;
65598 int rc = SQLITE_OK;
65600 /* If p->iStatement is greater than zero, then this Vdbe opened a
65601 ** statement transaction that should be closed here. The only exception
65602 ** is that an IO error may have occurred, causing an emergency rollback.
65603 ** In this case (db->nStatement==0), and there is nothing to do.
65605 if( db->nStatement && p->iStatement ){
65606 int i;
65607 const int iSavepoint = p->iStatement-1;
65609 assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
65610 assert( db->nStatement>0 );
65611 assert( p->iStatement==(db->nStatement+db->nSavepoint) );
65613 for(i=0; i<db->nDb; i++){
65614 int rc2 = SQLITE_OK;
65615 Btree *pBt = db->aDb[i].pBt;
65616 if( pBt ){
65617 if( eOp==SAVEPOINT_ROLLBACK ){
65618 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
65620 if( rc2==SQLITE_OK ){
65621 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
65623 if( rc==SQLITE_OK ){
65624 rc = rc2;
65628 db->nStatement--;
65629 p->iStatement = 0;
65631 if( rc==SQLITE_OK ){
65632 if( eOp==SAVEPOINT_ROLLBACK ){
65633 rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
65635 if( rc==SQLITE_OK ){
65636 rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
65640 /* If the statement transaction is being rolled back, also restore the
65641 ** database handles deferred constraint counter to the value it had when
65642 ** the statement transaction was opened. */
65643 if( eOp==SAVEPOINT_ROLLBACK ){
65644 db->nDeferredCons = p->nStmtDefCons;
65645 db->nDeferredImmCons = p->nStmtDefImmCons;
65648 return rc;
65652 ** This function is called when a transaction opened by the database
65653 ** handle associated with the VM passed as an argument is about to be
65654 ** committed. If there are outstanding deferred foreign key constraint
65655 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
65657 ** If there are outstanding FK violations and this function returns
65658 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
65659 ** and write an error message to it. Then return SQLITE_ERROR.
65661 #ifndef SQLITE_OMIT_FOREIGN_KEY
65662 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
65663 sqlite3 *db = p->db;
65664 if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
65665 || (!deferred && p->nFkConstraint>0)
65667 p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
65668 p->errorAction = OE_Abort;
65669 sqlite3SetString(&p->zErrMsg, db, "FOREIGN KEY constraint failed");
65670 return SQLITE_ERROR;
65672 return SQLITE_OK;
65674 #endif
65677 ** This routine is called the when a VDBE tries to halt. If the VDBE
65678 ** has made changes and is in autocommit mode, then commit those
65679 ** changes. If a rollback is needed, then do the rollback.
65681 ** This routine is the only way to move the state of a VM from
65682 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
65683 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
65685 ** Return an error code. If the commit could not complete because of
65686 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
65687 ** means the close did not happen and needs to be repeated.
65689 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
65690 int rc; /* Used to store transient return codes */
65691 sqlite3 *db = p->db;
65693 /* This function contains the logic that determines if a statement or
65694 ** transaction will be committed or rolled back as a result of the
65695 ** execution of this virtual machine.
65697 ** If any of the following errors occur:
65699 ** SQLITE_NOMEM
65700 ** SQLITE_IOERR
65701 ** SQLITE_FULL
65702 ** SQLITE_INTERRUPT
65704 ** Then the internal cache might have been left in an inconsistent
65705 ** state. We need to rollback the statement transaction, if there is
65706 ** one, or the complete transaction if there is no statement transaction.
65709 if( p->db->mallocFailed ){
65710 p->rc = SQLITE_NOMEM;
65712 if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
65713 closeAllCursors(p);
65714 if( p->magic!=VDBE_MAGIC_RUN ){
65715 return SQLITE_OK;
65717 checkActiveVdbeCnt(db);
65719 /* No commit or rollback needed if the program never started or if the
65720 ** SQL statement does not read or write a database file. */
65721 if( p->pc>=0 && p->bIsReader ){
65722 int mrc; /* Primary error code from p->rc */
65723 int eStatementOp = 0;
65724 int isSpecialError; /* Set to true if a 'special' error */
65726 /* Lock all btrees used by the statement */
65727 sqlite3VdbeEnter(p);
65729 /* Check for one of the special errors */
65730 mrc = p->rc & 0xff;
65731 isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
65732 || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
65733 if( isSpecialError ){
65734 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
65735 ** no rollback is necessary. Otherwise, at least a savepoint
65736 ** transaction must be rolled back to restore the database to a
65737 ** consistent state.
65739 ** Even if the statement is read-only, it is important to perform
65740 ** a statement or transaction rollback operation. If the error
65741 ** occurred while writing to the journal, sub-journal or database
65742 ** file as part of an effort to free up cache space (see function
65743 ** pagerStress() in pager.c), the rollback is required to restore
65744 ** the pager to a consistent state.
65746 if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
65747 if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
65748 eStatementOp = SAVEPOINT_ROLLBACK;
65749 }else{
65750 /* We are forced to roll back the active transaction. Before doing
65751 ** so, abort any other statements this handle currently has active.
65753 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
65754 sqlite3CloseSavepoints(db);
65755 db->autoCommit = 1;
65760 /* Check for immediate foreign key violations. */
65761 if( p->rc==SQLITE_OK ){
65762 sqlite3VdbeCheckFk(p, 0);
65765 /* If the auto-commit flag is set and this is the only active writer
65766 ** VM, then we do either a commit or rollback of the current transaction.
65768 ** Note: This block also runs if one of the special errors handled
65769 ** above has occurred.
65771 if( !sqlite3VtabInSync(db)
65772 && db->autoCommit
65773 && db->nVdbeWrite==(p->readOnly==0)
65775 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
65776 rc = sqlite3VdbeCheckFk(p, 1);
65777 if( rc!=SQLITE_OK ){
65778 if( NEVER(p->readOnly) ){
65779 sqlite3VdbeLeave(p);
65780 return SQLITE_ERROR;
65782 rc = SQLITE_CONSTRAINT_FOREIGNKEY;
65783 }else{
65784 /* The auto-commit flag is true, the vdbe program was successful
65785 ** or hit an 'OR FAIL' constraint and there are no deferred foreign
65786 ** key constraints to hold up the transaction. This means a commit
65787 ** is required. */
65788 rc = vdbeCommit(db, p);
65790 if( rc==SQLITE_BUSY && p->readOnly ){
65791 sqlite3VdbeLeave(p);
65792 return SQLITE_BUSY;
65793 }else if( rc!=SQLITE_OK ){
65794 p->rc = rc;
65795 sqlite3RollbackAll(db, SQLITE_OK);
65796 }else{
65797 db->nDeferredCons = 0;
65798 db->nDeferredImmCons = 0;
65799 db->flags &= ~SQLITE_DeferFKs;
65800 sqlite3CommitInternalChanges(db);
65802 }else{
65803 sqlite3RollbackAll(db, SQLITE_OK);
65805 db->nStatement = 0;
65806 }else if( eStatementOp==0 ){
65807 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
65808 eStatementOp = SAVEPOINT_RELEASE;
65809 }else if( p->errorAction==OE_Abort ){
65810 eStatementOp = SAVEPOINT_ROLLBACK;
65811 }else{
65812 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
65813 sqlite3CloseSavepoints(db);
65814 db->autoCommit = 1;
65818 /* If eStatementOp is non-zero, then a statement transaction needs to
65819 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
65820 ** do so. If this operation returns an error, and the current statement
65821 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
65822 ** current statement error code.
65824 if( eStatementOp ){
65825 rc = sqlite3VdbeCloseStatement(p, eStatementOp);
65826 if( rc ){
65827 if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
65828 p->rc = rc;
65829 sqlite3DbFree(db, p->zErrMsg);
65830 p->zErrMsg = 0;
65832 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
65833 sqlite3CloseSavepoints(db);
65834 db->autoCommit = 1;
65838 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
65839 ** has been rolled back, update the database connection change-counter.
65841 if( p->changeCntOn ){
65842 if( eStatementOp!=SAVEPOINT_ROLLBACK ){
65843 sqlite3VdbeSetChanges(db, p->nChange);
65844 }else{
65845 sqlite3VdbeSetChanges(db, 0);
65847 p->nChange = 0;
65850 /* Release the locks */
65851 sqlite3VdbeLeave(p);
65854 /* We have successfully halted and closed the VM. Record this fact. */
65855 if( p->pc>=0 ){
65856 db->nVdbeActive--;
65857 if( !p->readOnly ) db->nVdbeWrite--;
65858 if( p->bIsReader ) db->nVdbeRead--;
65859 assert( db->nVdbeActive>=db->nVdbeRead );
65860 assert( db->nVdbeRead>=db->nVdbeWrite );
65861 assert( db->nVdbeWrite>=0 );
65863 p->magic = VDBE_MAGIC_HALT;
65864 checkActiveVdbeCnt(db);
65865 if( p->db->mallocFailed ){
65866 p->rc = SQLITE_NOMEM;
65869 /* If the auto-commit flag is set to true, then any locks that were held
65870 ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
65871 ** to invoke any required unlock-notify callbacks.
65873 if( db->autoCommit ){
65874 sqlite3ConnectionUnlocked(db);
65877 assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
65878 return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
65883 ** Each VDBE holds the result of the most recent sqlite3_step() call
65884 ** in p->rc. This routine sets that result back to SQLITE_OK.
65886 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
65887 p->rc = SQLITE_OK;
65891 ** Copy the error code and error message belonging to the VDBE passed
65892 ** as the first argument to its database handle (so that they will be
65893 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
65895 ** This function does not clear the VDBE error code or message, just
65896 ** copies them to the database handle.
65898 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
65899 sqlite3 *db = p->db;
65900 int rc = p->rc;
65901 if( p->zErrMsg ){
65902 u8 mallocFailed = db->mallocFailed;
65903 sqlite3BeginBenignMalloc();
65904 if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
65905 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
65906 sqlite3EndBenignMalloc();
65907 db->mallocFailed = mallocFailed;
65908 db->errCode = rc;
65909 }else{
65910 sqlite3Error(db, rc);
65912 return rc;
65915 #ifdef SQLITE_ENABLE_SQLLOG
65917 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
65918 ** invoke it.
65920 static void vdbeInvokeSqllog(Vdbe *v){
65921 if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
65922 char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
65923 assert( v->db->init.busy==0 );
65924 if( zExpanded ){
65925 sqlite3GlobalConfig.xSqllog(
65926 sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
65928 sqlite3DbFree(v->db, zExpanded);
65932 #else
65933 # define vdbeInvokeSqllog(x)
65934 #endif
65937 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
65938 ** Write any error messages into *pzErrMsg. Return the result code.
65940 ** After this routine is run, the VDBE should be ready to be executed
65941 ** again.
65943 ** To look at it another way, this routine resets the state of the
65944 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
65945 ** VDBE_MAGIC_INIT.
65947 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
65948 sqlite3 *db;
65949 db = p->db;
65951 /* If the VM did not run to completion or if it encountered an
65952 ** error, then it might not have been halted properly. So halt
65953 ** it now.
65955 sqlite3VdbeHalt(p);
65957 /* If the VDBE has be run even partially, then transfer the error code
65958 ** and error message from the VDBE into the main database structure. But
65959 ** if the VDBE has just been set to run but has not actually executed any
65960 ** instructions yet, leave the main database error information unchanged.
65962 if( p->pc>=0 ){
65963 vdbeInvokeSqllog(p);
65964 sqlite3VdbeTransferError(p);
65965 sqlite3DbFree(db, p->zErrMsg);
65966 p->zErrMsg = 0;
65967 if( p->runOnlyOnce ) p->expired = 1;
65968 }else if( p->rc && p->expired ){
65969 /* The expired flag was set on the VDBE before the first call
65970 ** to sqlite3_step(). For consistency (since sqlite3_step() was
65971 ** called), set the database error in this case as well.
65973 sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
65974 sqlite3DbFree(db, p->zErrMsg);
65975 p->zErrMsg = 0;
65978 /* Reclaim all memory used by the VDBE
65980 Cleanup(p);
65982 /* Save profiling information from this VDBE run.
65984 #ifdef VDBE_PROFILE
65986 FILE *out = fopen("vdbe_profile.out", "a");
65987 if( out ){
65988 int i;
65989 fprintf(out, "---- ");
65990 for(i=0; i<p->nOp; i++){
65991 fprintf(out, "%02x", p->aOp[i].opcode);
65993 fprintf(out, "\n");
65994 if( p->zSql ){
65995 char c, pc = 0;
65996 fprintf(out, "-- ");
65997 for(i=0; (c = p->zSql[i])!=0; i++){
65998 if( pc=='\n' ) fprintf(out, "-- ");
65999 putc(c, out);
66000 pc = c;
66002 if( pc!='\n' ) fprintf(out, "\n");
66004 for(i=0; i<p->nOp; i++){
66005 char zHdr[100];
66006 sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
66007 p->aOp[i].cnt,
66008 p->aOp[i].cycles,
66009 p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
66011 fprintf(out, "%s", zHdr);
66012 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
66014 fclose(out);
66017 #endif
66018 p->iCurrentTime = 0;
66019 p->magic = VDBE_MAGIC_INIT;
66020 return p->rc & db->errMask;
66024 ** Clean up and delete a VDBE after execution. Return an integer which is
66025 ** the result code. Write any error message text into *pzErrMsg.
66027 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
66028 int rc = SQLITE_OK;
66029 if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
66030 rc = sqlite3VdbeReset(p);
66031 assert( (rc & p->db->errMask)==rc );
66033 sqlite3VdbeDelete(p);
66034 return rc;
66038 ** If parameter iOp is less than zero, then invoke the destructor for
66039 ** all auxiliary data pointers currently cached by the VM passed as
66040 ** the first argument.
66042 ** Or, if iOp is greater than or equal to zero, then the destructor is
66043 ** only invoked for those auxiliary data pointers created by the user
66044 ** function invoked by the OP_Function opcode at instruction iOp of
66045 ** VM pVdbe, and only then if:
66047 ** * the associated function parameter is the 32nd or later (counting
66048 ** from left to right), or
66050 ** * the corresponding bit in argument mask is clear (where the first
66051 ** function parameter corresponds to bit 0 etc.).
66053 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
66054 AuxData **pp = &pVdbe->pAuxData;
66055 while( *pp ){
66056 AuxData *pAux = *pp;
66057 if( (iOp<0)
66058 || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
66060 testcase( pAux->iArg==31 );
66061 if( pAux->xDelete ){
66062 pAux->xDelete(pAux->pAux);
66064 *pp = pAux->pNext;
66065 sqlite3DbFree(pVdbe->db, pAux);
66066 }else{
66067 pp= &pAux->pNext;
66073 ** Free all memory associated with the Vdbe passed as the second argument,
66074 ** except for object itself, which is preserved.
66076 ** The difference between this function and sqlite3VdbeDelete() is that
66077 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
66078 ** the database connection and frees the object itself.
66080 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
66081 SubProgram *pSub, *pNext;
66082 int i;
66083 assert( p->db==0 || p->db==db );
66084 releaseMemArray(p->aVar, p->nVar);
66085 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
66086 for(pSub=p->pProgram; pSub; pSub=pNext){
66087 pNext = pSub->pNext;
66088 vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
66089 sqlite3DbFree(db, pSub);
66091 for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
66092 vdbeFreeOpArray(db, p->aOp, p->nOp);
66093 sqlite3DbFree(db, p->aColName);
66094 sqlite3DbFree(db, p->zSql);
66095 sqlite3DbFree(db, p->pFree);
66099 ** Delete an entire VDBE.
66101 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
66102 sqlite3 *db;
66104 if( NEVER(p==0) ) return;
66105 db = p->db;
66106 assert( sqlite3_mutex_held(db->mutex) );
66107 sqlite3VdbeClearObject(db, p);
66108 if( p->pPrev ){
66109 p->pPrev->pNext = p->pNext;
66110 }else{
66111 assert( db->pVdbe==p );
66112 db->pVdbe = p->pNext;
66114 if( p->pNext ){
66115 p->pNext->pPrev = p->pPrev;
66117 p->magic = VDBE_MAGIC_DEAD;
66118 p->db = 0;
66119 sqlite3DbFree(db, p);
66123 ** The cursor "p" has a pending seek operation that has not yet been
66124 ** carried out. Seek the cursor now. If an error occurs, return
66125 ** the appropriate error code.
66127 static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
66128 int res, rc;
66129 #ifdef SQLITE_TEST
66130 extern int sqlite3_search_count;
66131 #endif
66132 assert( p->deferredMoveto );
66133 assert( p->isTable );
66134 rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
66135 if( rc ) return rc;
66136 if( res!=0 ) return SQLITE_CORRUPT_BKPT;
66137 #ifdef SQLITE_TEST
66138 sqlite3_search_count++;
66139 #endif
66140 p->deferredMoveto = 0;
66141 p->cacheStatus = CACHE_STALE;
66142 return SQLITE_OK;
66146 ** Something has moved cursor "p" out of place. Maybe the row it was
66147 ** pointed to was deleted out from under it. Or maybe the btree was
66148 ** rebalanced. Whatever the cause, try to restore "p" to the place it
66149 ** is supposed to be pointing. If the row was deleted out from under the
66150 ** cursor, set the cursor to point to a NULL row.
66152 static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
66153 int isDifferentRow, rc;
66154 assert( p->pCursor!=0 );
66155 assert( sqlite3BtreeCursorHasMoved(p->pCursor) );
66156 rc = sqlite3BtreeCursorRestore(p->pCursor, &isDifferentRow);
66157 p->cacheStatus = CACHE_STALE;
66158 if( isDifferentRow ) p->nullRow = 1;
66159 return rc;
66163 ** Check to ensure that the cursor is valid. Restore the cursor
66164 ** if need be. Return any I/O error from the restore operation.
66166 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
66167 if( sqlite3BtreeCursorHasMoved(p->pCursor) ){
66168 return handleMovedCursor(p);
66170 return SQLITE_OK;
66174 ** Make sure the cursor p is ready to read or write the row to which it
66175 ** was last positioned. Return an error code if an OOM fault or I/O error
66176 ** prevents us from positioning the cursor to its correct position.
66178 ** If a MoveTo operation is pending on the given cursor, then do that
66179 ** MoveTo now. If no move is pending, check to see if the row has been
66180 ** deleted out from under the cursor and if it has, mark the row as
66181 ** a NULL row.
66183 ** If the cursor is already pointing to the correct row and that row has
66184 ** not been deleted out from under the cursor, then this routine is a no-op.
66186 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
66187 if( p->deferredMoveto ){
66188 return handleDeferredMoveto(p);
66190 if( p->pCursor && sqlite3BtreeCursorHasMoved(p->pCursor) ){
66191 return handleMovedCursor(p);
66193 return SQLITE_OK;
66197 ** The following functions:
66199 ** sqlite3VdbeSerialType()
66200 ** sqlite3VdbeSerialTypeLen()
66201 ** sqlite3VdbeSerialLen()
66202 ** sqlite3VdbeSerialPut()
66203 ** sqlite3VdbeSerialGet()
66205 ** encapsulate the code that serializes values for storage in SQLite
66206 ** data and index records. Each serialized value consists of a
66207 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
66208 ** integer, stored as a varint.
66210 ** In an SQLite index record, the serial type is stored directly before
66211 ** the blob of data that it corresponds to. In a table record, all serial
66212 ** types are stored at the start of the record, and the blobs of data at
66213 ** the end. Hence these functions allow the caller to handle the
66214 ** serial-type and data blob separately.
66216 ** The following table describes the various storage classes for data:
66218 ** serial type bytes of data type
66219 ** -------------- --------------- ---------------
66220 ** 0 0 NULL
66221 ** 1 1 signed integer
66222 ** 2 2 signed integer
66223 ** 3 3 signed integer
66224 ** 4 4 signed integer
66225 ** 5 6 signed integer
66226 ** 6 8 signed integer
66227 ** 7 8 IEEE float
66228 ** 8 0 Integer constant 0
66229 ** 9 0 Integer constant 1
66230 ** 10,11 reserved for expansion
66231 ** N>=12 and even (N-12)/2 BLOB
66232 ** N>=13 and odd (N-13)/2 text
66234 ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
66235 ** of SQLite will not understand those serial types.
66239 ** Return the serial-type for the value stored in pMem.
66241 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
66242 int flags = pMem->flags;
66243 u32 n;
66245 if( flags&MEM_Null ){
66246 return 0;
66248 if( flags&MEM_Int ){
66249 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
66250 # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
66251 i64 i = pMem->u.i;
66252 u64 u;
66253 if( i<0 ){
66254 if( i<(-MAX_6BYTE) ) return 6;
66255 /* Previous test prevents: u = -(-9223372036854775808) */
66256 u = -i;
66257 }else{
66258 u = i;
66260 if( u<=127 ){
66261 return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
66263 if( u<=32767 ) return 2;
66264 if( u<=8388607 ) return 3;
66265 if( u<=2147483647 ) return 4;
66266 if( u<=MAX_6BYTE ) return 5;
66267 return 6;
66269 if( flags&MEM_Real ){
66270 return 7;
66272 assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
66273 assert( pMem->n>=0 );
66274 n = (u32)pMem->n;
66275 if( flags & MEM_Zero ){
66276 n += pMem->u.nZero;
66278 return ((n*2) + 12 + ((flags&MEM_Str)!=0));
66282 ** Return the length of the data corresponding to the supplied serial-type.
66284 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
66285 if( serial_type>=12 ){
66286 return (serial_type-12)/2;
66287 }else{
66288 static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
66289 return aSize[serial_type];
66294 ** If we are on an architecture with mixed-endian floating
66295 ** points (ex: ARM7) then swap the lower 4 bytes with the
66296 ** upper 4 bytes. Return the result.
66298 ** For most architectures, this is a no-op.
66300 ** (later): It is reported to me that the mixed-endian problem
66301 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
66302 ** that early versions of GCC stored the two words of a 64-bit
66303 ** float in the wrong order. And that error has been propagated
66304 ** ever since. The blame is not necessarily with GCC, though.
66305 ** GCC might have just copying the problem from a prior compiler.
66306 ** I am also told that newer versions of GCC that follow a different
66307 ** ABI get the byte order right.
66309 ** Developers using SQLite on an ARM7 should compile and run their
66310 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
66311 ** enabled, some asserts below will ensure that the byte order of
66312 ** floating point values is correct.
66314 ** (2007-08-30) Frank van Vugt has studied this problem closely
66315 ** and has send his findings to the SQLite developers. Frank
66316 ** writes that some Linux kernels offer floating point hardware
66317 ** emulation that uses only 32-bit mantissas instead of a full
66318 ** 48-bits as required by the IEEE standard. (This is the
66319 ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
66320 ** byte swapping becomes very complicated. To avoid problems,
66321 ** the necessary byte swapping is carried out using a 64-bit integer
66322 ** rather than a 64-bit float. Frank assures us that the code here
66323 ** works for him. We, the developers, have no way to independently
66324 ** verify this, but Frank seems to know what he is talking about
66325 ** so we trust him.
66327 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
66328 static u64 floatSwap(u64 in){
66329 union {
66330 u64 r;
66331 u32 i[2];
66332 } u;
66333 u32 t;
66335 u.r = in;
66336 t = u.i[0];
66337 u.i[0] = u.i[1];
66338 u.i[1] = t;
66339 return u.r;
66341 # define swapMixedEndianFloat(X) X = floatSwap(X)
66342 #else
66343 # define swapMixedEndianFloat(X)
66344 #endif
66347 ** Write the serialized data blob for the value stored in pMem into
66348 ** buf. It is assumed that the caller has allocated sufficient space.
66349 ** Return the number of bytes written.
66351 ** nBuf is the amount of space left in buf[]. The caller is responsible
66352 ** for allocating enough space to buf[] to hold the entire field, exclusive
66353 ** of the pMem->u.nZero bytes for a MEM_Zero value.
66355 ** Return the number of bytes actually written into buf[]. The number
66356 ** of bytes in the zero-filled tail is included in the return value only
66357 ** if those bytes were zeroed in buf[].
66359 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
66360 u32 len;
66362 /* Integer and Real */
66363 if( serial_type<=7 && serial_type>0 ){
66364 u64 v;
66365 u32 i;
66366 if( serial_type==7 ){
66367 assert( sizeof(v)==sizeof(pMem->u.r) );
66368 memcpy(&v, &pMem->u.r, sizeof(v));
66369 swapMixedEndianFloat(v);
66370 }else{
66371 v = pMem->u.i;
66373 len = i = sqlite3VdbeSerialTypeLen(serial_type);
66374 assert( i>0 );
66376 buf[--i] = (u8)(v&0xFF);
66377 v >>= 8;
66378 }while( i );
66379 return len;
66382 /* String or blob */
66383 if( serial_type>=12 ){
66384 assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
66385 == (int)sqlite3VdbeSerialTypeLen(serial_type) );
66386 len = pMem->n;
66387 memcpy(buf, pMem->z, len);
66388 return len;
66391 /* NULL or constants 0 or 1 */
66392 return 0;
66395 /* Input "x" is a sequence of unsigned characters that represent a
66396 ** big-endian integer. Return the equivalent native integer
66398 #define ONE_BYTE_INT(x) ((i8)(x)[0])
66399 #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
66400 #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
66401 #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
66402 #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
66405 ** Deserialize the data blob pointed to by buf as serial type serial_type
66406 ** and store the result in pMem. Return the number of bytes read.
66408 ** This function is implemented as two separate routines for performance.
66409 ** The few cases that require local variables are broken out into a separate
66410 ** routine so that in most cases the overhead of moving the stack pointer
66411 ** is avoided.
66413 static u32 SQLITE_NOINLINE serialGet(
66414 const unsigned char *buf, /* Buffer to deserialize from */
66415 u32 serial_type, /* Serial type to deserialize */
66416 Mem *pMem /* Memory cell to write value into */
66418 u64 x = FOUR_BYTE_UINT(buf);
66419 u32 y = FOUR_BYTE_UINT(buf+4);
66420 x = (x<<32) + y;
66421 if( serial_type==6 ){
66422 pMem->u.i = *(i64*)&x;
66423 pMem->flags = MEM_Int;
66424 testcase( pMem->u.i<0 );
66425 }else{
66426 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
66427 /* Verify that integers and floating point values use the same
66428 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
66429 ** defined that 64-bit floating point values really are mixed
66430 ** endian.
66432 static const u64 t1 = ((u64)0x3ff00000)<<32;
66433 static const double r1 = 1.0;
66434 u64 t2 = t1;
66435 swapMixedEndianFloat(t2);
66436 assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
66437 #endif
66438 assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
66439 swapMixedEndianFloat(x);
66440 memcpy(&pMem->u.r, &x, sizeof(x));
66441 pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
66443 return 8;
66445 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
66446 const unsigned char *buf, /* Buffer to deserialize from */
66447 u32 serial_type, /* Serial type to deserialize */
66448 Mem *pMem /* Memory cell to write value into */
66450 switch( serial_type ){
66451 case 10: /* Reserved for future use */
66452 case 11: /* Reserved for future use */
66453 case 0: { /* NULL */
66454 pMem->flags = MEM_Null;
66455 break;
66457 case 1: { /* 1-byte signed integer */
66458 pMem->u.i = ONE_BYTE_INT(buf);
66459 pMem->flags = MEM_Int;
66460 testcase( pMem->u.i<0 );
66461 return 1;
66463 case 2: { /* 2-byte signed integer */
66464 pMem->u.i = TWO_BYTE_INT(buf);
66465 pMem->flags = MEM_Int;
66466 testcase( pMem->u.i<0 );
66467 return 2;
66469 case 3: { /* 3-byte signed integer */
66470 pMem->u.i = THREE_BYTE_INT(buf);
66471 pMem->flags = MEM_Int;
66472 testcase( pMem->u.i<0 );
66473 return 3;
66475 case 4: { /* 4-byte signed integer */
66476 pMem->u.i = FOUR_BYTE_INT(buf);
66477 pMem->flags = MEM_Int;
66478 testcase( pMem->u.i<0 );
66479 return 4;
66481 case 5: { /* 6-byte signed integer */
66482 pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
66483 pMem->flags = MEM_Int;
66484 testcase( pMem->u.i<0 );
66485 return 6;
66487 case 6: /* 8-byte signed integer */
66488 case 7: { /* IEEE floating point */
66489 /* These use local variables, so do them in a separate routine
66490 ** to avoid having to move the frame pointer in the common case */
66491 return serialGet(buf,serial_type,pMem);
66493 case 8: /* Integer 0 */
66494 case 9: { /* Integer 1 */
66495 pMem->u.i = serial_type-8;
66496 pMem->flags = MEM_Int;
66497 return 0;
66499 default: {
66500 static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
66501 pMem->z = (char *)buf;
66502 pMem->n = (serial_type-12)/2;
66503 pMem->flags = aFlag[serial_type&1];
66504 return pMem->n;
66507 return 0;
66510 ** This routine is used to allocate sufficient space for an UnpackedRecord
66511 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
66512 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
66514 ** The space is either allocated using sqlite3DbMallocRaw() or from within
66515 ** the unaligned buffer passed via the second and third arguments (presumably
66516 ** stack space). If the former, then *ppFree is set to a pointer that should
66517 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
66518 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
66519 ** before returning.
66521 ** If an OOM error occurs, NULL is returned.
66523 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
66524 KeyInfo *pKeyInfo, /* Description of the record */
66525 char *pSpace, /* Unaligned space available */
66526 int szSpace, /* Size of pSpace[] in bytes */
66527 char **ppFree /* OUT: Caller should free this pointer */
66529 UnpackedRecord *p; /* Unpacked record to return */
66530 int nOff; /* Increment pSpace by nOff to align it */
66531 int nByte; /* Number of bytes required for *p */
66533 /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
66534 ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
66535 ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
66537 nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
66538 nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
66539 if( nByte>szSpace+nOff ){
66540 p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
66541 *ppFree = (char *)p;
66542 if( !p ) return 0;
66543 }else{
66544 p = (UnpackedRecord*)&pSpace[nOff];
66545 *ppFree = 0;
66548 p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
66549 assert( pKeyInfo->aSortOrder!=0 );
66550 p->pKeyInfo = pKeyInfo;
66551 p->nField = pKeyInfo->nField + 1;
66552 return p;
66556 ** Given the nKey-byte encoding of a record in pKey[], populate the
66557 ** UnpackedRecord structure indicated by the fourth argument with the
66558 ** contents of the decoded record.
66560 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
66561 KeyInfo *pKeyInfo, /* Information about the record format */
66562 int nKey, /* Size of the binary record */
66563 const void *pKey, /* The binary record */
66564 UnpackedRecord *p /* Populate this structure before returning. */
66566 const unsigned char *aKey = (const unsigned char *)pKey;
66567 int d;
66568 u32 idx; /* Offset in aKey[] to read from */
66569 u16 u; /* Unsigned loop counter */
66570 u32 szHdr;
66571 Mem *pMem = p->aMem;
66573 p->default_rc = 0;
66574 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
66575 idx = getVarint32(aKey, szHdr);
66576 d = szHdr;
66577 u = 0;
66578 while( idx<szHdr && d<=nKey ){
66579 u32 serial_type;
66581 idx += getVarint32(&aKey[idx], serial_type);
66582 pMem->enc = pKeyInfo->enc;
66583 pMem->db = pKeyInfo->db;
66584 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
66585 pMem->szMalloc = 0;
66586 d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
66587 pMem++;
66588 if( (++u)>=p->nField ) break;
66590 assert( u<=pKeyInfo->nField + 1 );
66591 p->nField = u;
66594 #if SQLITE_DEBUG
66596 ** This function compares two index or table record keys in the same way
66597 ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
66598 ** this function deserializes and compares values using the
66599 ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
66600 ** in assert() statements to ensure that the optimized code in
66601 ** sqlite3VdbeRecordCompare() returns results with these two primitives.
66603 ** Return true if the result of comparison is equivalent to desiredResult.
66604 ** Return false if there is a disagreement.
66606 static int vdbeRecordCompareDebug(
66607 int nKey1, const void *pKey1, /* Left key */
66608 const UnpackedRecord *pPKey2, /* Right key */
66609 int desiredResult /* Correct answer */
66611 u32 d1; /* Offset into aKey[] of next data element */
66612 u32 idx1; /* Offset into aKey[] of next header element */
66613 u32 szHdr1; /* Number of bytes in header */
66614 int i = 0;
66615 int rc = 0;
66616 const unsigned char *aKey1 = (const unsigned char *)pKey1;
66617 KeyInfo *pKeyInfo;
66618 Mem mem1;
66620 pKeyInfo = pPKey2->pKeyInfo;
66621 if( pKeyInfo->db==0 ) return 1;
66622 mem1.enc = pKeyInfo->enc;
66623 mem1.db = pKeyInfo->db;
66624 /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
66625 VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
66627 /* Compilers may complain that mem1.u.i is potentially uninitialized.
66628 ** We could initialize it, as shown here, to silence those complaints.
66629 ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
66630 ** the unnecessary initialization has a measurable negative performance
66631 ** impact, since this routine is a very high runner. And so, we choose
66632 ** to ignore the compiler warnings and leave this variable uninitialized.
66634 /* mem1.u.i = 0; // not needed, here to silence compiler warning */
66636 idx1 = getVarint32(aKey1, szHdr1);
66637 d1 = szHdr1;
66638 assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
66639 assert( pKeyInfo->aSortOrder!=0 );
66640 assert( pKeyInfo->nField>0 );
66641 assert( idx1<=szHdr1 || CORRUPT_DB );
66643 u32 serial_type1;
66645 /* Read the serial types for the next element in each key. */
66646 idx1 += getVarint32( aKey1+idx1, serial_type1 );
66648 /* Verify that there is enough key space remaining to avoid
66649 ** a buffer overread. The "d1+serial_type1+2" subexpression will
66650 ** always be greater than or equal to the amount of required key space.
66651 ** Use that approximation to avoid the more expensive call to
66652 ** sqlite3VdbeSerialTypeLen() in the common case.
66654 if( d1+serial_type1+2>(u32)nKey1
66655 && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
66657 break;
66660 /* Extract the values to be compared.
66662 d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
66664 /* Do the comparison
66666 rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
66667 if( rc!=0 ){
66668 assert( mem1.szMalloc==0 ); /* See comment below */
66669 if( pKeyInfo->aSortOrder[i] ){
66670 rc = -rc; /* Invert the result for DESC sort order. */
66672 goto debugCompareEnd;
66674 i++;
66675 }while( idx1<szHdr1 && i<pPKey2->nField );
66677 /* No memory allocation is ever used on mem1. Prove this using
66678 ** the following assert(). If the assert() fails, it indicates a
66679 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
66681 assert( mem1.szMalloc==0 );
66683 /* rc==0 here means that one of the keys ran out of fields and
66684 ** all the fields up to that point were equal. Return the default_rc
66685 ** value. */
66686 rc = pPKey2->default_rc;
66688 debugCompareEnd:
66689 if( desiredResult==0 && rc==0 ) return 1;
66690 if( desiredResult<0 && rc<0 ) return 1;
66691 if( desiredResult>0 && rc>0 ) return 1;
66692 if( CORRUPT_DB ) return 1;
66693 if( pKeyInfo->db->mallocFailed ) return 1;
66694 return 0;
66696 #endif
66699 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
66700 ** using the collation sequence pColl. As usual, return a negative , zero
66701 ** or positive value if *pMem1 is less than, equal to or greater than
66702 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
66704 static int vdbeCompareMemString(
66705 const Mem *pMem1,
66706 const Mem *pMem2,
66707 const CollSeq *pColl,
66708 u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
66710 if( pMem1->enc==pColl->enc ){
66711 /* The strings are already in the correct encoding. Call the
66712 ** comparison function directly */
66713 return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
66714 }else{
66715 int rc;
66716 const void *v1, *v2;
66717 int n1, n2;
66718 Mem c1;
66719 Mem c2;
66720 sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
66721 sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
66722 sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
66723 sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
66724 v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
66725 n1 = v1==0 ? 0 : c1.n;
66726 v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
66727 n2 = v2==0 ? 0 : c2.n;
66728 rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
66729 sqlite3VdbeMemRelease(&c1);
66730 sqlite3VdbeMemRelease(&c2);
66731 if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM;
66732 return rc;
66737 ** Compare two blobs. Return negative, zero, or positive if the first
66738 ** is less than, equal to, or greater than the second, respectively.
66739 ** If one blob is a prefix of the other, then the shorter is the lessor.
66741 static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
66742 int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
66743 if( c ) return c;
66744 return pB1->n - pB2->n;
66749 ** Compare the values contained by the two memory cells, returning
66750 ** negative, zero or positive if pMem1 is less than, equal to, or greater
66751 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
66752 ** and reals) sorted numerically, followed by text ordered by the collating
66753 ** sequence pColl and finally blob's ordered by memcmp().
66755 ** Two NULL values are considered equal by this function.
66757 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
66758 int f1, f2;
66759 int combined_flags;
66761 f1 = pMem1->flags;
66762 f2 = pMem2->flags;
66763 combined_flags = f1|f2;
66764 assert( (combined_flags & MEM_RowSet)==0 );
66766 /* If one value is NULL, it is less than the other. If both values
66767 ** are NULL, return 0.
66769 if( combined_flags&MEM_Null ){
66770 return (f2&MEM_Null) - (f1&MEM_Null);
66773 /* If one value is a number and the other is not, the number is less.
66774 ** If both are numbers, compare as reals if one is a real, or as integers
66775 ** if both values are integers.
66777 if( combined_flags&(MEM_Int|MEM_Real) ){
66778 double r1, r2;
66779 if( (f1 & f2 & MEM_Int)!=0 ){
66780 if( pMem1->u.i < pMem2->u.i ) return -1;
66781 if( pMem1->u.i > pMem2->u.i ) return 1;
66782 return 0;
66784 if( (f1&MEM_Real)!=0 ){
66785 r1 = pMem1->u.r;
66786 }else if( (f1&MEM_Int)!=0 ){
66787 r1 = (double)pMem1->u.i;
66788 }else{
66789 return 1;
66791 if( (f2&MEM_Real)!=0 ){
66792 r2 = pMem2->u.r;
66793 }else if( (f2&MEM_Int)!=0 ){
66794 r2 = (double)pMem2->u.i;
66795 }else{
66796 return -1;
66798 if( r1<r2 ) return -1;
66799 if( r1>r2 ) return 1;
66800 return 0;
66803 /* If one value is a string and the other is a blob, the string is less.
66804 ** If both are strings, compare using the collating functions.
66806 if( combined_flags&MEM_Str ){
66807 if( (f1 & MEM_Str)==0 ){
66808 return 1;
66810 if( (f2 & MEM_Str)==0 ){
66811 return -1;
66814 assert( pMem1->enc==pMem2->enc );
66815 assert( pMem1->enc==SQLITE_UTF8 ||
66816 pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
66818 /* The collation sequence must be defined at this point, even if
66819 ** the user deletes the collation sequence after the vdbe program is
66820 ** compiled (this was not always the case).
66822 assert( !pColl || pColl->xCmp );
66824 if( pColl ){
66825 return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
66827 /* If a NULL pointer was passed as the collate function, fall through
66828 ** to the blob case and use memcmp(). */
66831 /* Both values must be blobs. Compare using memcmp(). */
66832 return sqlite3BlobCompare(pMem1, pMem2);
66837 ** The first argument passed to this function is a serial-type that
66838 ** corresponds to an integer - all values between 1 and 9 inclusive
66839 ** except 7. The second points to a buffer containing an integer value
66840 ** serialized according to serial_type. This function deserializes
66841 ** and returns the value.
66843 static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
66844 u32 y;
66845 assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
66846 switch( serial_type ){
66847 case 0:
66848 case 1:
66849 testcase( aKey[0]&0x80 );
66850 return ONE_BYTE_INT(aKey);
66851 case 2:
66852 testcase( aKey[0]&0x80 );
66853 return TWO_BYTE_INT(aKey);
66854 case 3:
66855 testcase( aKey[0]&0x80 );
66856 return THREE_BYTE_INT(aKey);
66857 case 4: {
66858 testcase( aKey[0]&0x80 );
66859 y = FOUR_BYTE_UINT(aKey);
66860 return (i64)*(int*)&y;
66862 case 5: {
66863 testcase( aKey[0]&0x80 );
66864 return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
66866 case 6: {
66867 u64 x = FOUR_BYTE_UINT(aKey);
66868 testcase( aKey[0]&0x80 );
66869 x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
66870 return (i64)*(i64*)&x;
66874 return (serial_type - 8);
66878 ** This function compares the two table rows or index records
66879 ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
66880 ** or positive integer if key1 is less than, equal to or
66881 ** greater than key2. The {nKey1, pKey1} key must be a blob
66882 ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
66883 ** key must be a parsed key such as obtained from
66884 ** sqlite3VdbeParseRecord.
66886 ** If argument bSkip is non-zero, it is assumed that the caller has already
66887 ** determined that the first fields of the keys are equal.
66889 ** Key1 and Key2 do not have to contain the same number of fields. If all
66890 ** fields that appear in both keys are equal, then pPKey2->default_rc is
66891 ** returned.
66893 ** If database corruption is discovered, set pPKey2->errCode to
66894 ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
66895 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
66896 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
66898 static int vdbeRecordCompareWithSkip(
66899 int nKey1, const void *pKey1, /* Left key */
66900 UnpackedRecord *pPKey2, /* Right key */
66901 int bSkip /* If true, skip the first field */
66903 u32 d1; /* Offset into aKey[] of next data element */
66904 int i; /* Index of next field to compare */
66905 u32 szHdr1; /* Size of record header in bytes */
66906 u32 idx1; /* Offset of first type in header */
66907 int rc = 0; /* Return value */
66908 Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
66909 KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
66910 const unsigned char *aKey1 = (const unsigned char *)pKey1;
66911 Mem mem1;
66913 /* If bSkip is true, then the caller has already determined that the first
66914 ** two elements in the keys are equal. Fix the various stack variables so
66915 ** that this routine begins comparing at the second field. */
66916 if( bSkip ){
66917 u32 s1;
66918 idx1 = 1 + getVarint32(&aKey1[1], s1);
66919 szHdr1 = aKey1[0];
66920 d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
66921 i = 1;
66922 pRhs++;
66923 }else{
66924 idx1 = getVarint32(aKey1, szHdr1);
66925 d1 = szHdr1;
66926 if( d1>(unsigned)nKey1 ){
66927 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
66928 return 0; /* Corruption */
66930 i = 0;
66933 VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
66934 assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
66935 || CORRUPT_DB );
66936 assert( pPKey2->pKeyInfo->aSortOrder!=0 );
66937 assert( pPKey2->pKeyInfo->nField>0 );
66938 assert( idx1<=szHdr1 || CORRUPT_DB );
66940 u32 serial_type;
66942 /* RHS is an integer */
66943 if( pRhs->flags & MEM_Int ){
66944 serial_type = aKey1[idx1];
66945 testcase( serial_type==12 );
66946 if( serial_type>=12 ){
66947 rc = +1;
66948 }else if( serial_type==0 ){
66949 rc = -1;
66950 }else if( serial_type==7 ){
66951 double rhs = (double)pRhs->u.i;
66952 sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
66953 if( mem1.u.r<rhs ){
66954 rc = -1;
66955 }else if( mem1.u.r>rhs ){
66956 rc = +1;
66958 }else{
66959 i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
66960 i64 rhs = pRhs->u.i;
66961 if( lhs<rhs ){
66962 rc = -1;
66963 }else if( lhs>rhs ){
66964 rc = +1;
66969 /* RHS is real */
66970 else if( pRhs->flags & MEM_Real ){
66971 serial_type = aKey1[idx1];
66972 if( serial_type>=12 ){
66973 rc = +1;
66974 }else if( serial_type==0 ){
66975 rc = -1;
66976 }else{
66977 double rhs = pRhs->u.r;
66978 double lhs;
66979 sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
66980 if( serial_type==7 ){
66981 lhs = mem1.u.r;
66982 }else{
66983 lhs = (double)mem1.u.i;
66985 if( lhs<rhs ){
66986 rc = -1;
66987 }else if( lhs>rhs ){
66988 rc = +1;
66993 /* RHS is a string */
66994 else if( pRhs->flags & MEM_Str ){
66995 getVarint32(&aKey1[idx1], serial_type);
66996 testcase( serial_type==12 );
66997 if( serial_type<12 ){
66998 rc = -1;
66999 }else if( !(serial_type & 0x01) ){
67000 rc = +1;
67001 }else{
67002 mem1.n = (serial_type - 12) / 2;
67003 testcase( (d1+mem1.n)==(unsigned)nKey1 );
67004 testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
67005 if( (d1+mem1.n) > (unsigned)nKey1 ){
67006 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
67007 return 0; /* Corruption */
67008 }else if( pKeyInfo->aColl[i] ){
67009 mem1.enc = pKeyInfo->enc;
67010 mem1.db = pKeyInfo->db;
67011 mem1.flags = MEM_Str;
67012 mem1.z = (char*)&aKey1[d1];
67013 rc = vdbeCompareMemString(
67014 &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
67016 }else{
67017 int nCmp = MIN(mem1.n, pRhs->n);
67018 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
67019 if( rc==0 ) rc = mem1.n - pRhs->n;
67024 /* RHS is a blob */
67025 else if( pRhs->flags & MEM_Blob ){
67026 getVarint32(&aKey1[idx1], serial_type);
67027 testcase( serial_type==12 );
67028 if( serial_type<12 || (serial_type & 0x01) ){
67029 rc = -1;
67030 }else{
67031 int nStr = (serial_type - 12) / 2;
67032 testcase( (d1+nStr)==(unsigned)nKey1 );
67033 testcase( (d1+nStr+1)==(unsigned)nKey1 );
67034 if( (d1+nStr) > (unsigned)nKey1 ){
67035 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
67036 return 0; /* Corruption */
67037 }else{
67038 int nCmp = MIN(nStr, pRhs->n);
67039 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
67040 if( rc==0 ) rc = nStr - pRhs->n;
67045 /* RHS is null */
67046 else{
67047 serial_type = aKey1[idx1];
67048 rc = (serial_type!=0);
67051 if( rc!=0 ){
67052 if( pKeyInfo->aSortOrder[i] ){
67053 rc = -rc;
67055 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
67056 assert( mem1.szMalloc==0 ); /* See comment below */
67057 return rc;
67060 i++;
67061 pRhs++;
67062 d1 += sqlite3VdbeSerialTypeLen(serial_type);
67063 idx1 += sqlite3VarintLen(serial_type);
67064 }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
67066 /* No memory allocation is ever used on mem1. Prove this using
67067 ** the following assert(). If the assert() fails, it indicates a
67068 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
67069 assert( mem1.szMalloc==0 );
67071 /* rc==0 here means that one or both of the keys ran out of fields and
67072 ** all the fields up to that point were equal. Return the default_rc
67073 ** value. */
67074 assert( CORRUPT_DB
67075 || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
67076 || pKeyInfo->db->mallocFailed
67078 return pPKey2->default_rc;
67080 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
67081 int nKey1, const void *pKey1, /* Left key */
67082 UnpackedRecord *pPKey2 /* Right key */
67084 return vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
67089 ** This function is an optimized version of sqlite3VdbeRecordCompare()
67090 ** that (a) the first field of pPKey2 is an integer, and (b) the
67091 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
67092 ** byte (i.e. is less than 128).
67094 ** To avoid concerns about buffer overreads, this routine is only used
67095 ** on schemas where the maximum valid header size is 63 bytes or less.
67097 static int vdbeRecordCompareInt(
67098 int nKey1, const void *pKey1, /* Left key */
67099 UnpackedRecord *pPKey2 /* Right key */
67101 const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
67102 int serial_type = ((const u8*)pKey1)[1];
67103 int res;
67104 u32 y;
67105 u64 x;
67106 i64 v = pPKey2->aMem[0].u.i;
67107 i64 lhs;
67109 assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
67110 switch( serial_type ){
67111 case 1: { /* 1-byte signed integer */
67112 lhs = ONE_BYTE_INT(aKey);
67113 testcase( lhs<0 );
67114 break;
67116 case 2: { /* 2-byte signed integer */
67117 lhs = TWO_BYTE_INT(aKey);
67118 testcase( lhs<0 );
67119 break;
67121 case 3: { /* 3-byte signed integer */
67122 lhs = THREE_BYTE_INT(aKey);
67123 testcase( lhs<0 );
67124 break;
67126 case 4: { /* 4-byte signed integer */
67127 y = FOUR_BYTE_UINT(aKey);
67128 lhs = (i64)*(int*)&y;
67129 testcase( lhs<0 );
67130 break;
67132 case 5: { /* 6-byte signed integer */
67133 lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
67134 testcase( lhs<0 );
67135 break;
67137 case 6: { /* 8-byte signed integer */
67138 x = FOUR_BYTE_UINT(aKey);
67139 x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
67140 lhs = *(i64*)&x;
67141 testcase( lhs<0 );
67142 break;
67144 case 8:
67145 lhs = 0;
67146 break;
67147 case 9:
67148 lhs = 1;
67149 break;
67151 /* This case could be removed without changing the results of running
67152 ** this code. Including it causes gcc to generate a faster switch
67153 ** statement (since the range of switch targets now starts at zero and
67154 ** is contiguous) but does not cause any duplicate code to be generated
67155 ** (as gcc is clever enough to combine the two like cases). Other
67156 ** compilers might be similar. */
67157 case 0: case 7:
67158 return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
67160 default:
67161 return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
67164 if( v>lhs ){
67165 res = pPKey2->r1;
67166 }else if( v<lhs ){
67167 res = pPKey2->r2;
67168 }else if( pPKey2->nField>1 ){
67169 /* The first fields of the two keys are equal. Compare the trailing
67170 ** fields. */
67171 res = vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
67172 }else{
67173 /* The first fields of the two keys are equal and there are no trailing
67174 ** fields. Return pPKey2->default_rc in this case. */
67175 res = pPKey2->default_rc;
67178 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
67179 return res;
67183 ** This function is an optimized version of sqlite3VdbeRecordCompare()
67184 ** that (a) the first field of pPKey2 is a string, that (b) the first field
67185 ** uses the collation sequence BINARY and (c) that the size-of-header varint
67186 ** at the start of (pKey1/nKey1) fits in a single byte.
67188 static int vdbeRecordCompareString(
67189 int nKey1, const void *pKey1, /* Left key */
67190 UnpackedRecord *pPKey2 /* Right key */
67192 const u8 *aKey1 = (const u8*)pKey1;
67193 int serial_type;
67194 int res;
67196 getVarint32(&aKey1[1], serial_type);
67197 if( serial_type<12 ){
67198 res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
67199 }else if( !(serial_type & 0x01) ){
67200 res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
67201 }else{
67202 int nCmp;
67203 int nStr;
67204 int szHdr = aKey1[0];
67206 nStr = (serial_type-12) / 2;
67207 if( (szHdr + nStr) > nKey1 ){
67208 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
67209 return 0; /* Corruption */
67211 nCmp = MIN( pPKey2->aMem[0].n, nStr );
67212 res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
67214 if( res==0 ){
67215 res = nStr - pPKey2->aMem[0].n;
67216 if( res==0 ){
67217 if( pPKey2->nField>1 ){
67218 res = vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
67219 }else{
67220 res = pPKey2->default_rc;
67222 }else if( res>0 ){
67223 res = pPKey2->r2;
67224 }else{
67225 res = pPKey2->r1;
67227 }else if( res>0 ){
67228 res = pPKey2->r2;
67229 }else{
67230 res = pPKey2->r1;
67234 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
67235 || CORRUPT_DB
67236 || pPKey2->pKeyInfo->db->mallocFailed
67238 return res;
67242 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
67243 ** suitable for comparing serialized records to the unpacked record passed
67244 ** as the only argument.
67246 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
67247 /* varintRecordCompareInt() and varintRecordCompareString() both assume
67248 ** that the size-of-header varint that occurs at the start of each record
67249 ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
67250 ** also assumes that it is safe to overread a buffer by at least the
67251 ** maximum possible legal header size plus 8 bytes. Because there is
67252 ** guaranteed to be at least 74 (but not 136) bytes of padding following each
67253 ** buffer passed to varintRecordCompareInt() this makes it convenient to
67254 ** limit the size of the header to 64 bytes in cases where the first field
67255 ** is an integer.
67257 ** The easiest way to enforce this limit is to consider only records with
67258 ** 13 fields or less. If the first field is an integer, the maximum legal
67259 ** header size is (12*5 + 1 + 1) bytes. */
67260 if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
67261 int flags = p->aMem[0].flags;
67262 if( p->pKeyInfo->aSortOrder[0] ){
67263 p->r1 = 1;
67264 p->r2 = -1;
67265 }else{
67266 p->r1 = -1;
67267 p->r2 = 1;
67269 if( (flags & MEM_Int) ){
67270 return vdbeRecordCompareInt;
67272 testcase( flags & MEM_Real );
67273 testcase( flags & MEM_Null );
67274 testcase( flags & MEM_Blob );
67275 if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
67276 assert( flags & MEM_Str );
67277 return vdbeRecordCompareString;
67281 return sqlite3VdbeRecordCompare;
67285 ** pCur points at an index entry created using the OP_MakeRecord opcode.
67286 ** Read the rowid (the last field in the record) and store it in *rowid.
67287 ** Return SQLITE_OK if everything works, or an error code otherwise.
67289 ** pCur might be pointing to text obtained from a corrupt database file.
67290 ** So the content cannot be trusted. Do appropriate checks on the content.
67292 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
67293 i64 nCellKey = 0;
67294 int rc;
67295 u32 szHdr; /* Size of the header */
67296 u32 typeRowid; /* Serial type of the rowid */
67297 u32 lenRowid; /* Size of the rowid */
67298 Mem m, v;
67300 /* Get the size of the index entry. Only indices entries of less
67301 ** than 2GiB are support - anything large must be database corruption.
67302 ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
67303 ** this code can safely assume that nCellKey is 32-bits
67305 assert( sqlite3BtreeCursorIsValid(pCur) );
67306 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
67307 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
67308 assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
67310 /* Read in the complete content of the index entry */
67311 sqlite3VdbeMemInit(&m, db, 0);
67312 rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
67313 if( rc ){
67314 return rc;
67317 /* The index entry must begin with a header size */
67318 (void)getVarint32((u8*)m.z, szHdr);
67319 testcase( szHdr==3 );
67320 testcase( szHdr==m.n );
67321 if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
67322 goto idx_rowid_corruption;
67325 /* The last field of the index should be an integer - the ROWID.
67326 ** Verify that the last entry really is an integer. */
67327 (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
67328 testcase( typeRowid==1 );
67329 testcase( typeRowid==2 );
67330 testcase( typeRowid==3 );
67331 testcase( typeRowid==4 );
67332 testcase( typeRowid==5 );
67333 testcase( typeRowid==6 );
67334 testcase( typeRowid==8 );
67335 testcase( typeRowid==9 );
67336 if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
67337 goto idx_rowid_corruption;
67339 lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
67340 testcase( (u32)m.n==szHdr+lenRowid );
67341 if( unlikely((u32)m.n<szHdr+lenRowid) ){
67342 goto idx_rowid_corruption;
67345 /* Fetch the integer off the end of the index record */
67346 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
67347 *rowid = v.u.i;
67348 sqlite3VdbeMemRelease(&m);
67349 return SQLITE_OK;
67351 /* Jump here if database corruption is detected after m has been
67352 ** allocated. Free the m object and return SQLITE_CORRUPT. */
67353 idx_rowid_corruption:
67354 testcase( m.szMalloc!=0 );
67355 sqlite3VdbeMemRelease(&m);
67356 return SQLITE_CORRUPT_BKPT;
67360 ** Compare the key of the index entry that cursor pC is pointing to against
67361 ** the key string in pUnpacked. Write into *pRes a number
67362 ** that is negative, zero, or positive if pC is less than, equal to,
67363 ** or greater than pUnpacked. Return SQLITE_OK on success.
67365 ** pUnpacked is either created without a rowid or is truncated so that it
67366 ** omits the rowid at the end. The rowid at the end of the index entry
67367 ** is ignored as well. Hence, this routine only compares the prefixes
67368 ** of the keys prior to the final rowid, not the entire key.
67370 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
67371 sqlite3 *db, /* Database connection */
67372 VdbeCursor *pC, /* The cursor to compare against */
67373 UnpackedRecord *pUnpacked, /* Unpacked version of key */
67374 int *res /* Write the comparison result here */
67376 i64 nCellKey = 0;
67377 int rc;
67378 BtCursor *pCur = pC->pCursor;
67379 Mem m;
67381 assert( sqlite3BtreeCursorIsValid(pCur) );
67382 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
67383 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
67384 /* nCellKey will always be between 0 and 0xffffffff because of the way
67385 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
67386 if( nCellKey<=0 || nCellKey>0x7fffffff ){
67387 *res = 0;
67388 return SQLITE_CORRUPT_BKPT;
67390 sqlite3VdbeMemInit(&m, db, 0);
67391 rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
67392 if( rc ){
67393 return rc;
67395 *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
67396 sqlite3VdbeMemRelease(&m);
67397 return SQLITE_OK;
67401 ** This routine sets the value to be returned by subsequent calls to
67402 ** sqlite3_changes() on the database handle 'db'.
67404 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
67405 assert( sqlite3_mutex_held(db->mutex) );
67406 db->nChange = nChange;
67407 db->nTotalChange += nChange;
67411 ** Set a flag in the vdbe to update the change counter when it is finalised
67412 ** or reset.
67414 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
67415 v->changeCntOn = 1;
67419 ** Mark every prepared statement associated with a database connection
67420 ** as expired.
67422 ** An expired statement means that recompilation of the statement is
67423 ** recommend. Statements expire when things happen that make their
67424 ** programs obsolete. Removing user-defined functions or collating
67425 ** sequences, or changing an authorization function are the types of
67426 ** things that make prepared statements obsolete.
67428 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
67429 Vdbe *p;
67430 for(p = db->pVdbe; p; p=p->pNext){
67431 p->expired = 1;
67436 ** Return the database associated with the Vdbe.
67438 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
67439 return v->db;
67443 ** Return a pointer to an sqlite3_value structure containing the value bound
67444 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
67445 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
67446 ** constants) to the value before returning it.
67448 ** The returned value must be freed by the caller using sqlite3ValueFree().
67450 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
67451 assert( iVar>0 );
67452 if( v ){
67453 Mem *pMem = &v->aVar[iVar-1];
67454 if( 0==(pMem->flags & MEM_Null) ){
67455 sqlite3_value *pRet = sqlite3ValueNew(v->db);
67456 if( pRet ){
67457 sqlite3VdbeMemCopy((Mem *)pRet, pMem);
67458 sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
67460 return pRet;
67463 return 0;
67467 ** Configure SQL variable iVar so that binding a new value to it signals
67468 ** to sqlite3_reoptimize() that re-preparing the statement may result
67469 ** in a better query plan.
67471 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
67472 assert( iVar>0 );
67473 if( iVar>32 ){
67474 v->expmask = 0xffffffff;
67475 }else{
67476 v->expmask |= ((u32)1 << (iVar-1));
67480 #ifndef SQLITE_OMIT_VIRTUALTABLE
67482 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
67483 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
67484 ** in memory obtained from sqlite3DbMalloc).
67486 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
67487 sqlite3 *db = p->db;
67488 sqlite3DbFree(db, p->zErrMsg);
67489 p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
67490 sqlite3_free(pVtab->zErrMsg);
67491 pVtab->zErrMsg = 0;
67493 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67495 /************** End of vdbeaux.c *********************************************/
67496 /************** Begin file vdbeapi.c *****************************************/
67498 ** 2004 May 26
67500 ** The author disclaims copyright to this source code. In place of
67501 ** a legal notice, here is a blessing:
67503 ** May you do good and not evil.
67504 ** May you find forgiveness for yourself and forgive others.
67505 ** May you share freely, never taking more than you give.
67507 *************************************************************************
67509 ** This file contains code use to implement APIs that are part of the
67510 ** VDBE.
67513 #ifndef SQLITE_OMIT_DEPRECATED
67515 ** Return TRUE (non-zero) of the statement supplied as an argument needs
67516 ** to be recompiled. A statement needs to be recompiled whenever the
67517 ** execution environment changes in a way that would alter the program
67518 ** that sqlite3_prepare() generates. For example, if new functions or
67519 ** collating sequences are registered or if an authorizer function is
67520 ** added or changed.
67522 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
67523 Vdbe *p = (Vdbe*)pStmt;
67524 return p==0 || p->expired;
67526 #endif
67529 ** Check on a Vdbe to make sure it has not been finalized. Log
67530 ** an error and return true if it has been finalized (or is otherwise
67531 ** invalid). Return false if it is ok.
67533 static int vdbeSafety(Vdbe *p){
67534 if( p->db==0 ){
67535 sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
67536 return 1;
67537 }else{
67538 return 0;
67541 static int vdbeSafetyNotNull(Vdbe *p){
67542 if( p==0 ){
67543 sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
67544 return 1;
67545 }else{
67546 return vdbeSafety(p);
67551 ** The following routine destroys a virtual machine that is created by
67552 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
67553 ** success/failure code that describes the result of executing the virtual
67554 ** machine.
67556 ** This routine sets the error code and string returned by
67557 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
67559 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
67560 int rc;
67561 if( pStmt==0 ){
67562 /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
67563 ** pointer is a harmless no-op. */
67564 rc = SQLITE_OK;
67565 }else{
67566 Vdbe *v = (Vdbe*)pStmt;
67567 sqlite3 *db = v->db;
67568 if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
67569 sqlite3_mutex_enter(db->mutex);
67570 rc = sqlite3VdbeFinalize(v);
67571 rc = sqlite3ApiExit(db, rc);
67572 sqlite3LeaveMutexAndCloseZombie(db);
67574 return rc;
67578 ** Terminate the current execution of an SQL statement and reset it
67579 ** back to its starting state so that it can be reused. A success code from
67580 ** the prior execution is returned.
67582 ** This routine sets the error code and string returned by
67583 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
67585 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
67586 int rc;
67587 if( pStmt==0 ){
67588 rc = SQLITE_OK;
67589 }else{
67590 Vdbe *v = (Vdbe*)pStmt;
67591 sqlite3_mutex_enter(v->db->mutex);
67592 rc = sqlite3VdbeReset(v);
67593 sqlite3VdbeRewind(v);
67594 assert( (rc & (v->db->errMask))==rc );
67595 rc = sqlite3ApiExit(v->db, rc);
67596 sqlite3_mutex_leave(v->db->mutex);
67598 return rc;
67602 ** Set all the parameters in the compiled SQL statement to NULL.
67604 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
67605 int i;
67606 int rc = SQLITE_OK;
67607 Vdbe *p = (Vdbe*)pStmt;
67608 #if SQLITE_THREADSAFE
67609 sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
67610 #endif
67611 sqlite3_mutex_enter(mutex);
67612 for(i=0; i<p->nVar; i++){
67613 sqlite3VdbeMemRelease(&p->aVar[i]);
67614 p->aVar[i].flags = MEM_Null;
67616 if( p->isPrepareV2 && p->expmask ){
67617 p->expired = 1;
67619 sqlite3_mutex_leave(mutex);
67620 return rc;
67624 /**************************** sqlite3_value_ *******************************
67625 ** The following routines extract information from a Mem or sqlite3_value
67626 ** structure.
67628 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
67629 Mem *p = (Mem*)pVal;
67630 if( p->flags & (MEM_Blob|MEM_Str) ){
67631 sqlite3VdbeMemExpandBlob(p);
67632 p->flags |= MEM_Blob;
67633 return p->n ? p->z : 0;
67634 }else{
67635 return sqlite3_value_text(pVal);
67638 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
67639 return sqlite3ValueBytes(pVal, SQLITE_UTF8);
67641 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
67642 return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
67644 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
67645 return sqlite3VdbeRealValue((Mem*)pVal);
67647 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
67648 return (int)sqlite3VdbeIntValue((Mem*)pVal);
67650 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
67651 return sqlite3VdbeIntValue((Mem*)pVal);
67653 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
67654 return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
67656 #ifndef SQLITE_OMIT_UTF16
67657 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
67658 return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
67660 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
67661 return sqlite3ValueText(pVal, SQLITE_UTF16BE);
67663 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
67664 return sqlite3ValueText(pVal, SQLITE_UTF16LE);
67666 #endif /* SQLITE_OMIT_UTF16 */
67667 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
67668 static const u8 aType[] = {
67669 SQLITE_BLOB, /* 0x00 */
67670 SQLITE_NULL, /* 0x01 */
67671 SQLITE_TEXT, /* 0x02 */
67672 SQLITE_NULL, /* 0x03 */
67673 SQLITE_INTEGER, /* 0x04 */
67674 SQLITE_NULL, /* 0x05 */
67675 SQLITE_INTEGER, /* 0x06 */
67676 SQLITE_NULL, /* 0x07 */
67677 SQLITE_FLOAT, /* 0x08 */
67678 SQLITE_NULL, /* 0x09 */
67679 SQLITE_FLOAT, /* 0x0a */
67680 SQLITE_NULL, /* 0x0b */
67681 SQLITE_INTEGER, /* 0x0c */
67682 SQLITE_NULL, /* 0x0d */
67683 SQLITE_INTEGER, /* 0x0e */
67684 SQLITE_NULL, /* 0x0f */
67685 SQLITE_BLOB, /* 0x10 */
67686 SQLITE_NULL, /* 0x11 */
67687 SQLITE_TEXT, /* 0x12 */
67688 SQLITE_NULL, /* 0x13 */
67689 SQLITE_INTEGER, /* 0x14 */
67690 SQLITE_NULL, /* 0x15 */
67691 SQLITE_INTEGER, /* 0x16 */
67692 SQLITE_NULL, /* 0x17 */
67693 SQLITE_FLOAT, /* 0x18 */
67694 SQLITE_NULL, /* 0x19 */
67695 SQLITE_FLOAT, /* 0x1a */
67696 SQLITE_NULL, /* 0x1b */
67697 SQLITE_INTEGER, /* 0x1c */
67698 SQLITE_NULL, /* 0x1d */
67699 SQLITE_INTEGER, /* 0x1e */
67700 SQLITE_NULL, /* 0x1f */
67702 return aType[pVal->flags&MEM_AffMask];
67705 /**************************** sqlite3_result_ *******************************
67706 ** The following routines are used by user-defined functions to specify
67707 ** the function result.
67709 ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
67710 ** result as a string or blob but if the string or blob is too large, it
67711 ** then sets the error code to SQLITE_TOOBIG
67713 ** The invokeValueDestructor(P,X) routine invokes destructor function X()
67714 ** on value P is not going to be used and need to be destroyed.
67716 static void setResultStrOrError(
67717 sqlite3_context *pCtx, /* Function context */
67718 const char *z, /* String pointer */
67719 int n, /* Bytes in string, or negative */
67720 u8 enc, /* Encoding of z. 0 for BLOBs */
67721 void (*xDel)(void*) /* Destructor function */
67723 if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
67724 sqlite3_result_error_toobig(pCtx);
67727 static int invokeValueDestructor(
67728 const void *p, /* Value to destroy */
67729 void (*xDel)(void*), /* The destructor */
67730 sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
67732 assert( xDel!=SQLITE_DYNAMIC );
67733 if( xDel==0 ){
67734 /* noop */
67735 }else if( xDel==SQLITE_TRANSIENT ){
67736 /* noop */
67737 }else{
67738 xDel((void*)p);
67740 if( pCtx ) sqlite3_result_error_toobig(pCtx);
67741 return SQLITE_TOOBIG;
67743 SQLITE_API void sqlite3_result_blob(
67744 sqlite3_context *pCtx,
67745 const void *z,
67746 int n,
67747 void (*xDel)(void *)
67749 assert( n>=0 );
67750 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67751 setResultStrOrError(pCtx, z, n, 0, xDel);
67753 SQLITE_API void sqlite3_result_blob64(
67754 sqlite3_context *pCtx,
67755 const void *z,
67756 sqlite3_uint64 n,
67757 void (*xDel)(void *)
67759 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67760 assert( xDel!=SQLITE_DYNAMIC );
67761 if( n>0x7fffffff ){
67762 (void)invokeValueDestructor(z, xDel, pCtx);
67763 }else{
67764 setResultStrOrError(pCtx, z, (int)n, 0, xDel);
67767 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
67768 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67769 sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
67771 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
67772 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67773 pCtx->isError = SQLITE_ERROR;
67774 pCtx->fErrorOrAux = 1;
67775 sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
67777 #ifndef SQLITE_OMIT_UTF16
67778 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
67779 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67780 pCtx->isError = SQLITE_ERROR;
67781 pCtx->fErrorOrAux = 1;
67782 sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
67784 #endif
67785 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
67786 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67787 sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
67789 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
67790 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67791 sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
67793 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
67794 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67795 sqlite3VdbeMemSetNull(pCtx->pOut);
67797 SQLITE_API void sqlite3_result_text(
67798 sqlite3_context *pCtx,
67799 const char *z,
67800 int n,
67801 void (*xDel)(void *)
67803 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67804 setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
67806 SQLITE_API void sqlite3_result_text64(
67807 sqlite3_context *pCtx,
67808 const char *z,
67809 sqlite3_uint64 n,
67810 void (*xDel)(void *),
67811 unsigned char enc
67813 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67814 assert( xDel!=SQLITE_DYNAMIC );
67815 if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
67816 if( n>0x7fffffff ){
67817 (void)invokeValueDestructor(z, xDel, pCtx);
67818 }else{
67819 setResultStrOrError(pCtx, z, (int)n, enc, xDel);
67822 #ifndef SQLITE_OMIT_UTF16
67823 SQLITE_API void sqlite3_result_text16(
67824 sqlite3_context *pCtx,
67825 const void *z,
67826 int n,
67827 void (*xDel)(void *)
67829 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67830 setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
67832 SQLITE_API void sqlite3_result_text16be(
67833 sqlite3_context *pCtx,
67834 const void *z,
67835 int n,
67836 void (*xDel)(void *)
67838 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67839 setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
67841 SQLITE_API void sqlite3_result_text16le(
67842 sqlite3_context *pCtx,
67843 const void *z,
67844 int n,
67845 void (*xDel)(void *)
67847 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67848 setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
67850 #endif /* SQLITE_OMIT_UTF16 */
67851 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
67852 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67853 sqlite3VdbeMemCopy(pCtx->pOut, pValue);
67855 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
67856 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67857 sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
67859 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
67860 pCtx->isError = errCode;
67861 pCtx->fErrorOrAux = 1;
67862 if( pCtx->pOut->flags & MEM_Null ){
67863 sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
67864 SQLITE_UTF8, SQLITE_STATIC);
67868 /* Force an SQLITE_TOOBIG error. */
67869 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
67870 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67871 pCtx->isError = SQLITE_TOOBIG;
67872 pCtx->fErrorOrAux = 1;
67873 sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
67874 SQLITE_UTF8, SQLITE_STATIC);
67877 /* An SQLITE_NOMEM error. */
67878 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
67879 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67880 sqlite3VdbeMemSetNull(pCtx->pOut);
67881 pCtx->isError = SQLITE_NOMEM;
67882 pCtx->fErrorOrAux = 1;
67883 pCtx->pOut->db->mallocFailed = 1;
67887 ** This function is called after a transaction has been committed. It
67888 ** invokes callbacks registered with sqlite3_wal_hook() as required.
67890 static int doWalCallbacks(sqlite3 *db){
67891 int rc = SQLITE_OK;
67892 #ifndef SQLITE_OMIT_WAL
67893 int i;
67894 for(i=0; i<db->nDb; i++){
67895 Btree *pBt = db->aDb[i].pBt;
67896 if( pBt ){
67897 int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
67898 if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
67899 rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
67903 #endif
67904 return rc;
67908 ** Execute the statement pStmt, either until a row of data is ready, the
67909 ** statement is completely executed or an error occurs.
67911 ** This routine implements the bulk of the logic behind the sqlite_step()
67912 ** API. The only thing omitted is the automatic recompile if a
67913 ** schema change has occurred. That detail is handled by the
67914 ** outer sqlite3_step() wrapper procedure.
67916 static int sqlite3Step(Vdbe *p){
67917 sqlite3 *db;
67918 int rc;
67920 assert(p);
67921 if( p->magic!=VDBE_MAGIC_RUN ){
67922 /* We used to require that sqlite3_reset() be called before retrying
67923 ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
67924 ** with version 3.7.0, we changed this so that sqlite3_reset() would
67925 ** be called automatically instead of throwing the SQLITE_MISUSE error.
67926 ** This "automatic-reset" change is not technically an incompatibility,
67927 ** since any application that receives an SQLITE_MISUSE is broken by
67928 ** definition.
67930 ** Nevertheless, some published applications that were originally written
67931 ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
67932 ** returns, and those were broken by the automatic-reset change. As a
67933 ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
67934 ** legacy behavior of returning SQLITE_MISUSE for cases where the
67935 ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
67936 ** or SQLITE_BUSY error.
67938 #ifdef SQLITE_OMIT_AUTORESET
67939 if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
67940 sqlite3_reset((sqlite3_stmt*)p);
67941 }else{
67942 return SQLITE_MISUSE_BKPT;
67944 #else
67945 sqlite3_reset((sqlite3_stmt*)p);
67946 #endif
67949 /* Check that malloc() has not failed. If it has, return early. */
67950 db = p->db;
67951 if( db->mallocFailed ){
67952 p->rc = SQLITE_NOMEM;
67953 return SQLITE_NOMEM;
67956 if( p->pc<=0 && p->expired ){
67957 p->rc = SQLITE_SCHEMA;
67958 rc = SQLITE_ERROR;
67959 goto end_of_step;
67961 if( p->pc<0 ){
67962 /* If there are no other statements currently running, then
67963 ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
67964 ** from interrupting a statement that has not yet started.
67966 if( db->nVdbeActive==0 ){
67967 db->u1.isInterrupted = 0;
67970 assert( db->nVdbeWrite>0 || db->autoCommit==0
67971 || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
67974 #ifndef SQLITE_OMIT_TRACE
67975 if( db->xProfile && !db->init.busy ){
67976 sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
67978 #endif
67980 db->nVdbeActive++;
67981 if( p->readOnly==0 ) db->nVdbeWrite++;
67982 if( p->bIsReader ) db->nVdbeRead++;
67983 p->pc = 0;
67985 #ifndef SQLITE_OMIT_EXPLAIN
67986 if( p->explain ){
67987 rc = sqlite3VdbeList(p);
67988 }else
67989 #endif /* SQLITE_OMIT_EXPLAIN */
67991 db->nVdbeExec++;
67992 rc = sqlite3VdbeExec(p);
67993 db->nVdbeExec--;
67996 #ifndef SQLITE_OMIT_TRACE
67997 /* Invoke the profile callback if there is one
67999 if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
68000 sqlite3_int64 iNow;
68001 sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
68002 db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
68004 #endif
68006 if( rc==SQLITE_DONE ){
68007 assert( p->rc==SQLITE_OK );
68008 p->rc = doWalCallbacks(db);
68009 if( p->rc!=SQLITE_OK ){
68010 rc = SQLITE_ERROR;
68014 db->errCode = rc;
68015 if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
68016 p->rc = SQLITE_NOMEM;
68018 end_of_step:
68019 /* At this point local variable rc holds the value that should be
68020 ** returned if this statement was compiled using the legacy
68021 ** sqlite3_prepare() interface. According to the docs, this can only
68022 ** be one of the values in the first assert() below. Variable p->rc
68023 ** contains the value that would be returned if sqlite3_finalize()
68024 ** were called on statement p.
68026 assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
68027 || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
68029 assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
68030 if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
68031 /* If this statement was prepared using sqlite3_prepare_v2(), and an
68032 ** error has occurred, then return the error code in p->rc to the
68033 ** caller. Set the error code in the database handle to the same value.
68035 rc = sqlite3VdbeTransferError(p);
68037 return (rc&db->errMask);
68041 ** This is the top-level implementation of sqlite3_step(). Call
68042 ** sqlite3Step() to do most of the work. If a schema error occurs,
68043 ** call sqlite3Reprepare() and try again.
68045 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
68046 int rc = SQLITE_OK; /* Result from sqlite3Step() */
68047 int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
68048 Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
68049 int cnt = 0; /* Counter to prevent infinite loop of reprepares */
68050 sqlite3 *db; /* The database connection */
68052 if( vdbeSafetyNotNull(v) ){
68053 return SQLITE_MISUSE_BKPT;
68055 db = v->db;
68056 sqlite3_mutex_enter(db->mutex);
68057 v->doingRerun = 0;
68058 while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
68059 && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
68060 int savedPc = v->pc;
68061 rc2 = rc = sqlite3Reprepare(v);
68062 if( rc!=SQLITE_OK) break;
68063 sqlite3_reset(pStmt);
68064 if( savedPc>=0 ) v->doingRerun = 1;
68065 assert( v->expired==0 );
68067 if( rc2!=SQLITE_OK ){
68068 /* This case occurs after failing to recompile an sql statement.
68069 ** The error message from the SQL compiler has already been loaded
68070 ** into the database handle. This block copies the error message
68071 ** from the database handle into the statement and sets the statement
68072 ** program counter to 0 to ensure that when the statement is
68073 ** finalized or reset the parser error message is available via
68074 ** sqlite3_errmsg() and sqlite3_errcode().
68076 const char *zErr = (const char *)sqlite3_value_text(db->pErr);
68077 assert( zErr!=0 || db->mallocFailed );
68078 sqlite3DbFree(db, v->zErrMsg);
68079 if( !db->mallocFailed ){
68080 v->zErrMsg = sqlite3DbStrDup(db, zErr);
68081 v->rc = rc2;
68082 } else {
68083 v->zErrMsg = 0;
68084 v->rc = rc = SQLITE_NOMEM;
68087 rc = sqlite3ApiExit(db, rc);
68088 sqlite3_mutex_leave(db->mutex);
68089 return rc;
68094 ** Extract the user data from a sqlite3_context structure and return a
68095 ** pointer to it.
68097 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
68098 assert( p && p->pFunc );
68099 return p->pFunc->pUserData;
68103 ** Extract the user data from a sqlite3_context structure and return a
68104 ** pointer to it.
68106 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
68107 ** returns a copy of the pointer to the database connection (the 1st
68108 ** parameter) of the sqlite3_create_function() and
68109 ** sqlite3_create_function16() routines that originally registered the
68110 ** application defined function.
68112 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
68113 assert( p && p->pFunc );
68114 return p->pOut->db;
68118 ** Return the current time for a statement
68120 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
68121 Vdbe *v = p->pVdbe;
68122 int rc;
68123 if( v->iCurrentTime==0 ){
68124 rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, &v->iCurrentTime);
68125 if( rc ) v->iCurrentTime = 0;
68127 return v->iCurrentTime;
68131 ** The following is the implementation of an SQL function that always
68132 ** fails with an error message stating that the function is used in the
68133 ** wrong context. The sqlite3_overload_function() API might construct
68134 ** SQL function that use this routine so that the functions will exist
68135 ** for name resolution but are actually overloaded by the xFindFunction
68136 ** method of virtual tables.
68138 SQLITE_PRIVATE void sqlite3InvalidFunction(
68139 sqlite3_context *context, /* The function calling context */
68140 int NotUsed, /* Number of arguments to the function */
68141 sqlite3_value **NotUsed2 /* Value of each argument */
68143 const char *zName = context->pFunc->zName;
68144 char *zErr;
68145 UNUSED_PARAMETER2(NotUsed, NotUsed2);
68146 zErr = sqlite3_mprintf(
68147 "unable to use function %s in the requested context", zName);
68148 sqlite3_result_error(context, zErr, -1);
68149 sqlite3_free(zErr);
68153 ** Create a new aggregate context for p and return a pointer to
68154 ** its pMem->z element.
68156 static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
68157 Mem *pMem = p->pMem;
68158 assert( (pMem->flags & MEM_Agg)==0 );
68159 if( nByte<=0 ){
68160 sqlite3VdbeMemSetNull(pMem);
68161 pMem->z = 0;
68162 }else{
68163 sqlite3VdbeMemClearAndResize(pMem, nByte);
68164 pMem->flags = MEM_Agg;
68165 pMem->u.pDef = p->pFunc;
68166 if( pMem->z ){
68167 memset(pMem->z, 0, nByte);
68170 return (void*)pMem->z;
68174 ** Allocate or return the aggregate context for a user function. A new
68175 ** context is allocated on the first call. Subsequent calls return the
68176 ** same context that was returned on prior calls.
68178 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
68179 assert( p && p->pFunc && p->pFunc->xStep );
68180 assert( sqlite3_mutex_held(p->pOut->db->mutex) );
68181 testcase( nByte<0 );
68182 if( (p->pMem->flags & MEM_Agg)==0 ){
68183 return createAggContext(p, nByte);
68184 }else{
68185 return (void*)p->pMem->z;
68190 ** Return the auxiliary data pointer, if any, for the iArg'th argument to
68191 ** the user-function defined by pCtx.
68193 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
68194 AuxData *pAuxData;
68196 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
68197 for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
68198 if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
68201 return (pAuxData ? pAuxData->pAux : 0);
68205 ** Set the auxiliary data pointer and delete function, for the iArg'th
68206 ** argument to the user-function defined by pCtx. Any previous value is
68207 ** deleted by calling the delete function specified when it was set.
68209 SQLITE_API void sqlite3_set_auxdata(
68210 sqlite3_context *pCtx,
68211 int iArg,
68212 void *pAux,
68213 void (*xDelete)(void*)
68215 AuxData *pAuxData;
68216 Vdbe *pVdbe = pCtx->pVdbe;
68218 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
68219 if( iArg<0 ) goto failed;
68221 for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
68222 if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
68224 if( pAuxData==0 ){
68225 pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
68226 if( !pAuxData ) goto failed;
68227 pAuxData->iOp = pCtx->iOp;
68228 pAuxData->iArg = iArg;
68229 pAuxData->pNext = pVdbe->pAuxData;
68230 pVdbe->pAuxData = pAuxData;
68231 if( pCtx->fErrorOrAux==0 ){
68232 pCtx->isError = 0;
68233 pCtx->fErrorOrAux = 1;
68235 }else if( pAuxData->xDelete ){
68236 pAuxData->xDelete(pAuxData->pAux);
68239 pAuxData->pAux = pAux;
68240 pAuxData->xDelete = xDelete;
68241 return;
68243 failed:
68244 if( xDelete ){
68245 xDelete(pAux);
68249 #ifndef SQLITE_OMIT_DEPRECATED
68251 ** Return the number of times the Step function of an aggregate has been
68252 ** called.
68254 ** This function is deprecated. Do not use it for new code. It is
68255 ** provide only to avoid breaking legacy code. New aggregate function
68256 ** implementations should keep their own counts within their aggregate
68257 ** context.
68259 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
68260 assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
68261 return p->pMem->n;
68263 #endif
68266 ** Return the number of columns in the result set for the statement pStmt.
68268 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
68269 Vdbe *pVm = (Vdbe *)pStmt;
68270 return pVm ? pVm->nResColumn : 0;
68274 ** Return the number of values available from the current row of the
68275 ** currently executing statement pStmt.
68277 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
68278 Vdbe *pVm = (Vdbe *)pStmt;
68279 if( pVm==0 || pVm->pResultSet==0 ) return 0;
68280 return pVm->nResColumn;
68284 ** Return a pointer to static memory containing an SQL NULL value.
68286 static const Mem *columnNullValue(void){
68287 /* Even though the Mem structure contains an element
68288 ** of type i64, on certain architectures (x86) with certain compiler
68289 ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
68290 ** instead of an 8-byte one. This all works fine, except that when
68291 ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
68292 ** that a Mem structure is located on an 8-byte boundary. To prevent
68293 ** these assert()s from failing, when building with SQLITE_DEBUG defined
68294 ** using gcc, we force nullMem to be 8-byte aligned using the magical
68295 ** __attribute__((aligned(8))) macro. */
68296 static const Mem nullMem
68297 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
68298 __attribute__((aligned(8)))
68299 #endif
68301 /* .u = */ {0},
68302 /* .flags = */ MEM_Null,
68303 /* .enc = */ 0,
68304 /* .n = */ 0,
68305 /* .z = */ 0,
68306 /* .zMalloc = */ 0,
68307 /* .szMalloc = */ 0,
68308 /* .iPadding1 = */ 0,
68309 /* .db = */ 0,
68310 /* .xDel = */ 0,
68311 #ifdef SQLITE_DEBUG
68312 /* .pScopyFrom = */ 0,
68313 /* .pFiller = */ 0,
68314 #endif
68316 return &nullMem;
68320 ** Check to see if column iCol of the given statement is valid. If
68321 ** it is, return a pointer to the Mem for the value of that column.
68322 ** If iCol is not valid, return a pointer to a Mem which has a value
68323 ** of NULL.
68325 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
68326 Vdbe *pVm;
68327 Mem *pOut;
68329 pVm = (Vdbe *)pStmt;
68330 if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
68331 sqlite3_mutex_enter(pVm->db->mutex);
68332 pOut = &pVm->pResultSet[i];
68333 }else{
68334 if( pVm && ALWAYS(pVm->db) ){
68335 sqlite3_mutex_enter(pVm->db->mutex);
68336 sqlite3Error(pVm->db, SQLITE_RANGE);
68338 pOut = (Mem*)columnNullValue();
68340 return pOut;
68344 ** This function is called after invoking an sqlite3_value_XXX function on a
68345 ** column value (i.e. a value returned by evaluating an SQL expression in the
68346 ** select list of a SELECT statement) that may cause a malloc() failure. If
68347 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
68348 ** code of statement pStmt set to SQLITE_NOMEM.
68350 ** Specifically, this is called from within:
68352 ** sqlite3_column_int()
68353 ** sqlite3_column_int64()
68354 ** sqlite3_column_text()
68355 ** sqlite3_column_text16()
68356 ** sqlite3_column_real()
68357 ** sqlite3_column_bytes()
68358 ** sqlite3_column_bytes16()
68359 ** sqiite3_column_blob()
68361 static void columnMallocFailure(sqlite3_stmt *pStmt)
68363 /* If malloc() failed during an encoding conversion within an
68364 ** sqlite3_column_XXX API, then set the return code of the statement to
68365 ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
68366 ** and _finalize() will return NOMEM.
68368 Vdbe *p = (Vdbe *)pStmt;
68369 if( p ){
68370 p->rc = sqlite3ApiExit(p->db, p->rc);
68371 sqlite3_mutex_leave(p->db->mutex);
68375 /**************************** sqlite3_column_ *******************************
68376 ** The following routines are used to access elements of the current row
68377 ** in the result set.
68379 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
68380 const void *val;
68381 val = sqlite3_value_blob( columnMem(pStmt,i) );
68382 /* Even though there is no encoding conversion, value_blob() might
68383 ** need to call malloc() to expand the result of a zeroblob()
68384 ** expression.
68386 columnMallocFailure(pStmt);
68387 return val;
68389 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
68390 int val = sqlite3_value_bytes( columnMem(pStmt,i) );
68391 columnMallocFailure(pStmt);
68392 return val;
68394 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
68395 int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
68396 columnMallocFailure(pStmt);
68397 return val;
68399 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
68400 double val = sqlite3_value_double( columnMem(pStmt,i) );
68401 columnMallocFailure(pStmt);
68402 return val;
68404 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
68405 int val = sqlite3_value_int( columnMem(pStmt,i) );
68406 columnMallocFailure(pStmt);
68407 return val;
68409 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
68410 sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
68411 columnMallocFailure(pStmt);
68412 return val;
68414 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
68415 const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
68416 columnMallocFailure(pStmt);
68417 return val;
68419 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
68420 Mem *pOut = columnMem(pStmt, i);
68421 if( pOut->flags&MEM_Static ){
68422 pOut->flags &= ~MEM_Static;
68423 pOut->flags |= MEM_Ephem;
68425 columnMallocFailure(pStmt);
68426 return (sqlite3_value *)pOut;
68428 #ifndef SQLITE_OMIT_UTF16
68429 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
68430 const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
68431 columnMallocFailure(pStmt);
68432 return val;
68434 #endif /* SQLITE_OMIT_UTF16 */
68435 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
68436 int iType = sqlite3_value_type( columnMem(pStmt,i) );
68437 columnMallocFailure(pStmt);
68438 return iType;
68442 ** Convert the N-th element of pStmt->pColName[] into a string using
68443 ** xFunc() then return that string. If N is out of range, return 0.
68445 ** There are up to 5 names for each column. useType determines which
68446 ** name is returned. Here are the names:
68448 ** 0 The column name as it should be displayed for output
68449 ** 1 The datatype name for the column
68450 ** 2 The name of the database that the column derives from
68451 ** 3 The name of the table that the column derives from
68452 ** 4 The name of the table column that the result column derives from
68454 ** If the result is not a simple column reference (if it is an expression
68455 ** or a constant) then useTypes 2, 3, and 4 return NULL.
68457 static const void *columnName(
68458 sqlite3_stmt *pStmt,
68459 int N,
68460 const void *(*xFunc)(Mem*),
68461 int useType
68463 const void *ret = 0;
68464 Vdbe *p = (Vdbe *)pStmt;
68465 int n;
68466 sqlite3 *db = p->db;
68468 assert( db!=0 );
68469 n = sqlite3_column_count(pStmt);
68470 if( N<n && N>=0 ){
68471 N += useType*n;
68472 sqlite3_mutex_enter(db->mutex);
68473 assert( db->mallocFailed==0 );
68474 ret = xFunc(&p->aColName[N]);
68475 /* A malloc may have failed inside of the xFunc() call. If this
68476 ** is the case, clear the mallocFailed flag and return NULL.
68478 if( db->mallocFailed ){
68479 db->mallocFailed = 0;
68480 ret = 0;
68482 sqlite3_mutex_leave(db->mutex);
68484 return ret;
68488 ** Return the name of the Nth column of the result set returned by SQL
68489 ** statement pStmt.
68491 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
68492 return columnName(
68493 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
68495 #ifndef SQLITE_OMIT_UTF16
68496 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
68497 return columnName(
68498 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
68500 #endif
68503 ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
68504 ** not define OMIT_DECLTYPE.
68506 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
68507 # error "Must not define both SQLITE_OMIT_DECLTYPE \
68508 and SQLITE_ENABLE_COLUMN_METADATA"
68509 #endif
68511 #ifndef SQLITE_OMIT_DECLTYPE
68513 ** Return the column declaration type (if applicable) of the 'i'th column
68514 ** of the result set of SQL statement pStmt.
68516 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
68517 return columnName(
68518 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
68520 #ifndef SQLITE_OMIT_UTF16
68521 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
68522 return columnName(
68523 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
68525 #endif /* SQLITE_OMIT_UTF16 */
68526 #endif /* SQLITE_OMIT_DECLTYPE */
68528 #ifdef SQLITE_ENABLE_COLUMN_METADATA
68530 ** Return the name of the database from which a result column derives.
68531 ** NULL is returned if the result column is an expression or constant or
68532 ** anything else which is not an unambiguous reference to a database column.
68534 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
68535 return columnName(
68536 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
68538 #ifndef SQLITE_OMIT_UTF16
68539 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
68540 return columnName(
68541 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
68543 #endif /* SQLITE_OMIT_UTF16 */
68546 ** Return the name of the table from which a result column derives.
68547 ** NULL is returned if the result column is an expression or constant or
68548 ** anything else which is not an unambiguous reference to a database column.
68550 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
68551 return columnName(
68552 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
68554 #ifndef SQLITE_OMIT_UTF16
68555 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
68556 return columnName(
68557 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
68559 #endif /* SQLITE_OMIT_UTF16 */
68562 ** Return the name of the table column from which a result column derives.
68563 ** NULL is returned if the result column is an expression or constant or
68564 ** anything else which is not an unambiguous reference to a database column.
68566 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
68567 return columnName(
68568 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
68570 #ifndef SQLITE_OMIT_UTF16
68571 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
68572 return columnName(
68573 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
68575 #endif /* SQLITE_OMIT_UTF16 */
68576 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
68579 /******************************* sqlite3_bind_ ***************************
68581 ** Routines used to attach values to wildcards in a compiled SQL statement.
68584 ** Unbind the value bound to variable i in virtual machine p. This is the
68585 ** the same as binding a NULL value to the column. If the "i" parameter is
68586 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
68588 ** A successful evaluation of this routine acquires the mutex on p.
68589 ** the mutex is released if any kind of error occurs.
68591 ** The error code stored in database p->db is overwritten with the return
68592 ** value in any case.
68594 static int vdbeUnbind(Vdbe *p, int i){
68595 Mem *pVar;
68596 if( vdbeSafetyNotNull(p) ){
68597 return SQLITE_MISUSE_BKPT;
68599 sqlite3_mutex_enter(p->db->mutex);
68600 if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
68601 sqlite3Error(p->db, SQLITE_MISUSE);
68602 sqlite3_mutex_leave(p->db->mutex);
68603 sqlite3_log(SQLITE_MISUSE,
68604 "bind on a busy prepared statement: [%s]", p->zSql);
68605 return SQLITE_MISUSE_BKPT;
68607 if( i<1 || i>p->nVar ){
68608 sqlite3Error(p->db, SQLITE_RANGE);
68609 sqlite3_mutex_leave(p->db->mutex);
68610 return SQLITE_RANGE;
68612 i--;
68613 pVar = &p->aVar[i];
68614 sqlite3VdbeMemRelease(pVar);
68615 pVar->flags = MEM_Null;
68616 sqlite3Error(p->db, SQLITE_OK);
68618 /* If the bit corresponding to this variable in Vdbe.expmask is set, then
68619 ** binding a new value to this variable invalidates the current query plan.
68621 ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
68622 ** parameter in the WHERE clause might influence the choice of query plan
68623 ** for a statement, then the statement will be automatically recompiled,
68624 ** as if there had been a schema change, on the first sqlite3_step() call
68625 ** following any change to the bindings of that parameter.
68627 if( p->isPrepareV2 &&
68628 ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
68630 p->expired = 1;
68632 return SQLITE_OK;
68636 ** Bind a text or BLOB value.
68638 static int bindText(
68639 sqlite3_stmt *pStmt, /* The statement to bind against */
68640 int i, /* Index of the parameter to bind */
68641 const void *zData, /* Pointer to the data to be bound */
68642 int nData, /* Number of bytes of data to be bound */
68643 void (*xDel)(void*), /* Destructor for the data */
68644 u8 encoding /* Encoding for the data */
68646 Vdbe *p = (Vdbe *)pStmt;
68647 Mem *pVar;
68648 int rc;
68650 rc = vdbeUnbind(p, i);
68651 if( rc==SQLITE_OK ){
68652 if( zData!=0 ){
68653 pVar = &p->aVar[i-1];
68654 rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
68655 if( rc==SQLITE_OK && encoding!=0 ){
68656 rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
68658 sqlite3Error(p->db, rc);
68659 rc = sqlite3ApiExit(p->db, rc);
68661 sqlite3_mutex_leave(p->db->mutex);
68662 }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
68663 xDel((void*)zData);
68665 return rc;
68670 ** Bind a blob value to an SQL statement variable.
68672 SQLITE_API int sqlite3_bind_blob(
68673 sqlite3_stmt *pStmt,
68674 int i,
68675 const void *zData,
68676 int nData,
68677 void (*xDel)(void*)
68679 return bindText(pStmt, i, zData, nData, xDel, 0);
68681 SQLITE_API int sqlite3_bind_blob64(
68682 sqlite3_stmt *pStmt,
68683 int i,
68684 const void *zData,
68685 sqlite3_uint64 nData,
68686 void (*xDel)(void*)
68688 assert( xDel!=SQLITE_DYNAMIC );
68689 if( nData>0x7fffffff ){
68690 return invokeValueDestructor(zData, xDel, 0);
68691 }else{
68692 return bindText(pStmt, i, zData, (int)nData, xDel, 0);
68695 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
68696 int rc;
68697 Vdbe *p = (Vdbe *)pStmt;
68698 rc = vdbeUnbind(p, i);
68699 if( rc==SQLITE_OK ){
68700 sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
68701 sqlite3_mutex_leave(p->db->mutex);
68703 return rc;
68705 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
68706 return sqlite3_bind_int64(p, i, (i64)iValue);
68708 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
68709 int rc;
68710 Vdbe *p = (Vdbe *)pStmt;
68711 rc = vdbeUnbind(p, i);
68712 if( rc==SQLITE_OK ){
68713 sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
68714 sqlite3_mutex_leave(p->db->mutex);
68716 return rc;
68718 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
68719 int rc;
68720 Vdbe *p = (Vdbe*)pStmt;
68721 rc = vdbeUnbind(p, i);
68722 if( rc==SQLITE_OK ){
68723 sqlite3_mutex_leave(p->db->mutex);
68725 return rc;
68727 SQLITE_API int sqlite3_bind_text(
68728 sqlite3_stmt *pStmt,
68729 int i,
68730 const char *zData,
68731 int nData,
68732 void (*xDel)(void*)
68734 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
68736 SQLITE_API int sqlite3_bind_text64(
68737 sqlite3_stmt *pStmt,
68738 int i,
68739 const char *zData,
68740 sqlite3_uint64 nData,
68741 void (*xDel)(void*),
68742 unsigned char enc
68744 assert( xDel!=SQLITE_DYNAMIC );
68745 if( nData>0x7fffffff ){
68746 return invokeValueDestructor(zData, xDel, 0);
68747 }else{
68748 if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
68749 return bindText(pStmt, i, zData, (int)nData, xDel, enc);
68752 #ifndef SQLITE_OMIT_UTF16
68753 SQLITE_API int sqlite3_bind_text16(
68754 sqlite3_stmt *pStmt,
68755 int i,
68756 const void *zData,
68757 int nData,
68758 void (*xDel)(void*)
68760 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
68762 #endif /* SQLITE_OMIT_UTF16 */
68763 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
68764 int rc;
68765 switch( sqlite3_value_type((sqlite3_value*)pValue) ){
68766 case SQLITE_INTEGER: {
68767 rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
68768 break;
68770 case SQLITE_FLOAT: {
68771 rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
68772 break;
68774 case SQLITE_BLOB: {
68775 if( pValue->flags & MEM_Zero ){
68776 rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
68777 }else{
68778 rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
68780 break;
68782 case SQLITE_TEXT: {
68783 rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
68784 pValue->enc);
68785 break;
68787 default: {
68788 rc = sqlite3_bind_null(pStmt, i);
68789 break;
68792 return rc;
68794 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
68795 int rc;
68796 Vdbe *p = (Vdbe *)pStmt;
68797 rc = vdbeUnbind(p, i);
68798 if( rc==SQLITE_OK ){
68799 sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
68800 sqlite3_mutex_leave(p->db->mutex);
68802 return rc;
68806 ** Return the number of wildcards that can be potentially bound to.
68807 ** This routine is added to support DBD::SQLite.
68809 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
68810 Vdbe *p = (Vdbe*)pStmt;
68811 return p ? p->nVar : 0;
68815 ** Return the name of a wildcard parameter. Return NULL if the index
68816 ** is out of range or if the wildcard is unnamed.
68818 ** The result is always UTF-8.
68820 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
68821 Vdbe *p = (Vdbe*)pStmt;
68822 if( p==0 || i<1 || i>p->nzVar ){
68823 return 0;
68825 return p->azVar[i-1];
68829 ** Given a wildcard parameter name, return the index of the variable
68830 ** with that name. If there is no variable with the given name,
68831 ** return 0.
68833 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
68834 int i;
68835 if( p==0 ){
68836 return 0;
68838 if( zName ){
68839 for(i=0; i<p->nzVar; i++){
68840 const char *z = p->azVar[i];
68841 if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
68842 return i+1;
68846 return 0;
68848 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
68849 return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
68853 ** Transfer all bindings from the first statement over to the second.
68855 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
68856 Vdbe *pFrom = (Vdbe*)pFromStmt;
68857 Vdbe *pTo = (Vdbe*)pToStmt;
68858 int i;
68859 assert( pTo->db==pFrom->db );
68860 assert( pTo->nVar==pFrom->nVar );
68861 sqlite3_mutex_enter(pTo->db->mutex);
68862 for(i=0; i<pFrom->nVar; i++){
68863 sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
68865 sqlite3_mutex_leave(pTo->db->mutex);
68866 return SQLITE_OK;
68869 #ifndef SQLITE_OMIT_DEPRECATED
68871 ** Deprecated external interface. Internal/core SQLite code
68872 ** should call sqlite3TransferBindings.
68874 ** It is misuse to call this routine with statements from different
68875 ** database connections. But as this is a deprecated interface, we
68876 ** will not bother to check for that condition.
68878 ** If the two statements contain a different number of bindings, then
68879 ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
68880 ** SQLITE_OK is returned.
68882 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
68883 Vdbe *pFrom = (Vdbe*)pFromStmt;
68884 Vdbe *pTo = (Vdbe*)pToStmt;
68885 if( pFrom->nVar!=pTo->nVar ){
68886 return SQLITE_ERROR;
68888 if( pTo->isPrepareV2 && pTo->expmask ){
68889 pTo->expired = 1;
68891 if( pFrom->isPrepareV2 && pFrom->expmask ){
68892 pFrom->expired = 1;
68894 return sqlite3TransferBindings(pFromStmt, pToStmt);
68896 #endif
68899 ** Return the sqlite3* database handle to which the prepared statement given
68900 ** in the argument belongs. This is the same database handle that was
68901 ** the first argument to the sqlite3_prepare() that was used to create
68902 ** the statement in the first place.
68904 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
68905 return pStmt ? ((Vdbe*)pStmt)->db : 0;
68909 ** Return true if the prepared statement is guaranteed to not modify the
68910 ** database.
68912 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
68913 return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
68917 ** Return true if the prepared statement is in need of being reset.
68919 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
68920 Vdbe *v = (Vdbe*)pStmt;
68921 return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
68925 ** Return a pointer to the next prepared statement after pStmt associated
68926 ** with database connection pDb. If pStmt is NULL, return the first
68927 ** prepared statement for the database connection. Return NULL if there
68928 ** are no more.
68930 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
68931 sqlite3_stmt *pNext;
68932 sqlite3_mutex_enter(pDb->mutex);
68933 if( pStmt==0 ){
68934 pNext = (sqlite3_stmt*)pDb->pVdbe;
68935 }else{
68936 pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
68938 sqlite3_mutex_leave(pDb->mutex);
68939 return pNext;
68943 ** Return the value of a status counter for a prepared statement
68945 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
68946 Vdbe *pVdbe = (Vdbe*)pStmt;
68947 u32 v = pVdbe->aCounter[op];
68948 if( resetFlag ) pVdbe->aCounter[op] = 0;
68949 return (int)v;
68952 /************** End of vdbeapi.c *********************************************/
68953 /************** Begin file vdbetrace.c ***************************************/
68955 ** 2009 November 25
68957 ** The author disclaims copyright to this source code. In place of
68958 ** a legal notice, here is a blessing:
68960 ** May you do good and not evil.
68961 ** May you find forgiveness for yourself and forgive others.
68962 ** May you share freely, never taking more than you give.
68964 *************************************************************************
68966 ** This file contains code used to insert the values of host parameters
68967 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
68969 ** The Vdbe parse-tree explainer is also found here.
68972 #ifndef SQLITE_OMIT_TRACE
68975 ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
68976 ** bytes in this text up to but excluding the first character in
68977 ** a host parameter. If the text contains no host parameters, return
68978 ** the total number of bytes in the text.
68980 static int findNextHostParameter(const char *zSql, int *pnToken){
68981 int tokenType;
68982 int nTotal = 0;
68983 int n;
68985 *pnToken = 0;
68986 while( zSql[0] ){
68987 n = sqlite3GetToken((u8*)zSql, &tokenType);
68988 assert( n>0 && tokenType!=TK_ILLEGAL );
68989 if( tokenType==TK_VARIABLE ){
68990 *pnToken = n;
68991 break;
68993 nTotal += n;
68994 zSql += n;
68996 return nTotal;
69000 ** This function returns a pointer to a nul-terminated string in memory
69001 ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
69002 ** string contains a copy of zRawSql but with host parameters expanded to
69003 ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
69004 ** then the returned string holds a copy of zRawSql with "-- " prepended
69005 ** to each line of text.
69007 ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
69008 ** then long strings and blobs are truncated to that many bytes. This
69009 ** can be used to prevent unreasonably large trace strings when dealing
69010 ** with large (multi-megabyte) strings and blobs.
69012 ** The calling function is responsible for making sure the memory returned
69013 ** is eventually freed.
69015 ** ALGORITHM: Scan the input string looking for host parameters in any of
69016 ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
69017 ** string literals, quoted identifier names, and comments. For text forms,
69018 ** the host parameter index is found by scanning the prepared
69019 ** statement for the corresponding OP_Variable opcode. Once the host
69020 ** parameter index is known, locate the value in p->aVar[]. Then render
69021 ** the value as a literal in place of the host parameter name.
69023 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
69024 Vdbe *p, /* The prepared statement being evaluated */
69025 const char *zRawSql /* Raw text of the SQL statement */
69027 sqlite3 *db; /* The database connection */
69028 int idx = 0; /* Index of a host parameter */
69029 int nextIndex = 1; /* Index of next ? host parameter */
69030 int n; /* Length of a token prefix */
69031 int nToken; /* Length of the parameter token */
69032 int i; /* Loop counter */
69033 Mem *pVar; /* Value of a host parameter */
69034 StrAccum out; /* Accumulate the output here */
69035 char zBase[100]; /* Initial working space */
69037 db = p->db;
69038 sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
69039 db->aLimit[SQLITE_LIMIT_LENGTH]);
69040 out.db = db;
69041 if( db->nVdbeExec>1 ){
69042 while( *zRawSql ){
69043 const char *zStart = zRawSql;
69044 while( *(zRawSql++)!='\n' && *zRawSql );
69045 sqlite3StrAccumAppend(&out, "-- ", 3);
69046 assert( (zRawSql - zStart) > 0 );
69047 sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
69049 }else{
69050 while( zRawSql[0] ){
69051 n = findNextHostParameter(zRawSql, &nToken);
69052 assert( n>0 );
69053 sqlite3StrAccumAppend(&out, zRawSql, n);
69054 zRawSql += n;
69055 assert( zRawSql[0] || nToken==0 );
69056 if( nToken==0 ) break;
69057 if( zRawSql[0]=='?' ){
69058 if( nToken>1 ){
69059 assert( sqlite3Isdigit(zRawSql[1]) );
69060 sqlite3GetInt32(&zRawSql[1], &idx);
69061 }else{
69062 idx = nextIndex;
69064 }else{
69065 assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
69066 testcase( zRawSql[0]==':' );
69067 testcase( zRawSql[0]=='$' );
69068 testcase( zRawSql[0]=='@' );
69069 idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
69070 assert( idx>0 );
69072 zRawSql += nToken;
69073 nextIndex = idx + 1;
69074 assert( idx>0 && idx<=p->nVar );
69075 pVar = &p->aVar[idx-1];
69076 if( pVar->flags & MEM_Null ){
69077 sqlite3StrAccumAppend(&out, "NULL", 4);
69078 }else if( pVar->flags & MEM_Int ){
69079 sqlite3XPrintf(&out, 0, "%lld", pVar->u.i);
69080 }else if( pVar->flags & MEM_Real ){
69081 sqlite3XPrintf(&out, 0, "%!.15g", pVar->u.r);
69082 }else if( pVar->flags & MEM_Str ){
69083 int nOut; /* Number of bytes of the string text to include in output */
69084 #ifndef SQLITE_OMIT_UTF16
69085 u8 enc = ENC(db);
69086 Mem utf8;
69087 if( enc!=SQLITE_UTF8 ){
69088 memset(&utf8, 0, sizeof(utf8));
69089 utf8.db = db;
69090 sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
69091 sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
69092 pVar = &utf8;
69094 #endif
69095 nOut = pVar->n;
69096 #ifdef SQLITE_TRACE_SIZE_LIMIT
69097 if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
69098 nOut = SQLITE_TRACE_SIZE_LIMIT;
69099 while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
69101 #endif
69102 sqlite3XPrintf(&out, 0, "'%.*q'", nOut, pVar->z);
69103 #ifdef SQLITE_TRACE_SIZE_LIMIT
69104 if( nOut<pVar->n ){
69105 sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
69107 #endif
69108 #ifndef SQLITE_OMIT_UTF16
69109 if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
69110 #endif
69111 }else if( pVar->flags & MEM_Zero ){
69112 sqlite3XPrintf(&out, 0, "zeroblob(%d)", pVar->u.nZero);
69113 }else{
69114 int nOut; /* Number of bytes of the blob to include in output */
69115 assert( pVar->flags & MEM_Blob );
69116 sqlite3StrAccumAppend(&out, "x'", 2);
69117 nOut = pVar->n;
69118 #ifdef SQLITE_TRACE_SIZE_LIMIT
69119 if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
69120 #endif
69121 for(i=0; i<nOut; i++){
69122 sqlite3XPrintf(&out, 0, "%02x", pVar->z[i]&0xff);
69124 sqlite3StrAccumAppend(&out, "'", 1);
69125 #ifdef SQLITE_TRACE_SIZE_LIMIT
69126 if( nOut<pVar->n ){
69127 sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
69129 #endif
69133 return sqlite3StrAccumFinish(&out);
69136 #endif /* #ifndef SQLITE_OMIT_TRACE */
69138 /************** End of vdbetrace.c *******************************************/
69139 /************** Begin file vdbe.c ********************************************/
69141 ** 2001 September 15
69143 ** The author disclaims copyright to this source code. In place of
69144 ** a legal notice, here is a blessing:
69146 ** May you do good and not evil.
69147 ** May you find forgiveness for yourself and forgive others.
69148 ** May you share freely, never taking more than you give.
69150 *************************************************************************
69151 ** The code in this file implements the function that runs the
69152 ** bytecode of a prepared statement.
69154 ** Various scripts scan this source file in order to generate HTML
69155 ** documentation, headers files, or other derived files. The formatting
69156 ** of the code in this file is, therefore, important. See other comments
69157 ** in this file for details. If in doubt, do not deviate from existing
69158 ** commenting and indentation practices when changing or adding code.
69162 ** Invoke this macro on memory cells just prior to changing the
69163 ** value of the cell. This macro verifies that shallow copies are
69164 ** not misused. A shallow copy of a string or blob just copies a
69165 ** pointer to the string or blob, not the content. If the original
69166 ** is changed while the copy is still in use, the string or blob might
69167 ** be changed out from under the copy. This macro verifies that nothing
69168 ** like that ever happens.
69170 #ifdef SQLITE_DEBUG
69171 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
69172 #else
69173 # define memAboutToChange(P,M)
69174 #endif
69177 ** The following global variable is incremented every time a cursor
69178 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
69179 ** procedures use this information to make sure that indices are
69180 ** working correctly. This variable has no function other than to
69181 ** help verify the correct operation of the library.
69183 #ifdef SQLITE_TEST
69184 SQLITE_API int sqlite3_search_count = 0;
69185 #endif
69188 ** When this global variable is positive, it gets decremented once before
69189 ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
69190 ** field of the sqlite3 structure is set in order to simulate an interrupt.
69192 ** This facility is used for testing purposes only. It does not function
69193 ** in an ordinary build.
69195 #ifdef SQLITE_TEST
69196 SQLITE_API int sqlite3_interrupt_count = 0;
69197 #endif
69200 ** The next global variable is incremented each type the OP_Sort opcode
69201 ** is executed. The test procedures use this information to make sure that
69202 ** sorting is occurring or not occurring at appropriate times. This variable
69203 ** has no function other than to help verify the correct operation of the
69204 ** library.
69206 #ifdef SQLITE_TEST
69207 SQLITE_API int sqlite3_sort_count = 0;
69208 #endif
69211 ** The next global variable records the size of the largest MEM_Blob
69212 ** or MEM_Str that has been used by a VDBE opcode. The test procedures
69213 ** use this information to make sure that the zero-blob functionality
69214 ** is working correctly. This variable has no function other than to
69215 ** help verify the correct operation of the library.
69217 #ifdef SQLITE_TEST
69218 SQLITE_API int sqlite3_max_blobsize = 0;
69219 static void updateMaxBlobsize(Mem *p){
69220 if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
69221 sqlite3_max_blobsize = p->n;
69224 #endif
69227 ** The next global variable is incremented each time the OP_Found opcode
69228 ** is executed. This is used to test whether or not the foreign key
69229 ** operation implemented using OP_FkIsZero is working. This variable
69230 ** has no function other than to help verify the correct operation of the
69231 ** library.
69233 #ifdef SQLITE_TEST
69234 SQLITE_API int sqlite3_found_count = 0;
69235 #endif
69238 ** Test a register to see if it exceeds the current maximum blob size.
69239 ** If it does, record the new maximum blob size.
69241 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
69242 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
69243 #else
69244 # define UPDATE_MAX_BLOBSIZE(P)
69245 #endif
69248 ** Invoke the VDBE coverage callback, if that callback is defined. This
69249 ** feature is used for test suite validation only and does not appear an
69250 ** production builds.
69252 ** M is an integer, 2 or 3, that indices how many different ways the
69253 ** branch can go. It is usually 2. "I" is the direction the branch
69254 ** goes. 0 means falls through. 1 means branch is taken. 2 means the
69255 ** second alternative branch is taken.
69257 ** iSrcLine is the source code line (from the __LINE__ macro) that
69258 ** generated the VDBE instruction. This instrumentation assumes that all
69259 ** source code is in a single file (the amalgamation). Special values 1
69260 ** and 2 for the iSrcLine parameter mean that this particular branch is
69261 ** always taken or never taken, respectively.
69263 #if !defined(SQLITE_VDBE_COVERAGE)
69264 # define VdbeBranchTaken(I,M)
69265 #else
69266 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
69267 static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
69268 if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
69269 M = iSrcLine;
69270 /* Assert the truth of VdbeCoverageAlwaysTaken() and
69271 ** VdbeCoverageNeverTaken() */
69272 assert( (M & I)==I );
69273 }else{
69274 if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
69275 sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
69276 iSrcLine,I,M);
69279 #endif
69282 ** Convert the given register into a string if it isn't one
69283 ** already. Return non-zero if a malloc() fails.
69285 #define Stringify(P, enc) \
69286 if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
69287 { goto no_mem; }
69290 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
69291 ** a pointer to a dynamically allocated string where some other entity
69292 ** is responsible for deallocating that string. Because the register
69293 ** does not control the string, it might be deleted without the register
69294 ** knowing it.
69296 ** This routine converts an ephemeral string into a dynamically allocated
69297 ** string that the register itself controls. In other words, it
69298 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
69300 #define Deephemeralize(P) \
69301 if( ((P)->flags&MEM_Ephem)!=0 \
69302 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
69304 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
69305 #define isSorter(x) ((x)->pSorter!=0)
69308 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
69309 ** if we run out of memory.
69311 static VdbeCursor *allocateCursor(
69312 Vdbe *p, /* The virtual machine */
69313 int iCur, /* Index of the new VdbeCursor */
69314 int nField, /* Number of fields in the table or index */
69315 int iDb, /* Database the cursor belongs to, or -1 */
69316 int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
69318 /* Find the memory cell that will be used to store the blob of memory
69319 ** required for this VdbeCursor structure. It is convenient to use a
69320 ** vdbe memory cell to manage the memory allocation required for a
69321 ** VdbeCursor structure for the following reasons:
69323 ** * Sometimes cursor numbers are used for a couple of different
69324 ** purposes in a vdbe program. The different uses might require
69325 ** different sized allocations. Memory cells provide growable
69326 ** allocations.
69328 ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
69329 ** be freed lazily via the sqlite3_release_memory() API. This
69330 ** minimizes the number of malloc calls made by the system.
69332 ** Memory cells for cursors are allocated at the top of the address
69333 ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
69334 ** cursor 1 is managed by memory cell (p->nMem-1), etc.
69336 Mem *pMem = &p->aMem[p->nMem-iCur];
69338 int nByte;
69339 VdbeCursor *pCx = 0;
69340 nByte =
69341 ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
69342 (isBtreeCursor?sqlite3BtreeCursorSize():0);
69344 assert( iCur<p->nCursor );
69345 if( p->apCsr[iCur] ){
69346 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
69347 p->apCsr[iCur] = 0;
69349 if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
69350 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
69351 memset(pCx, 0, sizeof(VdbeCursor));
69352 pCx->iDb = iDb;
69353 pCx->nField = nField;
69354 pCx->aOffset = &pCx->aType[nField];
69355 if( isBtreeCursor ){
69356 pCx->pCursor = (BtCursor*)
69357 &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
69358 sqlite3BtreeCursorZero(pCx->pCursor);
69361 return pCx;
69365 ** Try to convert a value into a numeric representation if we can
69366 ** do so without loss of information. In other words, if the string
69367 ** looks like a number, convert it into a number. If it does not
69368 ** look like a number, leave it alone.
69370 ** If the bTryForInt flag is true, then extra effort is made to give
69371 ** an integer representation. Strings that look like floating point
69372 ** values but which have no fractional component (example: '48.00')
69373 ** will have a MEM_Int representation when bTryForInt is true.
69375 ** If bTryForInt is false, then if the input string contains a decimal
69376 ** point or exponential notation, the result is only MEM_Real, even
69377 ** if there is an exact integer representation of the quantity.
69379 static void applyNumericAffinity(Mem *pRec, int bTryForInt){
69380 double rValue;
69381 i64 iValue;
69382 u8 enc = pRec->enc;
69383 assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
69384 if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
69385 if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
69386 pRec->u.i = iValue;
69387 pRec->flags |= MEM_Int;
69388 }else{
69389 pRec->u.r = rValue;
69390 pRec->flags |= MEM_Real;
69391 if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
69396 ** Processing is determine by the affinity parameter:
69398 ** SQLITE_AFF_INTEGER:
69399 ** SQLITE_AFF_REAL:
69400 ** SQLITE_AFF_NUMERIC:
69401 ** Try to convert pRec to an integer representation or a
69402 ** floating-point representation if an integer representation
69403 ** is not possible. Note that the integer representation is
69404 ** always preferred, even if the affinity is REAL, because
69405 ** an integer representation is more space efficient on disk.
69407 ** SQLITE_AFF_TEXT:
69408 ** Convert pRec to a text representation.
69410 ** SQLITE_AFF_NONE:
69411 ** No-op. pRec is unchanged.
69413 static void applyAffinity(
69414 Mem *pRec, /* The value to apply affinity to */
69415 char affinity, /* The affinity to be applied */
69416 u8 enc /* Use this text encoding */
69418 if( affinity>=SQLITE_AFF_NUMERIC ){
69419 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
69420 || affinity==SQLITE_AFF_NUMERIC );
69421 if( (pRec->flags & MEM_Int)==0 ){
69422 if( (pRec->flags & MEM_Real)==0 ){
69423 if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
69424 }else{
69425 sqlite3VdbeIntegerAffinity(pRec);
69428 }else if( affinity==SQLITE_AFF_TEXT ){
69429 /* Only attempt the conversion to TEXT if there is an integer or real
69430 ** representation (blob and NULL do not get converted) but no string
69431 ** representation.
69433 if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
69434 sqlite3VdbeMemStringify(pRec, enc, 1);
69440 ** Try to convert the type of a function argument or a result column
69441 ** into a numeric representation. Use either INTEGER or REAL whichever
69442 ** is appropriate. But only do the conversion if it is possible without
69443 ** loss of information and return the revised type of the argument.
69445 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
69446 int eType = sqlite3_value_type(pVal);
69447 if( eType==SQLITE_TEXT ){
69448 Mem *pMem = (Mem*)pVal;
69449 applyNumericAffinity(pMem, 0);
69450 eType = sqlite3_value_type(pVal);
69452 return eType;
69456 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
69457 ** not the internal Mem* type.
69459 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
69460 sqlite3_value *pVal,
69461 u8 affinity,
69462 u8 enc
69464 applyAffinity((Mem *)pVal, affinity, enc);
69468 ** pMem currently only holds a string type (or maybe a BLOB that we can
69469 ** interpret as a string if we want to). Compute its corresponding
69470 ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
69471 ** accordingly.
69473 static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
69474 assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
69475 assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
69476 if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
69477 return 0;
69479 if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
69480 return MEM_Int;
69482 return MEM_Real;
69486 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
69487 ** none.
69489 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
69490 ** But it does set pMem->u.r and pMem->u.i appropriately.
69492 static u16 numericType(Mem *pMem){
69493 if( pMem->flags & (MEM_Int|MEM_Real) ){
69494 return pMem->flags & (MEM_Int|MEM_Real);
69496 if( pMem->flags & (MEM_Str|MEM_Blob) ){
69497 return computeNumericType(pMem);
69499 return 0;
69502 #ifdef SQLITE_DEBUG
69504 ** Write a nice string representation of the contents of cell pMem
69505 ** into buffer zBuf, length nBuf.
69507 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
69508 char *zCsr = zBuf;
69509 int f = pMem->flags;
69511 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
69513 if( f&MEM_Blob ){
69514 int i;
69515 char c;
69516 if( f & MEM_Dyn ){
69517 c = 'z';
69518 assert( (f & (MEM_Static|MEM_Ephem))==0 );
69519 }else if( f & MEM_Static ){
69520 c = 't';
69521 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
69522 }else if( f & MEM_Ephem ){
69523 c = 'e';
69524 assert( (f & (MEM_Static|MEM_Dyn))==0 );
69525 }else{
69526 c = 's';
69529 sqlite3_snprintf(100, zCsr, "%c", c);
69530 zCsr += sqlite3Strlen30(zCsr);
69531 sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
69532 zCsr += sqlite3Strlen30(zCsr);
69533 for(i=0; i<16 && i<pMem->n; i++){
69534 sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
69535 zCsr += sqlite3Strlen30(zCsr);
69537 for(i=0; i<16 && i<pMem->n; i++){
69538 char z = pMem->z[i];
69539 if( z<32 || z>126 ) *zCsr++ = '.';
69540 else *zCsr++ = z;
69543 sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
69544 zCsr += sqlite3Strlen30(zCsr);
69545 if( f & MEM_Zero ){
69546 sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
69547 zCsr += sqlite3Strlen30(zCsr);
69549 *zCsr = '\0';
69550 }else if( f & MEM_Str ){
69551 int j, k;
69552 zBuf[0] = ' ';
69553 if( f & MEM_Dyn ){
69554 zBuf[1] = 'z';
69555 assert( (f & (MEM_Static|MEM_Ephem))==0 );
69556 }else if( f & MEM_Static ){
69557 zBuf[1] = 't';
69558 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
69559 }else if( f & MEM_Ephem ){
69560 zBuf[1] = 'e';
69561 assert( (f & (MEM_Static|MEM_Dyn))==0 );
69562 }else{
69563 zBuf[1] = 's';
69565 k = 2;
69566 sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
69567 k += sqlite3Strlen30(&zBuf[k]);
69568 zBuf[k++] = '[';
69569 for(j=0; j<15 && j<pMem->n; j++){
69570 u8 c = pMem->z[j];
69571 if( c>=0x20 && c<0x7f ){
69572 zBuf[k++] = c;
69573 }else{
69574 zBuf[k++] = '.';
69577 zBuf[k++] = ']';
69578 sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
69579 k += sqlite3Strlen30(&zBuf[k]);
69580 zBuf[k++] = 0;
69583 #endif
69585 #ifdef SQLITE_DEBUG
69587 ** Print the value of a register for tracing purposes:
69589 static void memTracePrint(Mem *p){
69590 if( p->flags & MEM_Undefined ){
69591 printf(" undefined");
69592 }else if( p->flags & MEM_Null ){
69593 printf(" NULL");
69594 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
69595 printf(" si:%lld", p->u.i);
69596 }else if( p->flags & MEM_Int ){
69597 printf(" i:%lld", p->u.i);
69598 #ifndef SQLITE_OMIT_FLOATING_POINT
69599 }else if( p->flags & MEM_Real ){
69600 printf(" r:%g", p->u.r);
69601 #endif
69602 }else if( p->flags & MEM_RowSet ){
69603 printf(" (rowset)");
69604 }else{
69605 char zBuf[200];
69606 sqlite3VdbeMemPrettyPrint(p, zBuf);
69607 printf(" %s", zBuf);
69610 static void registerTrace(int iReg, Mem *p){
69611 printf("REG[%d] = ", iReg);
69612 memTracePrint(p);
69613 printf("\n");
69615 #endif
69617 #ifdef SQLITE_DEBUG
69618 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
69619 #else
69620 # define REGISTER_TRACE(R,M)
69621 #endif
69624 #ifdef VDBE_PROFILE
69627 ** hwtime.h contains inline assembler code for implementing
69628 ** high-performance timing routines.
69630 /************** Include hwtime.h in the middle of vdbe.c *********************/
69631 /************** Begin file hwtime.h ******************************************/
69633 ** 2008 May 27
69635 ** The author disclaims copyright to this source code. In place of
69636 ** a legal notice, here is a blessing:
69638 ** May you do good and not evil.
69639 ** May you find forgiveness for yourself and forgive others.
69640 ** May you share freely, never taking more than you give.
69642 ******************************************************************************
69644 ** This file contains inline asm code for retrieving "high-performance"
69645 ** counters for x86 class CPUs.
69647 #ifndef _HWTIME_H_
69648 #define _HWTIME_H_
69651 ** The following routine only works on pentium-class (or newer) processors.
69652 ** It uses the RDTSC opcode to read the cycle count value out of the
69653 ** processor and returns that value. This can be used for high-res
69654 ** profiling.
69656 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
69657 (defined(i386) || defined(__i386__) || defined(_M_IX86))
69659 #if defined(__GNUC__)
69661 __inline__ sqlite_uint64 sqlite3Hwtime(void){
69662 unsigned int lo, hi;
69663 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
69664 return (sqlite_uint64)hi << 32 | lo;
69667 #elif defined(_MSC_VER)
69669 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
69670 __asm {
69671 rdtsc
69672 ret ; return value at EDX:EAX
69676 #endif
69678 #elif (defined(__GNUC__) && defined(__x86_64__))
69680 __inline__ sqlite_uint64 sqlite3Hwtime(void){
69681 unsigned long val;
69682 __asm__ __volatile__ ("rdtsc" : "=A" (val));
69683 return val;
69686 #elif (defined(__GNUC__) && defined(__ppc__))
69688 __inline__ sqlite_uint64 sqlite3Hwtime(void){
69689 unsigned long long retval;
69690 unsigned long junk;
69691 __asm__ __volatile__ ("\n\
69692 1: mftbu %1\n\
69693 mftb %L0\n\
69694 mftbu %0\n\
69695 cmpw %0,%1\n\
69696 bne 1b"
69697 : "=r" (retval), "=r" (junk));
69698 return retval;
69701 #else
69703 #error Need implementation of sqlite3Hwtime() for your platform.
69706 ** To compile without implementing sqlite3Hwtime() for your platform,
69707 ** you can remove the above #error and use the following
69708 ** stub function. You will lose timing support for many
69709 ** of the debugging and testing utilities, but it should at
69710 ** least compile and run.
69712 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
69714 #endif
69716 #endif /* !defined(_HWTIME_H_) */
69718 /************** End of hwtime.h **********************************************/
69719 /************** Continuing where we left off in vdbe.c ***********************/
69721 #endif
69723 #ifndef NDEBUG
69725 ** This function is only called from within an assert() expression. It
69726 ** checks that the sqlite3.nTransaction variable is correctly set to
69727 ** the number of non-transaction savepoints currently in the
69728 ** linked list starting at sqlite3.pSavepoint.
69730 ** Usage:
69732 ** assert( checkSavepointCount(db) );
69734 static int checkSavepointCount(sqlite3 *db){
69735 int n = 0;
69736 Savepoint *p;
69737 for(p=db->pSavepoint; p; p=p->pNext) n++;
69738 assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
69739 return 1;
69741 #endif
69745 ** Execute as much of a VDBE program as we can.
69746 ** This is the core of sqlite3_step().
69748 SQLITE_PRIVATE int sqlite3VdbeExec(
69749 Vdbe *p /* The VDBE */
69751 int pc=0; /* The program counter */
69752 Op *aOp = p->aOp; /* Copy of p->aOp */
69753 Op *pOp; /* Current operation */
69754 int rc = SQLITE_OK; /* Value to return */
69755 sqlite3 *db = p->db; /* The database */
69756 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
69757 u8 encoding = ENC(db); /* The database encoding */
69758 int iCompare = 0; /* Result of last OP_Compare operation */
69759 unsigned nVmStep = 0; /* Number of virtual machine steps */
69760 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
69761 unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
69762 #endif
69763 Mem *aMem = p->aMem; /* Copy of p->aMem */
69764 Mem *pIn1 = 0; /* 1st input operand */
69765 Mem *pIn2 = 0; /* 2nd input operand */
69766 Mem *pIn3 = 0; /* 3rd input operand */
69767 Mem *pOut = 0; /* Output operand */
69768 int *aPermute = 0; /* Permutation of columns for OP_Compare */
69769 i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
69770 #ifdef VDBE_PROFILE
69771 u64 start; /* CPU clock count at start of opcode */
69772 #endif
69773 /*** INSERT STACK UNION HERE ***/
69775 assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
69776 sqlite3VdbeEnter(p);
69777 if( p->rc==SQLITE_NOMEM ){
69778 /* This happens if a malloc() inside a call to sqlite3_column_text() or
69779 ** sqlite3_column_text16() failed. */
69780 goto no_mem;
69782 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
69783 assert( p->bIsReader || p->readOnly!=0 );
69784 p->rc = SQLITE_OK;
69785 p->iCurrentTime = 0;
69786 assert( p->explain==0 );
69787 p->pResultSet = 0;
69788 db->busyHandler.nBusy = 0;
69789 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
69790 sqlite3VdbeIOTraceSql(p);
69791 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
69792 if( db->xProgress ){
69793 assert( 0 < db->nProgressOps );
69794 nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
69795 if( nProgressLimit==0 ){
69796 nProgressLimit = db->nProgressOps;
69797 }else{
69798 nProgressLimit %= (unsigned)db->nProgressOps;
69801 #endif
69802 #ifdef SQLITE_DEBUG
69803 sqlite3BeginBenignMalloc();
69804 if( p->pc==0
69805 && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
69807 int i;
69808 int once = 1;
69809 sqlite3VdbePrintSql(p);
69810 if( p->db->flags & SQLITE_VdbeListing ){
69811 printf("VDBE Program Listing:\n");
69812 for(i=0; i<p->nOp; i++){
69813 sqlite3VdbePrintOp(stdout, i, &aOp[i]);
69816 if( p->db->flags & SQLITE_VdbeEQP ){
69817 for(i=0; i<p->nOp; i++){
69818 if( aOp[i].opcode==OP_Explain ){
69819 if( once ) printf("VDBE Query Plan:\n");
69820 printf("%s\n", aOp[i].p4.z);
69821 once = 0;
69825 if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
69827 sqlite3EndBenignMalloc();
69828 #endif
69829 for(pc=p->pc; rc==SQLITE_OK; pc++){
69830 assert( pc>=0 && pc<p->nOp );
69831 if( db->mallocFailed ) goto no_mem;
69832 #ifdef VDBE_PROFILE
69833 start = sqlite3Hwtime();
69834 #endif
69835 nVmStep++;
69836 pOp = &aOp[pc];
69838 /* Only allow tracing if SQLITE_DEBUG is defined.
69840 #ifdef SQLITE_DEBUG
69841 if( db->flags & SQLITE_VdbeTrace ){
69842 sqlite3VdbePrintOp(stdout, pc, pOp);
69844 #endif
69847 /* Check to see if we need to simulate an interrupt. This only happens
69848 ** if we have a special test build.
69850 #ifdef SQLITE_TEST
69851 if( sqlite3_interrupt_count>0 ){
69852 sqlite3_interrupt_count--;
69853 if( sqlite3_interrupt_count==0 ){
69854 sqlite3_interrupt(db);
69857 #endif
69859 /* On any opcode with the "out2-prerelease" tag, free any
69860 ** external allocations out of mem[p2] and set mem[p2] to be
69861 ** an undefined integer. Opcodes will either fill in the integer
69862 ** value or convert mem[p2] to a different type.
69864 assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
69865 if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
69866 assert( pOp->p2>0 );
69867 assert( pOp->p2<=(p->nMem-p->nCursor) );
69868 pOut = &aMem[pOp->p2];
69869 memAboutToChange(p, pOut);
69870 if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
69871 pOut->flags = MEM_Int;
69874 /* Sanity checking on other operands */
69875 #ifdef SQLITE_DEBUG
69876 if( (pOp->opflags & OPFLG_IN1)!=0 ){
69877 assert( pOp->p1>0 );
69878 assert( pOp->p1<=(p->nMem-p->nCursor) );
69879 assert( memIsValid(&aMem[pOp->p1]) );
69880 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
69881 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
69883 if( (pOp->opflags & OPFLG_IN2)!=0 ){
69884 assert( pOp->p2>0 );
69885 assert( pOp->p2<=(p->nMem-p->nCursor) );
69886 assert( memIsValid(&aMem[pOp->p2]) );
69887 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
69888 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
69890 if( (pOp->opflags & OPFLG_IN3)!=0 ){
69891 assert( pOp->p3>0 );
69892 assert( pOp->p3<=(p->nMem-p->nCursor) );
69893 assert( memIsValid(&aMem[pOp->p3]) );
69894 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
69895 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
69897 if( (pOp->opflags & OPFLG_OUT2)!=0 ){
69898 assert( pOp->p2>0 );
69899 assert( pOp->p2<=(p->nMem-p->nCursor) );
69900 memAboutToChange(p, &aMem[pOp->p2]);
69902 if( (pOp->opflags & OPFLG_OUT3)!=0 ){
69903 assert( pOp->p3>0 );
69904 assert( pOp->p3<=(p->nMem-p->nCursor) );
69905 memAboutToChange(p, &aMem[pOp->p3]);
69907 #endif
69909 switch( pOp->opcode ){
69911 /*****************************************************************************
69912 ** What follows is a massive switch statement where each case implements a
69913 ** separate instruction in the virtual machine. If we follow the usual
69914 ** indentation conventions, each case should be indented by 6 spaces. But
69915 ** that is a lot of wasted space on the left margin. So the code within
69916 ** the switch statement will break with convention and be flush-left. Another
69917 ** big comment (similar to this one) will mark the point in the code where
69918 ** we transition back to normal indentation.
69920 ** The formatting of each case is important. The makefile for SQLite
69921 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
69922 ** file looking for lines that begin with "case OP_". The opcodes.h files
69923 ** will be filled with #defines that give unique integer values to each
69924 ** opcode and the opcodes.c file is filled with an array of strings where
69925 ** each string is the symbolic name for the corresponding opcode. If the
69926 ** case statement is followed by a comment of the form "/# same as ... #/"
69927 ** that comment is used to determine the particular value of the opcode.
69929 ** Other keywords in the comment that follows each case are used to
69930 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
69931 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
69932 ** the mkopcodeh.awk script for additional information.
69934 ** Documentation about VDBE opcodes is generated by scanning this file
69935 ** for lines of that contain "Opcode:". That line and all subsequent
69936 ** comment lines are used in the generation of the opcode.html documentation
69937 ** file.
69939 ** SUMMARY:
69941 ** Formatting is important to scripts that scan this file.
69942 ** Do not deviate from the formatting style currently in use.
69944 *****************************************************************************/
69946 /* Opcode: Goto * P2 * * *
69948 ** An unconditional jump to address P2.
69949 ** The next instruction executed will be
69950 ** the one at index P2 from the beginning of
69951 ** the program.
69953 ** The P1 parameter is not actually used by this opcode. However, it
69954 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
69955 ** that this Goto is the bottom of a loop and that the lines from P2 down
69956 ** to the current line should be indented for EXPLAIN output.
69958 case OP_Goto: { /* jump */
69959 pc = pOp->p2 - 1;
69961 /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
69962 ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
69963 ** completion. Check to see if sqlite3_interrupt() has been called
69964 ** or if the progress callback needs to be invoked.
69966 ** This code uses unstructured "goto" statements and does not look clean.
69967 ** But that is not due to sloppy coding habits. The code is written this
69968 ** way for performance, to avoid having to run the interrupt and progress
69969 ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
69970 ** faster according to "valgrind --tool=cachegrind" */
69971 check_for_interrupt:
69972 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
69973 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
69974 /* Call the progress callback if it is configured and the required number
69975 ** of VDBE ops have been executed (either since this invocation of
69976 ** sqlite3VdbeExec() or since last time the progress callback was called).
69977 ** If the progress callback returns non-zero, exit the virtual machine with
69978 ** a return code SQLITE_ABORT.
69980 if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
69981 assert( db->nProgressOps!=0 );
69982 nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
69983 if( db->xProgress(db->pProgressArg) ){
69984 rc = SQLITE_INTERRUPT;
69985 goto vdbe_error_halt;
69988 #endif
69990 break;
69993 /* Opcode: Gosub P1 P2 * * *
69995 ** Write the current address onto register P1
69996 ** and then jump to address P2.
69998 case OP_Gosub: { /* jump */
69999 assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
70000 pIn1 = &aMem[pOp->p1];
70001 assert( VdbeMemDynamic(pIn1)==0 );
70002 memAboutToChange(p, pIn1);
70003 pIn1->flags = MEM_Int;
70004 pIn1->u.i = pc;
70005 REGISTER_TRACE(pOp->p1, pIn1);
70006 pc = pOp->p2 - 1;
70007 break;
70010 /* Opcode: Return P1 * * * *
70012 ** Jump to the next instruction after the address in register P1. After
70013 ** the jump, register P1 becomes undefined.
70015 case OP_Return: { /* in1 */
70016 pIn1 = &aMem[pOp->p1];
70017 assert( pIn1->flags==MEM_Int );
70018 pc = (int)pIn1->u.i;
70019 pIn1->flags = MEM_Undefined;
70020 break;
70023 /* Opcode: InitCoroutine P1 P2 P3 * *
70025 ** Set up register P1 so that it will Yield to the coroutine
70026 ** located at address P3.
70028 ** If P2!=0 then the coroutine implementation immediately follows
70029 ** this opcode. So jump over the coroutine implementation to
70030 ** address P2.
70032 ** See also: EndCoroutine
70034 case OP_InitCoroutine: { /* jump */
70035 assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
70036 assert( pOp->p2>=0 && pOp->p2<p->nOp );
70037 assert( pOp->p3>=0 && pOp->p3<p->nOp );
70038 pOut = &aMem[pOp->p1];
70039 assert( !VdbeMemDynamic(pOut) );
70040 pOut->u.i = pOp->p3 - 1;
70041 pOut->flags = MEM_Int;
70042 if( pOp->p2 ) pc = pOp->p2 - 1;
70043 break;
70046 /* Opcode: EndCoroutine P1 * * * *
70048 ** The instruction at the address in register P1 is a Yield.
70049 ** Jump to the P2 parameter of that Yield.
70050 ** After the jump, register P1 becomes undefined.
70052 ** See also: InitCoroutine
70054 case OP_EndCoroutine: { /* in1 */
70055 VdbeOp *pCaller;
70056 pIn1 = &aMem[pOp->p1];
70057 assert( pIn1->flags==MEM_Int );
70058 assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
70059 pCaller = &aOp[pIn1->u.i];
70060 assert( pCaller->opcode==OP_Yield );
70061 assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
70062 pc = pCaller->p2 - 1;
70063 pIn1->flags = MEM_Undefined;
70064 break;
70067 /* Opcode: Yield P1 P2 * * *
70069 ** Swap the program counter with the value in register P1. This
70070 ** has the effect of yielding to a coroutine.
70072 ** If the coroutine that is launched by this instruction ends with
70073 ** Yield or Return then continue to the next instruction. But if
70074 ** the coroutine launched by this instruction ends with
70075 ** EndCoroutine, then jump to P2 rather than continuing with the
70076 ** next instruction.
70078 ** See also: InitCoroutine
70080 case OP_Yield: { /* in1, jump */
70081 int pcDest;
70082 pIn1 = &aMem[pOp->p1];
70083 assert( VdbeMemDynamic(pIn1)==0 );
70084 pIn1->flags = MEM_Int;
70085 pcDest = (int)pIn1->u.i;
70086 pIn1->u.i = pc;
70087 REGISTER_TRACE(pOp->p1, pIn1);
70088 pc = pcDest;
70089 break;
70092 /* Opcode: HaltIfNull P1 P2 P3 P4 P5
70093 ** Synopsis: if r[P3]=null halt
70095 ** Check the value in register P3. If it is NULL then Halt using
70096 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
70097 ** value in register P3 is not NULL, then this routine is a no-op.
70098 ** The P5 parameter should be 1.
70100 case OP_HaltIfNull: { /* in3 */
70101 pIn3 = &aMem[pOp->p3];
70102 if( (pIn3->flags & MEM_Null)==0 ) break;
70103 /* Fall through into OP_Halt */
70106 /* Opcode: Halt P1 P2 * P4 P5
70108 ** Exit immediately. All open cursors, etc are closed
70109 ** automatically.
70111 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
70112 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
70113 ** For errors, it can be some other value. If P1!=0 then P2 will determine
70114 ** whether or not to rollback the current transaction. Do not rollback
70115 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
70116 ** then back out all changes that have occurred during this execution of the
70117 ** VDBE, but do not rollback the transaction.
70119 ** If P4 is not null then it is an error message string.
70121 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
70123 ** 0: (no change)
70124 ** 1: NOT NULL contraint failed: P4
70125 ** 2: UNIQUE constraint failed: P4
70126 ** 3: CHECK constraint failed: P4
70127 ** 4: FOREIGN KEY constraint failed: P4
70129 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
70130 ** omitted.
70132 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
70133 ** every program. So a jump past the last instruction of the program
70134 ** is the same as executing Halt.
70136 case OP_Halt: {
70137 const char *zType;
70138 const char *zLogFmt;
70140 if( pOp->p1==SQLITE_OK && p->pFrame ){
70141 /* Halt the sub-program. Return control to the parent frame. */
70142 VdbeFrame *pFrame = p->pFrame;
70143 p->pFrame = pFrame->pParent;
70144 p->nFrame--;
70145 sqlite3VdbeSetChanges(db, p->nChange);
70146 pc = sqlite3VdbeFrameRestore(pFrame);
70147 lastRowid = db->lastRowid;
70148 if( pOp->p2==OE_Ignore ){
70149 /* Instruction pc is the OP_Program that invoked the sub-program
70150 ** currently being halted. If the p2 instruction of this OP_Halt
70151 ** instruction is set to OE_Ignore, then the sub-program is throwing
70152 ** an IGNORE exception. In this case jump to the address specified
70153 ** as the p2 of the calling OP_Program. */
70154 pc = p->aOp[pc].p2-1;
70156 aOp = p->aOp;
70157 aMem = p->aMem;
70158 break;
70160 p->rc = pOp->p1;
70161 p->errorAction = (u8)pOp->p2;
70162 p->pc = pc;
70163 if( p->rc ){
70164 if( pOp->p5 ){
70165 static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
70166 "FOREIGN KEY" };
70167 assert( pOp->p5>=1 && pOp->p5<=4 );
70168 testcase( pOp->p5==1 );
70169 testcase( pOp->p5==2 );
70170 testcase( pOp->p5==3 );
70171 testcase( pOp->p5==4 );
70172 zType = azType[pOp->p5-1];
70173 }else{
70174 zType = 0;
70176 assert( zType!=0 || pOp->p4.z!=0 );
70177 zLogFmt = "abort at %d in [%s]: %s";
70178 if( zType && pOp->p4.z ){
70179 sqlite3SetString(&p->zErrMsg, db, "%s constraint failed: %s",
70180 zType, pOp->p4.z);
70181 }else if( pOp->p4.z ){
70182 sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
70183 }else{
70184 sqlite3SetString(&p->zErrMsg, db, "%s constraint failed", zType);
70186 sqlite3_log(pOp->p1, zLogFmt, pc, p->zSql, p->zErrMsg);
70188 rc = sqlite3VdbeHalt(p);
70189 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
70190 if( rc==SQLITE_BUSY ){
70191 p->rc = rc = SQLITE_BUSY;
70192 }else{
70193 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
70194 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
70195 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
70197 goto vdbe_return;
70200 /* Opcode: Integer P1 P2 * * *
70201 ** Synopsis: r[P2]=P1
70203 ** The 32-bit integer value P1 is written into register P2.
70205 case OP_Integer: { /* out2-prerelease */
70206 pOut->u.i = pOp->p1;
70207 break;
70210 /* Opcode: Int64 * P2 * P4 *
70211 ** Synopsis: r[P2]=P4
70213 ** P4 is a pointer to a 64-bit integer value.
70214 ** Write that value into register P2.
70216 case OP_Int64: { /* out2-prerelease */
70217 assert( pOp->p4.pI64!=0 );
70218 pOut->u.i = *pOp->p4.pI64;
70219 break;
70222 #ifndef SQLITE_OMIT_FLOATING_POINT
70223 /* Opcode: Real * P2 * P4 *
70224 ** Synopsis: r[P2]=P4
70226 ** P4 is a pointer to a 64-bit floating point value.
70227 ** Write that value into register P2.
70229 case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
70230 pOut->flags = MEM_Real;
70231 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
70232 pOut->u.r = *pOp->p4.pReal;
70233 break;
70235 #endif
70237 /* Opcode: String8 * P2 * P4 *
70238 ** Synopsis: r[P2]='P4'
70240 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
70241 ** into a String before it is executed for the first time. During
70242 ** this transformation, the length of string P4 is computed and stored
70243 ** as the P1 parameter.
70245 case OP_String8: { /* same as TK_STRING, out2-prerelease */
70246 assert( pOp->p4.z!=0 );
70247 pOp->opcode = OP_String;
70248 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
70250 #ifndef SQLITE_OMIT_UTF16
70251 if( encoding!=SQLITE_UTF8 ){
70252 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
70253 if( rc==SQLITE_TOOBIG ) goto too_big;
70254 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
70255 assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
70256 assert( VdbeMemDynamic(pOut)==0 );
70257 pOut->szMalloc = 0;
70258 pOut->flags |= MEM_Static;
70259 if( pOp->p4type==P4_DYNAMIC ){
70260 sqlite3DbFree(db, pOp->p4.z);
70262 pOp->p4type = P4_DYNAMIC;
70263 pOp->p4.z = pOut->z;
70264 pOp->p1 = pOut->n;
70266 #endif
70267 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
70268 goto too_big;
70270 /* Fall through to the next case, OP_String */
70273 /* Opcode: String P1 P2 * P4 *
70274 ** Synopsis: r[P2]='P4' (len=P1)
70276 ** The string value P4 of length P1 (bytes) is stored in register P2.
70278 case OP_String: { /* out2-prerelease */
70279 assert( pOp->p4.z!=0 );
70280 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
70281 pOut->z = pOp->p4.z;
70282 pOut->n = pOp->p1;
70283 pOut->enc = encoding;
70284 UPDATE_MAX_BLOBSIZE(pOut);
70285 break;
70288 /* Opcode: Null P1 P2 P3 * *
70289 ** Synopsis: r[P2..P3]=NULL
70291 ** Write a NULL into registers P2. If P3 greater than P2, then also write
70292 ** NULL into register P3 and every register in between P2 and P3. If P3
70293 ** is less than P2 (typically P3 is zero) then only register P2 is
70294 ** set to NULL.
70296 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
70297 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
70298 ** OP_Ne or OP_Eq.
70300 case OP_Null: { /* out2-prerelease */
70301 int cnt;
70302 u16 nullFlag;
70303 cnt = pOp->p3-pOp->p2;
70304 assert( pOp->p3<=(p->nMem-p->nCursor) );
70305 pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
70306 while( cnt>0 ){
70307 pOut++;
70308 memAboutToChange(p, pOut);
70309 sqlite3VdbeMemSetNull(pOut);
70310 pOut->flags = nullFlag;
70311 cnt--;
70313 break;
70316 /* Opcode: SoftNull P1 * * * *
70317 ** Synopsis: r[P1]=NULL
70319 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
70320 ** instruction, but do not free any string or blob memory associated with
70321 ** the register, so that if the value was a string or blob that was
70322 ** previously copied using OP_SCopy, the copies will continue to be valid.
70324 case OP_SoftNull: {
70325 assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
70326 pOut = &aMem[pOp->p1];
70327 pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
70328 break;
70331 /* Opcode: Blob P1 P2 * P4 *
70332 ** Synopsis: r[P2]=P4 (len=P1)
70334 ** P4 points to a blob of data P1 bytes long. Store this
70335 ** blob in register P2.
70337 case OP_Blob: { /* out2-prerelease */
70338 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
70339 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
70340 pOut->enc = encoding;
70341 UPDATE_MAX_BLOBSIZE(pOut);
70342 break;
70345 /* Opcode: Variable P1 P2 * P4 *
70346 ** Synopsis: r[P2]=parameter(P1,P4)
70348 ** Transfer the values of bound parameter P1 into register P2
70350 ** If the parameter is named, then its name appears in P4.
70351 ** The P4 value is used by sqlite3_bind_parameter_name().
70353 case OP_Variable: { /* out2-prerelease */
70354 Mem *pVar; /* Value being transferred */
70356 assert( pOp->p1>0 && pOp->p1<=p->nVar );
70357 assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
70358 pVar = &p->aVar[pOp->p1 - 1];
70359 if( sqlite3VdbeMemTooBig(pVar) ){
70360 goto too_big;
70362 sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
70363 UPDATE_MAX_BLOBSIZE(pOut);
70364 break;
70367 /* Opcode: Move P1 P2 P3 * *
70368 ** Synopsis: r[P2@P3]=r[P1@P3]
70370 ** Move the P3 values in register P1..P1+P3-1 over into
70371 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
70372 ** left holding a NULL. It is an error for register ranges
70373 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
70374 ** for P3 to be less than 1.
70376 case OP_Move: {
70377 int n; /* Number of registers left to copy */
70378 int p1; /* Register to copy from */
70379 int p2; /* Register to copy to */
70381 n = pOp->p3;
70382 p1 = pOp->p1;
70383 p2 = pOp->p2;
70384 assert( n>0 && p1>0 && p2>0 );
70385 assert( p1+n<=p2 || p2+n<=p1 );
70387 pIn1 = &aMem[p1];
70388 pOut = &aMem[p2];
70390 assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
70391 assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
70392 assert( memIsValid(pIn1) );
70393 memAboutToChange(p, pOut);
70394 sqlite3VdbeMemMove(pOut, pIn1);
70395 #ifdef SQLITE_DEBUG
70396 if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<&aMem[p1+pOp->p3] ){
70397 pOut->pScopyFrom += p1 - pOp->p2;
70399 #endif
70400 REGISTER_TRACE(p2++, pOut);
70401 pIn1++;
70402 pOut++;
70403 }while( --n );
70404 break;
70407 /* Opcode: Copy P1 P2 P3 * *
70408 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
70410 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
70412 ** This instruction makes a deep copy of the value. A duplicate
70413 ** is made of any string or blob constant. See also OP_SCopy.
70415 case OP_Copy: {
70416 int n;
70418 n = pOp->p3;
70419 pIn1 = &aMem[pOp->p1];
70420 pOut = &aMem[pOp->p2];
70421 assert( pOut!=pIn1 );
70422 while( 1 ){
70423 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
70424 Deephemeralize(pOut);
70425 #ifdef SQLITE_DEBUG
70426 pOut->pScopyFrom = 0;
70427 #endif
70428 REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
70429 if( (n--)==0 ) break;
70430 pOut++;
70431 pIn1++;
70433 break;
70436 /* Opcode: SCopy P1 P2 * * *
70437 ** Synopsis: r[P2]=r[P1]
70439 ** Make a shallow copy of register P1 into register P2.
70441 ** This instruction makes a shallow copy of the value. If the value
70442 ** is a string or blob, then the copy is only a pointer to the
70443 ** original and hence if the original changes so will the copy.
70444 ** Worse, if the original is deallocated, the copy becomes invalid.
70445 ** Thus the program must guarantee that the original will not change
70446 ** during the lifetime of the copy. Use OP_Copy to make a complete
70447 ** copy.
70449 case OP_SCopy: { /* out2 */
70450 pIn1 = &aMem[pOp->p1];
70451 pOut = &aMem[pOp->p2];
70452 assert( pOut!=pIn1 );
70453 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
70454 #ifdef SQLITE_DEBUG
70455 if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
70456 #endif
70457 break;
70460 /* Opcode: ResultRow P1 P2 * * *
70461 ** Synopsis: output=r[P1@P2]
70463 ** The registers P1 through P1+P2-1 contain a single row of
70464 ** results. This opcode causes the sqlite3_step() call to terminate
70465 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
70466 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
70467 ** the result row.
70469 case OP_ResultRow: {
70470 Mem *pMem;
70471 int i;
70472 assert( p->nResColumn==pOp->p2 );
70473 assert( pOp->p1>0 );
70474 assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
70476 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
70477 /* Run the progress counter just before returning.
70479 if( db->xProgress!=0
70480 && nVmStep>=nProgressLimit
70481 && db->xProgress(db->pProgressArg)!=0
70483 rc = SQLITE_INTERRUPT;
70484 goto vdbe_error_halt;
70486 #endif
70488 /* If this statement has violated immediate foreign key constraints, do
70489 ** not return the number of rows modified. And do not RELEASE the statement
70490 ** transaction. It needs to be rolled back. */
70491 if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
70492 assert( db->flags&SQLITE_CountRows );
70493 assert( p->usesStmtJournal );
70494 break;
70497 /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
70498 ** DML statements invoke this opcode to return the number of rows
70499 ** modified to the user. This is the only way that a VM that
70500 ** opens a statement transaction may invoke this opcode.
70502 ** In case this is such a statement, close any statement transaction
70503 ** opened by this VM before returning control to the user. This is to
70504 ** ensure that statement-transactions are always nested, not overlapping.
70505 ** If the open statement-transaction is not closed here, then the user
70506 ** may step another VM that opens its own statement transaction. This
70507 ** may lead to overlapping statement transactions.
70509 ** The statement transaction is never a top-level transaction. Hence
70510 ** the RELEASE call below can never fail.
70512 assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
70513 rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
70514 if( NEVER(rc!=SQLITE_OK) ){
70515 break;
70518 /* Invalidate all ephemeral cursor row caches */
70519 p->cacheCtr = (p->cacheCtr + 2)|1;
70521 /* Make sure the results of the current row are \000 terminated
70522 ** and have an assigned type. The results are de-ephemeralized as
70523 ** a side effect.
70525 pMem = p->pResultSet = &aMem[pOp->p1];
70526 for(i=0; i<pOp->p2; i++){
70527 assert( memIsValid(&pMem[i]) );
70528 Deephemeralize(&pMem[i]);
70529 assert( (pMem[i].flags & MEM_Ephem)==0
70530 || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
70531 sqlite3VdbeMemNulTerminate(&pMem[i]);
70532 REGISTER_TRACE(pOp->p1+i, &pMem[i]);
70534 if( db->mallocFailed ) goto no_mem;
70536 /* Return SQLITE_ROW
70538 p->pc = pc + 1;
70539 rc = SQLITE_ROW;
70540 goto vdbe_return;
70543 /* Opcode: Concat P1 P2 P3 * *
70544 ** Synopsis: r[P3]=r[P2]+r[P1]
70546 ** Add the text in register P1 onto the end of the text in
70547 ** register P2 and store the result in register P3.
70548 ** If either the P1 or P2 text are NULL then store NULL in P3.
70550 ** P3 = P2 || P1
70552 ** It is illegal for P1 and P3 to be the same register. Sometimes,
70553 ** if P3 is the same register as P2, the implementation is able
70554 ** to avoid a memcpy().
70556 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
70557 i64 nByte;
70559 pIn1 = &aMem[pOp->p1];
70560 pIn2 = &aMem[pOp->p2];
70561 pOut = &aMem[pOp->p3];
70562 assert( pIn1!=pOut );
70563 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
70564 sqlite3VdbeMemSetNull(pOut);
70565 break;
70567 if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
70568 Stringify(pIn1, encoding);
70569 Stringify(pIn2, encoding);
70570 nByte = pIn1->n + pIn2->n;
70571 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
70572 goto too_big;
70574 if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
70575 goto no_mem;
70577 MemSetTypeFlag(pOut, MEM_Str);
70578 if( pOut!=pIn2 ){
70579 memcpy(pOut->z, pIn2->z, pIn2->n);
70581 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
70582 pOut->z[nByte]=0;
70583 pOut->z[nByte+1] = 0;
70584 pOut->flags |= MEM_Term;
70585 pOut->n = (int)nByte;
70586 pOut->enc = encoding;
70587 UPDATE_MAX_BLOBSIZE(pOut);
70588 break;
70591 /* Opcode: Add P1 P2 P3 * *
70592 ** Synopsis: r[P3]=r[P1]+r[P2]
70594 ** Add the value in register P1 to the value in register P2
70595 ** and store the result in register P3.
70596 ** If either input is NULL, the result is NULL.
70598 /* Opcode: Multiply P1 P2 P3 * *
70599 ** Synopsis: r[P3]=r[P1]*r[P2]
70602 ** Multiply the value in register P1 by the value in register P2
70603 ** and store the result in register P3.
70604 ** If either input is NULL, the result is NULL.
70606 /* Opcode: Subtract P1 P2 P3 * *
70607 ** Synopsis: r[P3]=r[P2]-r[P1]
70609 ** Subtract the value in register P1 from the value in register P2
70610 ** and store the result in register P3.
70611 ** If either input is NULL, the result is NULL.
70613 /* Opcode: Divide P1 P2 P3 * *
70614 ** Synopsis: r[P3]=r[P2]/r[P1]
70616 ** Divide the value in register P1 by the value in register P2
70617 ** and store the result in register P3 (P3=P2/P1). If the value in
70618 ** register P1 is zero, then the result is NULL. If either input is
70619 ** NULL, the result is NULL.
70621 /* Opcode: Remainder P1 P2 P3 * *
70622 ** Synopsis: r[P3]=r[P2]%r[P1]
70624 ** Compute the remainder after integer register P2 is divided by
70625 ** register P1 and store the result in register P3.
70626 ** If the value in register P1 is zero the result is NULL.
70627 ** If either operand is NULL, the result is NULL.
70629 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
70630 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
70631 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
70632 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
70633 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
70634 char bIntint; /* Started out as two integer operands */
70635 u16 flags; /* Combined MEM_* flags from both inputs */
70636 u16 type1; /* Numeric type of left operand */
70637 u16 type2; /* Numeric type of right operand */
70638 i64 iA; /* Integer value of left operand */
70639 i64 iB; /* Integer value of right operand */
70640 double rA; /* Real value of left operand */
70641 double rB; /* Real value of right operand */
70643 pIn1 = &aMem[pOp->p1];
70644 type1 = numericType(pIn1);
70645 pIn2 = &aMem[pOp->p2];
70646 type2 = numericType(pIn2);
70647 pOut = &aMem[pOp->p3];
70648 flags = pIn1->flags | pIn2->flags;
70649 if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
70650 if( (type1 & type2 & MEM_Int)!=0 ){
70651 iA = pIn1->u.i;
70652 iB = pIn2->u.i;
70653 bIntint = 1;
70654 switch( pOp->opcode ){
70655 case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
70656 case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
70657 case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
70658 case OP_Divide: {
70659 if( iA==0 ) goto arithmetic_result_is_null;
70660 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
70661 iB /= iA;
70662 break;
70664 default: {
70665 if( iA==0 ) goto arithmetic_result_is_null;
70666 if( iA==-1 ) iA = 1;
70667 iB %= iA;
70668 break;
70671 pOut->u.i = iB;
70672 MemSetTypeFlag(pOut, MEM_Int);
70673 }else{
70674 bIntint = 0;
70675 fp_math:
70676 rA = sqlite3VdbeRealValue(pIn1);
70677 rB = sqlite3VdbeRealValue(pIn2);
70678 switch( pOp->opcode ){
70679 case OP_Add: rB += rA; break;
70680 case OP_Subtract: rB -= rA; break;
70681 case OP_Multiply: rB *= rA; break;
70682 case OP_Divide: {
70683 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
70684 if( rA==(double)0 ) goto arithmetic_result_is_null;
70685 rB /= rA;
70686 break;
70688 default: {
70689 iA = (i64)rA;
70690 iB = (i64)rB;
70691 if( iA==0 ) goto arithmetic_result_is_null;
70692 if( iA==-1 ) iA = 1;
70693 rB = (double)(iB % iA);
70694 break;
70697 #ifdef SQLITE_OMIT_FLOATING_POINT
70698 pOut->u.i = rB;
70699 MemSetTypeFlag(pOut, MEM_Int);
70700 #else
70701 if( sqlite3IsNaN(rB) ){
70702 goto arithmetic_result_is_null;
70704 pOut->u.r = rB;
70705 MemSetTypeFlag(pOut, MEM_Real);
70706 if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
70707 sqlite3VdbeIntegerAffinity(pOut);
70709 #endif
70711 break;
70713 arithmetic_result_is_null:
70714 sqlite3VdbeMemSetNull(pOut);
70715 break;
70718 /* Opcode: CollSeq P1 * * P4
70720 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
70721 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
70722 ** be returned. This is used by the built-in min(), max() and nullif()
70723 ** functions.
70725 ** If P1 is not zero, then it is a register that a subsequent min() or
70726 ** max() aggregate will set to 1 if the current row is not the minimum or
70727 ** maximum. The P1 register is initialized to 0 by this instruction.
70729 ** The interface used by the implementation of the aforementioned functions
70730 ** to retrieve the collation sequence set by this opcode is not available
70731 ** publicly, only to user functions defined in func.c.
70733 case OP_CollSeq: {
70734 assert( pOp->p4type==P4_COLLSEQ );
70735 if( pOp->p1 ){
70736 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
70738 break;
70741 /* Opcode: Function P1 P2 P3 P4 P5
70742 ** Synopsis: r[P3]=func(r[P2@P5])
70744 ** Invoke a user function (P4 is a pointer to a Function structure that
70745 ** defines the function) with P5 arguments taken from register P2 and
70746 ** successors. The result of the function is stored in register P3.
70747 ** Register P3 must not be one of the function inputs.
70749 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
70750 ** function was determined to be constant at compile time. If the first
70751 ** argument was constant then bit 0 of P1 is set. This is used to determine
70752 ** whether meta data associated with a user function argument using the
70753 ** sqlite3_set_auxdata() API may be safely retained until the next
70754 ** invocation of this opcode.
70756 ** See also: AggStep and AggFinal
70758 case OP_Function: {
70759 int i;
70760 Mem *pArg;
70761 sqlite3_context ctx;
70762 sqlite3_value **apVal;
70763 int n;
70765 n = pOp->p5;
70766 apVal = p->apArg;
70767 assert( apVal || n==0 );
70768 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
70769 ctx.pOut = &aMem[pOp->p3];
70770 memAboutToChange(p, ctx.pOut);
70772 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
70773 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
70774 pArg = &aMem[pOp->p2];
70775 for(i=0; i<n; i++, pArg++){
70776 assert( memIsValid(pArg) );
70777 apVal[i] = pArg;
70778 Deephemeralize(pArg);
70779 REGISTER_TRACE(pOp->p2+i, pArg);
70782 assert( pOp->p4type==P4_FUNCDEF );
70783 ctx.pFunc = pOp->p4.pFunc;
70784 ctx.iOp = pc;
70785 ctx.pVdbe = p;
70786 MemSetTypeFlag(ctx.pOut, MEM_Null);
70787 ctx.fErrorOrAux = 0;
70788 db->lastRowid = lastRowid;
70789 (*ctx.pFunc->xFunc)(&ctx, n, apVal); /* IMP: R-24505-23230 */
70790 lastRowid = db->lastRowid; /* Remember rowid changes made by xFunc */
70792 /* If the function returned an error, throw an exception */
70793 if( ctx.fErrorOrAux ){
70794 if( ctx.isError ){
70795 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(ctx.pOut));
70796 rc = ctx.isError;
70798 sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
70801 /* Copy the result of the function into register P3 */
70802 sqlite3VdbeChangeEncoding(ctx.pOut, encoding);
70803 if( sqlite3VdbeMemTooBig(ctx.pOut) ){
70804 goto too_big;
70807 REGISTER_TRACE(pOp->p3, ctx.pOut);
70808 UPDATE_MAX_BLOBSIZE(ctx.pOut);
70809 break;
70812 /* Opcode: BitAnd P1 P2 P3 * *
70813 ** Synopsis: r[P3]=r[P1]&r[P2]
70815 ** Take the bit-wise AND of the values in register P1 and P2 and
70816 ** store the result in register P3.
70817 ** If either input is NULL, the result is NULL.
70819 /* Opcode: BitOr P1 P2 P3 * *
70820 ** Synopsis: r[P3]=r[P1]|r[P2]
70822 ** Take the bit-wise OR of the values in register P1 and P2 and
70823 ** store the result in register P3.
70824 ** If either input is NULL, the result is NULL.
70826 /* Opcode: ShiftLeft P1 P2 P3 * *
70827 ** Synopsis: r[P3]=r[P2]<<r[P1]
70829 ** Shift the integer value in register P2 to the left by the
70830 ** number of bits specified by the integer in register P1.
70831 ** Store the result in register P3.
70832 ** If either input is NULL, the result is NULL.
70834 /* Opcode: ShiftRight P1 P2 P3 * *
70835 ** Synopsis: r[P3]=r[P2]>>r[P1]
70837 ** Shift the integer value in register P2 to the right by the
70838 ** number of bits specified by the integer in register P1.
70839 ** Store the result in register P3.
70840 ** If either input is NULL, the result is NULL.
70842 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
70843 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
70844 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
70845 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
70846 i64 iA;
70847 u64 uA;
70848 i64 iB;
70849 u8 op;
70851 pIn1 = &aMem[pOp->p1];
70852 pIn2 = &aMem[pOp->p2];
70853 pOut = &aMem[pOp->p3];
70854 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
70855 sqlite3VdbeMemSetNull(pOut);
70856 break;
70858 iA = sqlite3VdbeIntValue(pIn2);
70859 iB = sqlite3VdbeIntValue(pIn1);
70860 op = pOp->opcode;
70861 if( op==OP_BitAnd ){
70862 iA &= iB;
70863 }else if( op==OP_BitOr ){
70864 iA |= iB;
70865 }else if( iB!=0 ){
70866 assert( op==OP_ShiftRight || op==OP_ShiftLeft );
70868 /* If shifting by a negative amount, shift in the other direction */
70869 if( iB<0 ){
70870 assert( OP_ShiftRight==OP_ShiftLeft+1 );
70871 op = 2*OP_ShiftLeft + 1 - op;
70872 iB = iB>(-64) ? -iB : 64;
70875 if( iB>=64 ){
70876 iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
70877 }else{
70878 memcpy(&uA, &iA, sizeof(uA));
70879 if( op==OP_ShiftLeft ){
70880 uA <<= iB;
70881 }else{
70882 uA >>= iB;
70883 /* Sign-extend on a right shift of a negative number */
70884 if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
70886 memcpy(&iA, &uA, sizeof(iA));
70889 pOut->u.i = iA;
70890 MemSetTypeFlag(pOut, MEM_Int);
70891 break;
70894 /* Opcode: AddImm P1 P2 * * *
70895 ** Synopsis: r[P1]=r[P1]+P2
70897 ** Add the constant P2 to the value in register P1.
70898 ** The result is always an integer.
70900 ** To force any register to be an integer, just add 0.
70902 case OP_AddImm: { /* in1 */
70903 pIn1 = &aMem[pOp->p1];
70904 memAboutToChange(p, pIn1);
70905 sqlite3VdbeMemIntegerify(pIn1);
70906 pIn1->u.i += pOp->p2;
70907 break;
70910 /* Opcode: MustBeInt P1 P2 * * *
70912 ** Force the value in register P1 to be an integer. If the value
70913 ** in P1 is not an integer and cannot be converted into an integer
70914 ** without data loss, then jump immediately to P2, or if P2==0
70915 ** raise an SQLITE_MISMATCH exception.
70917 case OP_MustBeInt: { /* jump, in1 */
70918 pIn1 = &aMem[pOp->p1];
70919 if( (pIn1->flags & MEM_Int)==0 ){
70920 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
70921 VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
70922 if( (pIn1->flags & MEM_Int)==0 ){
70923 if( pOp->p2==0 ){
70924 rc = SQLITE_MISMATCH;
70925 goto abort_due_to_error;
70926 }else{
70927 pc = pOp->p2 - 1;
70928 break;
70932 MemSetTypeFlag(pIn1, MEM_Int);
70933 break;
70936 #ifndef SQLITE_OMIT_FLOATING_POINT
70937 /* Opcode: RealAffinity P1 * * * *
70939 ** If register P1 holds an integer convert it to a real value.
70941 ** This opcode is used when extracting information from a column that
70942 ** has REAL affinity. Such column values may still be stored as
70943 ** integers, for space efficiency, but after extraction we want them
70944 ** to have only a real value.
70946 case OP_RealAffinity: { /* in1 */
70947 pIn1 = &aMem[pOp->p1];
70948 if( pIn1->flags & MEM_Int ){
70949 sqlite3VdbeMemRealify(pIn1);
70951 break;
70953 #endif
70955 #ifndef SQLITE_OMIT_CAST
70956 /* Opcode: Cast P1 P2 * * *
70957 ** Synopsis: affinity(r[P1])
70959 ** Force the value in register P1 to be the type defined by P2.
70961 ** <ul>
70962 ** <li value="97"> TEXT
70963 ** <li value="98"> BLOB
70964 ** <li value="99"> NUMERIC
70965 ** <li value="100"> INTEGER
70966 ** <li value="101"> REAL
70967 ** </ul>
70969 ** A NULL value is not changed by this routine. It remains NULL.
70971 case OP_Cast: { /* in1 */
70972 assert( pOp->p2>=SQLITE_AFF_NONE && pOp->p2<=SQLITE_AFF_REAL );
70973 testcase( pOp->p2==SQLITE_AFF_TEXT );
70974 testcase( pOp->p2==SQLITE_AFF_NONE );
70975 testcase( pOp->p2==SQLITE_AFF_NUMERIC );
70976 testcase( pOp->p2==SQLITE_AFF_INTEGER );
70977 testcase( pOp->p2==SQLITE_AFF_REAL );
70978 pIn1 = &aMem[pOp->p1];
70979 memAboutToChange(p, pIn1);
70980 rc = ExpandBlob(pIn1);
70981 sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
70982 UPDATE_MAX_BLOBSIZE(pIn1);
70983 break;
70985 #endif /* SQLITE_OMIT_CAST */
70987 /* Opcode: Lt P1 P2 P3 P4 P5
70988 ** Synopsis: if r[P1]<r[P3] goto P2
70990 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
70991 ** jump to address P2.
70993 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
70994 ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
70995 ** bit is clear then fall through if either operand is NULL.
70997 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
70998 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
70999 ** to coerce both inputs according to this affinity before the
71000 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
71001 ** affinity is used. Note that the affinity conversions are stored
71002 ** back into the input registers P1 and P3. So this opcode can cause
71003 ** persistent changes to registers P1 and P3.
71005 ** Once any conversions have taken place, and neither value is NULL,
71006 ** the values are compared. If both values are blobs then memcmp() is
71007 ** used to determine the results of the comparison. If both values
71008 ** are text, then the appropriate collating function specified in
71009 ** P4 is used to do the comparison. If P4 is not specified then
71010 ** memcmp() is used to compare text string. If both values are
71011 ** numeric, then a numeric comparison is used. If the two values
71012 ** are of different types, then numbers are considered less than
71013 ** strings and strings are considered less than blobs.
71015 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
71016 ** store a boolean result (either 0, or 1, or NULL) in register P2.
71018 ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
71019 ** equal to one another, provided that they do not have their MEM_Cleared
71020 ** bit set.
71022 /* Opcode: Ne P1 P2 P3 P4 P5
71023 ** Synopsis: if r[P1]!=r[P3] goto P2
71025 ** This works just like the Lt opcode except that the jump is taken if
71026 ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
71027 ** additional information.
71029 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
71030 ** true or false and is never NULL. If both operands are NULL then the result
71031 ** of comparison is false. If either operand is NULL then the result is true.
71032 ** If neither operand is NULL the result is the same as it would be if
71033 ** the SQLITE_NULLEQ flag were omitted from P5.
71035 /* Opcode: Eq P1 P2 P3 P4 P5
71036 ** Synopsis: if r[P1]==r[P3] goto P2
71038 ** This works just like the Lt opcode except that the jump is taken if
71039 ** the operands in registers P1 and P3 are equal.
71040 ** See the Lt opcode for additional information.
71042 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
71043 ** true or false and is never NULL. If both operands are NULL then the result
71044 ** of comparison is true. If either operand is NULL then the result is false.
71045 ** If neither operand is NULL the result is the same as it would be if
71046 ** the SQLITE_NULLEQ flag were omitted from P5.
71048 /* Opcode: Le P1 P2 P3 P4 P5
71049 ** Synopsis: if r[P1]<=r[P3] goto P2
71051 ** This works just like the Lt opcode except that the jump is taken if
71052 ** the content of register P3 is less than or equal to the content of
71053 ** register P1. See the Lt opcode for additional information.
71055 /* Opcode: Gt P1 P2 P3 P4 P5
71056 ** Synopsis: if r[P1]>r[P3] goto P2
71058 ** This works just like the Lt opcode except that the jump is taken if
71059 ** the content of register P3 is greater than the content of
71060 ** register P1. See the Lt opcode for additional information.
71062 /* Opcode: Ge P1 P2 P3 P4 P5
71063 ** Synopsis: if r[P1]>=r[P3] goto P2
71065 ** This works just like the Lt opcode except that the jump is taken if
71066 ** the content of register P3 is greater than or equal to the content of
71067 ** register P1. See the Lt opcode for additional information.
71069 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
71070 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
71071 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
71072 case OP_Le: /* same as TK_LE, jump, in1, in3 */
71073 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
71074 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
71075 int res; /* Result of the comparison of pIn1 against pIn3 */
71076 char affinity; /* Affinity to use for comparison */
71077 u16 flags1; /* Copy of initial value of pIn1->flags */
71078 u16 flags3; /* Copy of initial value of pIn3->flags */
71080 pIn1 = &aMem[pOp->p1];
71081 pIn3 = &aMem[pOp->p3];
71082 flags1 = pIn1->flags;
71083 flags3 = pIn3->flags;
71084 if( (flags1 | flags3)&MEM_Null ){
71085 /* One or both operands are NULL */
71086 if( pOp->p5 & SQLITE_NULLEQ ){
71087 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
71088 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
71089 ** or not both operands are null.
71091 assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
71092 assert( (flags1 & MEM_Cleared)==0 );
71093 assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
71094 if( (flags1&MEM_Null)!=0
71095 && (flags3&MEM_Null)!=0
71096 && (flags3&MEM_Cleared)==0
71098 res = 0; /* Results are equal */
71099 }else{
71100 res = 1; /* Results are not equal */
71102 }else{
71103 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
71104 ** then the result is always NULL.
71105 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
71107 if( pOp->p5 & SQLITE_STOREP2 ){
71108 pOut = &aMem[pOp->p2];
71109 MemSetTypeFlag(pOut, MEM_Null);
71110 REGISTER_TRACE(pOp->p2, pOut);
71111 }else{
71112 VdbeBranchTaken(2,3);
71113 if( pOp->p5 & SQLITE_JUMPIFNULL ){
71114 pc = pOp->p2-1;
71117 break;
71119 }else{
71120 /* Neither operand is NULL. Do a comparison. */
71121 affinity = pOp->p5 & SQLITE_AFF_MASK;
71122 if( affinity>=SQLITE_AFF_NUMERIC ){
71123 if( (pIn1->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
71124 applyNumericAffinity(pIn1,0);
71126 if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
71127 applyNumericAffinity(pIn3,0);
71129 }else if( affinity==SQLITE_AFF_TEXT ){
71130 if( (pIn1->flags & MEM_Str)==0 && (pIn1->flags & (MEM_Int|MEM_Real))!=0 ){
71131 testcase( pIn1->flags & MEM_Int );
71132 testcase( pIn1->flags & MEM_Real );
71133 sqlite3VdbeMemStringify(pIn1, encoding, 1);
71135 if( (pIn3->flags & MEM_Str)==0 && (pIn3->flags & (MEM_Int|MEM_Real))!=0 ){
71136 testcase( pIn3->flags & MEM_Int );
71137 testcase( pIn3->flags & MEM_Real );
71138 sqlite3VdbeMemStringify(pIn3, encoding, 1);
71141 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
71142 if( pIn1->flags & MEM_Zero ){
71143 sqlite3VdbeMemExpandBlob(pIn1);
71144 flags1 &= ~MEM_Zero;
71146 if( pIn3->flags & MEM_Zero ){
71147 sqlite3VdbeMemExpandBlob(pIn3);
71148 flags3 &= ~MEM_Zero;
71150 if( db->mallocFailed ) goto no_mem;
71151 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
71153 switch( pOp->opcode ){
71154 case OP_Eq: res = res==0; break;
71155 case OP_Ne: res = res!=0; break;
71156 case OP_Lt: res = res<0; break;
71157 case OP_Le: res = res<=0; break;
71158 case OP_Gt: res = res>0; break;
71159 default: res = res>=0; break;
71162 if( pOp->p5 & SQLITE_STOREP2 ){
71163 pOut = &aMem[pOp->p2];
71164 memAboutToChange(p, pOut);
71165 MemSetTypeFlag(pOut, MEM_Int);
71166 pOut->u.i = res;
71167 REGISTER_TRACE(pOp->p2, pOut);
71168 }else{
71169 VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
71170 if( res ){
71171 pc = pOp->p2-1;
71174 /* Undo any changes made by applyAffinity() to the input registers. */
71175 pIn1->flags = flags1;
71176 pIn3->flags = flags3;
71177 break;
71180 /* Opcode: Permutation * * * P4 *
71182 ** Set the permutation used by the OP_Compare operator to be the array
71183 ** of integers in P4.
71185 ** The permutation is only valid until the next OP_Compare that has
71186 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
71187 ** occur immediately prior to the OP_Compare.
71189 case OP_Permutation: {
71190 assert( pOp->p4type==P4_INTARRAY );
71191 assert( pOp->p4.ai );
71192 aPermute = pOp->p4.ai;
71193 break;
71196 /* Opcode: Compare P1 P2 P3 P4 P5
71197 ** Synopsis: r[P1@P3] <-> r[P2@P3]
71199 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
71200 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
71201 ** the comparison for use by the next OP_Jump instruct.
71203 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
71204 ** determined by the most recent OP_Permutation operator. If the
71205 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
71206 ** order.
71208 ** P4 is a KeyInfo structure that defines collating sequences and sort
71209 ** orders for the comparison. The permutation applies to registers
71210 ** only. The KeyInfo elements are used sequentially.
71212 ** The comparison is a sort comparison, so NULLs compare equal,
71213 ** NULLs are less than numbers, numbers are less than strings,
71214 ** and strings are less than blobs.
71216 case OP_Compare: {
71217 int n;
71218 int i;
71219 int p1;
71220 int p2;
71221 const KeyInfo *pKeyInfo;
71222 int idx;
71223 CollSeq *pColl; /* Collating sequence to use on this term */
71224 int bRev; /* True for DESCENDING sort order */
71226 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
71227 n = pOp->p3;
71228 pKeyInfo = pOp->p4.pKeyInfo;
71229 assert( n>0 );
71230 assert( pKeyInfo!=0 );
71231 p1 = pOp->p1;
71232 p2 = pOp->p2;
71233 #if SQLITE_DEBUG
71234 if( aPermute ){
71235 int k, mx = 0;
71236 for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
71237 assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
71238 assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
71239 }else{
71240 assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
71241 assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
71243 #endif /* SQLITE_DEBUG */
71244 for(i=0; i<n; i++){
71245 idx = aPermute ? aPermute[i] : i;
71246 assert( memIsValid(&aMem[p1+idx]) );
71247 assert( memIsValid(&aMem[p2+idx]) );
71248 REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
71249 REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
71250 assert( i<pKeyInfo->nField );
71251 pColl = pKeyInfo->aColl[i];
71252 bRev = pKeyInfo->aSortOrder[i];
71253 iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
71254 if( iCompare ){
71255 if( bRev ) iCompare = -iCompare;
71256 break;
71259 aPermute = 0;
71260 break;
71263 /* Opcode: Jump P1 P2 P3 * *
71265 ** Jump to the instruction at address P1, P2, or P3 depending on whether
71266 ** in the most recent OP_Compare instruction the P1 vector was less than
71267 ** equal to, or greater than the P2 vector, respectively.
71269 case OP_Jump: { /* jump */
71270 if( iCompare<0 ){
71271 pc = pOp->p1 - 1; VdbeBranchTaken(0,3);
71272 }else if( iCompare==0 ){
71273 pc = pOp->p2 - 1; VdbeBranchTaken(1,3);
71274 }else{
71275 pc = pOp->p3 - 1; VdbeBranchTaken(2,3);
71277 break;
71280 /* Opcode: And P1 P2 P3 * *
71281 ** Synopsis: r[P3]=(r[P1] && r[P2])
71283 ** Take the logical AND of the values in registers P1 and P2 and
71284 ** write the result into register P3.
71286 ** If either P1 or P2 is 0 (false) then the result is 0 even if
71287 ** the other input is NULL. A NULL and true or two NULLs give
71288 ** a NULL output.
71290 /* Opcode: Or P1 P2 P3 * *
71291 ** Synopsis: r[P3]=(r[P1] || r[P2])
71293 ** Take the logical OR of the values in register P1 and P2 and
71294 ** store the answer in register P3.
71296 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
71297 ** even if the other input is NULL. A NULL and false or two NULLs
71298 ** give a NULL output.
71300 case OP_And: /* same as TK_AND, in1, in2, out3 */
71301 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
71302 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
71303 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
71305 pIn1 = &aMem[pOp->p1];
71306 if( pIn1->flags & MEM_Null ){
71307 v1 = 2;
71308 }else{
71309 v1 = sqlite3VdbeIntValue(pIn1)!=0;
71311 pIn2 = &aMem[pOp->p2];
71312 if( pIn2->flags & MEM_Null ){
71313 v2 = 2;
71314 }else{
71315 v2 = sqlite3VdbeIntValue(pIn2)!=0;
71317 if( pOp->opcode==OP_And ){
71318 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
71319 v1 = and_logic[v1*3+v2];
71320 }else{
71321 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
71322 v1 = or_logic[v1*3+v2];
71324 pOut = &aMem[pOp->p3];
71325 if( v1==2 ){
71326 MemSetTypeFlag(pOut, MEM_Null);
71327 }else{
71328 pOut->u.i = v1;
71329 MemSetTypeFlag(pOut, MEM_Int);
71331 break;
71334 /* Opcode: Not P1 P2 * * *
71335 ** Synopsis: r[P2]= !r[P1]
71337 ** Interpret the value in register P1 as a boolean value. Store the
71338 ** boolean complement in register P2. If the value in register P1 is
71339 ** NULL, then a NULL is stored in P2.
71341 case OP_Not: { /* same as TK_NOT, in1, out2 */
71342 pIn1 = &aMem[pOp->p1];
71343 pOut = &aMem[pOp->p2];
71344 sqlite3VdbeMemSetNull(pOut);
71345 if( (pIn1->flags & MEM_Null)==0 ){
71346 pOut->flags = MEM_Int;
71347 pOut->u.i = !sqlite3VdbeIntValue(pIn1);
71349 break;
71352 /* Opcode: BitNot P1 P2 * * *
71353 ** Synopsis: r[P1]= ~r[P1]
71355 ** Interpret the content of register P1 as an integer. Store the
71356 ** ones-complement of the P1 value into register P2. If P1 holds
71357 ** a NULL then store a NULL in P2.
71359 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
71360 pIn1 = &aMem[pOp->p1];
71361 pOut = &aMem[pOp->p2];
71362 sqlite3VdbeMemSetNull(pOut);
71363 if( (pIn1->flags & MEM_Null)==0 ){
71364 pOut->flags = MEM_Int;
71365 pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
71367 break;
71370 /* Opcode: Once P1 P2 * * *
71372 ** Check the "once" flag number P1. If it is set, jump to instruction P2.
71373 ** Otherwise, set the flag and fall through to the next instruction.
71374 ** In other words, this opcode causes all following opcodes up through P2
71375 ** (but not including P2) to run just once and to be skipped on subsequent
71376 ** times through the loop.
71378 ** All "once" flags are initially cleared whenever a prepared statement
71379 ** first begins to run.
71381 case OP_Once: { /* jump */
71382 assert( pOp->p1<p->nOnceFlag );
71383 VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
71384 if( p->aOnceFlag[pOp->p1] ){
71385 pc = pOp->p2-1;
71386 }else{
71387 p->aOnceFlag[pOp->p1] = 1;
71389 break;
71392 /* Opcode: If P1 P2 P3 * *
71394 ** Jump to P2 if the value in register P1 is true. The value
71395 ** is considered true if it is numeric and non-zero. If the value
71396 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
71398 /* Opcode: IfNot P1 P2 P3 * *
71400 ** Jump to P2 if the value in register P1 is False. The value
71401 ** is considered false if it has a numeric value of zero. If the value
71402 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
71404 case OP_If: /* jump, in1 */
71405 case OP_IfNot: { /* jump, in1 */
71406 int c;
71407 pIn1 = &aMem[pOp->p1];
71408 if( pIn1->flags & MEM_Null ){
71409 c = pOp->p3;
71410 }else{
71411 #ifdef SQLITE_OMIT_FLOATING_POINT
71412 c = sqlite3VdbeIntValue(pIn1)!=0;
71413 #else
71414 c = sqlite3VdbeRealValue(pIn1)!=0.0;
71415 #endif
71416 if( pOp->opcode==OP_IfNot ) c = !c;
71418 VdbeBranchTaken(c!=0, 2);
71419 if( c ){
71420 pc = pOp->p2-1;
71422 break;
71425 /* Opcode: IsNull P1 P2 * * *
71426 ** Synopsis: if r[P1]==NULL goto P2
71428 ** Jump to P2 if the value in register P1 is NULL.
71430 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
71431 pIn1 = &aMem[pOp->p1];
71432 VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
71433 if( (pIn1->flags & MEM_Null)!=0 ){
71434 pc = pOp->p2 - 1;
71436 break;
71439 /* Opcode: NotNull P1 P2 * * *
71440 ** Synopsis: if r[P1]!=NULL goto P2
71442 ** Jump to P2 if the value in register P1 is not NULL.
71444 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
71445 pIn1 = &aMem[pOp->p1];
71446 VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
71447 if( (pIn1->flags & MEM_Null)==0 ){
71448 pc = pOp->p2 - 1;
71450 break;
71453 /* Opcode: Column P1 P2 P3 P4 P5
71454 ** Synopsis: r[P3]=PX
71456 ** Interpret the data that cursor P1 points to as a structure built using
71457 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
71458 ** information about the format of the data.) Extract the P2-th column
71459 ** from this record. If there are less that (P2+1)
71460 ** values in the record, extract a NULL.
71462 ** The value extracted is stored in register P3.
71464 ** If the column contains fewer than P2 fields, then extract a NULL. Or,
71465 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
71466 ** the result.
71468 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
71469 ** then the cache of the cursor is reset prior to extracting the column.
71470 ** The first OP_Column against a pseudo-table after the value of the content
71471 ** register has changed should have this bit set.
71473 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
71474 ** the result is guaranteed to only be used as the argument of a length()
71475 ** or typeof() function, respectively. The loading of large blobs can be
71476 ** skipped for length() and all content loading can be skipped for typeof().
71478 case OP_Column: {
71479 i64 payloadSize64; /* Number of bytes in the record */
71480 int p2; /* column number to retrieve */
71481 VdbeCursor *pC; /* The VDBE cursor */
71482 BtCursor *pCrsr; /* The BTree cursor */
71483 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
71484 int len; /* The length of the serialized data for the column */
71485 int i; /* Loop counter */
71486 Mem *pDest; /* Where to write the extracted value */
71487 Mem sMem; /* For storing the record being decoded */
71488 const u8 *zData; /* Part of the record being decoded */
71489 const u8 *zHdr; /* Next unparsed byte of the header */
71490 const u8 *zEndHdr; /* Pointer to first byte after the header */
71491 u32 offset; /* Offset into the data */
71492 u32 szField; /* Number of bytes in the content of a field */
71493 u32 avail; /* Number of bytes of available data */
71494 u32 t; /* A type code from the record header */
71495 u16 fx; /* pDest->flags value */
71496 Mem *pReg; /* PseudoTable input register */
71498 p2 = pOp->p2;
71499 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
71500 pDest = &aMem[pOp->p3];
71501 memAboutToChange(p, pDest);
71502 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71503 pC = p->apCsr[pOp->p1];
71504 assert( pC!=0 );
71505 assert( p2<pC->nField );
71506 aOffset = pC->aOffset;
71507 #ifndef SQLITE_OMIT_VIRTUALTABLE
71508 assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
71509 #endif
71510 pCrsr = pC->pCursor;
71511 assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
71512 assert( pCrsr!=0 || pC->nullRow ); /* pC->nullRow on PseudoTables */
71514 /* If the cursor cache is stale, bring it up-to-date */
71515 rc = sqlite3VdbeCursorMoveto(pC);
71516 if( rc ) goto abort_due_to_error;
71517 if( pC->cacheStatus!=p->cacheCtr ){
71518 if( pC->nullRow ){
71519 if( pCrsr==0 ){
71520 assert( pC->pseudoTableReg>0 );
71521 pReg = &aMem[pC->pseudoTableReg];
71522 assert( pReg->flags & MEM_Blob );
71523 assert( memIsValid(pReg) );
71524 pC->payloadSize = pC->szRow = avail = pReg->n;
71525 pC->aRow = (u8*)pReg->z;
71526 }else{
71527 sqlite3VdbeMemSetNull(pDest);
71528 goto op_column_out;
71530 }else{
71531 assert( pCrsr );
71532 if( pC->isTable==0 ){
71533 assert( sqlite3BtreeCursorIsValid(pCrsr) );
71534 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
71535 assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
71536 /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
71537 ** payload size, so it is impossible for payloadSize64 to be
71538 ** larger than 32 bits. */
71539 assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
71540 pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
71541 pC->payloadSize = (u32)payloadSize64;
71542 }else{
71543 assert( sqlite3BtreeCursorIsValid(pCrsr) );
71544 VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
71545 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
71546 pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
71548 assert( avail<=65536 ); /* Maximum page size is 64KiB */
71549 if( pC->payloadSize <= (u32)avail ){
71550 pC->szRow = pC->payloadSize;
71551 }else{
71552 pC->szRow = avail;
71554 if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
71555 goto too_big;
71558 pC->cacheStatus = p->cacheCtr;
71559 pC->iHdrOffset = getVarint32(pC->aRow, offset);
71560 pC->nHdrParsed = 0;
71561 aOffset[0] = offset;
71563 /* Make sure a corrupt database has not given us an oversize header.
71564 ** Do this now to avoid an oversize memory allocation.
71566 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
71567 ** types use so much data space that there can only be 4096 and 32 of
71568 ** them, respectively. So the maximum header length results from a
71569 ** 3-byte type for each of the maximum of 32768 columns plus three
71570 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
71572 if( offset > 98307 || offset > pC->payloadSize ){
71573 rc = SQLITE_CORRUPT_BKPT;
71574 goto op_column_error;
71577 if( avail<offset ){
71578 /* pC->aRow does not have to hold the entire row, but it does at least
71579 ** need to cover the header of the record. If pC->aRow does not contain
71580 ** the complete header, then set it to zero, forcing the header to be
71581 ** dynamically allocated. */
71582 pC->aRow = 0;
71583 pC->szRow = 0;
71586 /* The following goto is an optimization. It can be omitted and
71587 ** everything will still work. But OP_Column is measurably faster
71588 ** by skipping the subsequent conditional, which is always true.
71590 assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
71591 goto op_column_read_header;
71594 /* Make sure at least the first p2+1 entries of the header have been
71595 ** parsed and valid information is in aOffset[] and pC->aType[].
71597 if( pC->nHdrParsed<=p2 ){
71598 /* If there is more header available for parsing in the record, try
71599 ** to extract additional fields up through the p2+1-th field
71601 op_column_read_header:
71602 if( pC->iHdrOffset<aOffset[0] ){
71603 /* Make sure zData points to enough of the record to cover the header. */
71604 if( pC->aRow==0 ){
71605 memset(&sMem, 0, sizeof(sMem));
71606 rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0],
71607 !pC->isTable, &sMem);
71608 if( rc!=SQLITE_OK ){
71609 goto op_column_error;
71611 zData = (u8*)sMem.z;
71612 }else{
71613 zData = pC->aRow;
71616 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
71617 i = pC->nHdrParsed;
71618 offset = aOffset[i];
71619 zHdr = zData + pC->iHdrOffset;
71620 zEndHdr = zData + aOffset[0];
71621 assert( i<=p2 && zHdr<zEndHdr );
71623 if( zHdr[0]<0x80 ){
71624 t = zHdr[0];
71625 zHdr++;
71626 }else{
71627 zHdr += sqlite3GetVarint32(zHdr, &t);
71629 pC->aType[i] = t;
71630 szField = sqlite3VdbeSerialTypeLen(t);
71631 offset += szField;
71632 if( offset<szField ){ /* True if offset overflows */
71633 zHdr = &zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
71634 break;
71636 i++;
71637 aOffset[i] = offset;
71638 }while( i<=p2 && zHdr<zEndHdr );
71639 pC->nHdrParsed = i;
71640 pC->iHdrOffset = (u32)(zHdr - zData);
71641 if( pC->aRow==0 ){
71642 sqlite3VdbeMemRelease(&sMem);
71643 sMem.flags = MEM_Null;
71646 /* The record is corrupt if any of the following are true:
71647 ** (1) the bytes of the header extend past the declared header size
71648 ** (zHdr>zEndHdr)
71649 ** (2) the entire header was used but not all data was used
71650 ** (zHdr==zEndHdr && offset!=pC->payloadSize)
71651 ** (3) the end of the data extends beyond the end of the record.
71652 ** (offset > pC->payloadSize)
71654 if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset!=pC->payloadSize))
71655 || (offset > pC->payloadSize)
71657 rc = SQLITE_CORRUPT_BKPT;
71658 goto op_column_error;
71662 /* If after trying to extra new entries from the header, nHdrParsed is
71663 ** still not up to p2, that means that the record has fewer than p2
71664 ** columns. So the result will be either the default value or a NULL.
71666 if( pC->nHdrParsed<=p2 ){
71667 if( pOp->p4type==P4_MEM ){
71668 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
71669 }else{
71670 sqlite3VdbeMemSetNull(pDest);
71672 goto op_column_out;
71676 /* Extract the content for the p2+1-th column. Control can only
71677 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
71678 ** all valid.
71680 assert( p2<pC->nHdrParsed );
71681 assert( rc==SQLITE_OK );
71682 assert( sqlite3VdbeCheckMemInvariants(pDest) );
71683 if( VdbeMemDynamic(pDest) ) sqlite3VdbeMemSetNull(pDest);
71684 t = pC->aType[p2];
71685 if( pC->szRow>=aOffset[p2+1] ){
71686 /* This is the common case where the desired content fits on the original
71687 ** page - where the content is not on an overflow page */
71688 sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], t, pDest);
71689 }else{
71690 /* This branch happens only when content is on overflow pages */
71691 if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
71692 && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
71693 || (len = sqlite3VdbeSerialTypeLen(t))==0
71695 /* Content is irrelevant for
71696 ** 1. the typeof() function,
71697 ** 2. the length(X) function if X is a blob, and
71698 ** 3. if the content length is zero.
71699 ** So we might as well use bogus content rather than reading
71700 ** content from disk. NULL will work for the value for strings
71701 ** and blobs and whatever is in the payloadSize64 variable
71702 ** will work for everything else. */
71703 sqlite3VdbeSerialGet(t<=13 ? (u8*)&payloadSize64 : 0, t, pDest);
71704 }else{
71705 rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
71706 pDest);
71707 if( rc!=SQLITE_OK ){
71708 goto op_column_error;
71710 sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
71711 pDest->flags &= ~MEM_Ephem;
71714 pDest->enc = encoding;
71716 op_column_out:
71717 /* If the column value is an ephemeral string, go ahead and persist
71718 ** that string in case the cursor moves before the column value is
71719 ** used. The following code does the equivalent of Deephemeralize()
71720 ** but does it faster. */
71721 if( (pDest->flags & MEM_Ephem)!=0 && pDest->z ){
71722 fx = pDest->flags & (MEM_Str|MEM_Blob);
71723 assert( fx!=0 );
71724 zData = (const u8*)pDest->z;
71725 len = pDest->n;
71726 if( sqlite3VdbeMemClearAndResize(pDest, len+2) ) goto no_mem;
71727 memcpy(pDest->z, zData, len);
71728 pDest->z[len] = 0;
71729 pDest->z[len+1] = 0;
71730 pDest->flags = fx|MEM_Term;
71732 op_column_error:
71733 UPDATE_MAX_BLOBSIZE(pDest);
71734 REGISTER_TRACE(pOp->p3, pDest);
71735 break;
71738 /* Opcode: Affinity P1 P2 * P4 *
71739 ** Synopsis: affinity(r[P1@P2])
71741 ** Apply affinities to a range of P2 registers starting with P1.
71743 ** P4 is a string that is P2 characters long. The nth character of the
71744 ** string indicates the column affinity that should be used for the nth
71745 ** memory cell in the range.
71747 case OP_Affinity: {
71748 const char *zAffinity; /* The affinity to be applied */
71749 char cAff; /* A single character of affinity */
71751 zAffinity = pOp->p4.z;
71752 assert( zAffinity!=0 );
71753 assert( zAffinity[pOp->p2]==0 );
71754 pIn1 = &aMem[pOp->p1];
71755 while( (cAff = *(zAffinity++))!=0 ){
71756 assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
71757 assert( memIsValid(pIn1) );
71758 applyAffinity(pIn1, cAff, encoding);
71759 pIn1++;
71761 break;
71764 /* Opcode: MakeRecord P1 P2 P3 P4 *
71765 ** Synopsis: r[P3]=mkrec(r[P1@P2])
71767 ** Convert P2 registers beginning with P1 into the [record format]
71768 ** use as a data record in a database table or as a key
71769 ** in an index. The OP_Column opcode can decode the record later.
71771 ** P4 may be a string that is P2 characters long. The nth character of the
71772 ** string indicates the column affinity that should be used for the nth
71773 ** field of the index key.
71775 ** The mapping from character to affinity is given by the SQLITE_AFF_
71776 ** macros defined in sqliteInt.h.
71778 ** If P4 is NULL then all index fields have the affinity NONE.
71780 case OP_MakeRecord: {
71781 u8 *zNewRecord; /* A buffer to hold the data for the new record */
71782 Mem *pRec; /* The new record */
71783 u64 nData; /* Number of bytes of data space */
71784 int nHdr; /* Number of bytes of header space */
71785 i64 nByte; /* Data space required for this record */
71786 int nZero; /* Number of zero bytes at the end of the record */
71787 int nVarint; /* Number of bytes in a varint */
71788 u32 serial_type; /* Type field */
71789 Mem *pData0; /* First field to be combined into the record */
71790 Mem *pLast; /* Last field of the record */
71791 int nField; /* Number of fields in the record */
71792 char *zAffinity; /* The affinity string for the record */
71793 int file_format; /* File format to use for encoding */
71794 int i; /* Space used in zNewRecord[] header */
71795 int j; /* Space used in zNewRecord[] content */
71796 int len; /* Length of a field */
71798 /* Assuming the record contains N fields, the record format looks
71799 ** like this:
71801 ** ------------------------------------------------------------------------
71802 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
71803 ** ------------------------------------------------------------------------
71805 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
71806 ** and so forth.
71808 ** Each type field is a varint representing the serial type of the
71809 ** corresponding data element (see sqlite3VdbeSerialType()). The
71810 ** hdr-size field is also a varint which is the offset from the beginning
71811 ** of the record to data0.
71813 nData = 0; /* Number of bytes of data space */
71814 nHdr = 0; /* Number of bytes of header space */
71815 nZero = 0; /* Number of zero bytes at the end of the record */
71816 nField = pOp->p1;
71817 zAffinity = pOp->p4.z;
71818 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
71819 pData0 = &aMem[nField];
71820 nField = pOp->p2;
71821 pLast = &pData0[nField-1];
71822 file_format = p->minWriteFileFormat;
71824 /* Identify the output register */
71825 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
71826 pOut = &aMem[pOp->p3];
71827 memAboutToChange(p, pOut);
71829 /* Apply the requested affinity to all inputs
71831 assert( pData0<=pLast );
71832 if( zAffinity ){
71833 pRec = pData0;
71835 applyAffinity(pRec++, *(zAffinity++), encoding);
71836 assert( zAffinity[0]==0 || pRec<=pLast );
71837 }while( zAffinity[0] );
71840 /* Loop through the elements that will make up the record to figure
71841 ** out how much space is required for the new record.
71843 pRec = pLast;
71845 assert( memIsValid(pRec) );
71846 pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format);
71847 len = sqlite3VdbeSerialTypeLen(serial_type);
71848 if( pRec->flags & MEM_Zero ){
71849 if( nData ){
71850 sqlite3VdbeMemExpandBlob(pRec);
71851 }else{
71852 nZero += pRec->u.nZero;
71853 len -= pRec->u.nZero;
71856 nData += len;
71857 testcase( serial_type==127 );
71858 testcase( serial_type==128 );
71859 nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
71860 }while( (--pRec)>=pData0 );
71862 /* Add the initial header varint and total the size */
71863 testcase( nHdr==126 );
71864 testcase( nHdr==127 );
71865 if( nHdr<=126 ){
71866 /* The common case */
71867 nHdr += 1;
71868 }else{
71869 /* Rare case of a really large header */
71870 nVarint = sqlite3VarintLen(nHdr);
71871 nHdr += nVarint;
71872 if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
71874 nByte = nHdr+nData;
71875 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
71876 goto too_big;
71879 /* Make sure the output register has a buffer large enough to store
71880 ** the new record. The output register (pOp->p3) is not allowed to
71881 ** be one of the input registers (because the following call to
71882 ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
71884 if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
71885 goto no_mem;
71887 zNewRecord = (u8 *)pOut->z;
71889 /* Write the record */
71890 i = putVarint32(zNewRecord, nHdr);
71891 j = nHdr;
71892 assert( pData0<=pLast );
71893 pRec = pData0;
71895 serial_type = pRec->uTemp;
71896 i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
71897 j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
71898 }while( (++pRec)<=pLast );
71899 assert( i==nHdr );
71900 assert( j==nByte );
71902 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
71903 pOut->n = (int)nByte;
71904 pOut->flags = MEM_Blob;
71905 if( nZero ){
71906 pOut->u.nZero = nZero;
71907 pOut->flags |= MEM_Zero;
71909 pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
71910 REGISTER_TRACE(pOp->p3, pOut);
71911 UPDATE_MAX_BLOBSIZE(pOut);
71912 break;
71915 /* Opcode: Count P1 P2 * * *
71916 ** Synopsis: r[P2]=count()
71918 ** Store the number of entries (an integer value) in the table or index
71919 ** opened by cursor P1 in register P2
71921 #ifndef SQLITE_OMIT_BTREECOUNT
71922 case OP_Count: { /* out2-prerelease */
71923 i64 nEntry;
71924 BtCursor *pCrsr;
71926 pCrsr = p->apCsr[pOp->p1]->pCursor;
71927 assert( pCrsr );
71928 nEntry = 0; /* Not needed. Only used to silence a warning. */
71929 rc = sqlite3BtreeCount(pCrsr, &nEntry);
71930 pOut->u.i = nEntry;
71931 break;
71933 #endif
71935 /* Opcode: Savepoint P1 * * P4 *
71937 ** Open, release or rollback the savepoint named by parameter P4, depending
71938 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
71939 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
71941 case OP_Savepoint: {
71942 int p1; /* Value of P1 operand */
71943 char *zName; /* Name of savepoint */
71944 int nName;
71945 Savepoint *pNew;
71946 Savepoint *pSavepoint;
71947 Savepoint *pTmp;
71948 int iSavepoint;
71949 int ii;
71951 p1 = pOp->p1;
71952 zName = pOp->p4.z;
71954 /* Assert that the p1 parameter is valid. Also that if there is no open
71955 ** transaction, then there cannot be any savepoints.
71957 assert( db->pSavepoint==0 || db->autoCommit==0 );
71958 assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
71959 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
71960 assert( checkSavepointCount(db) );
71961 assert( p->bIsReader );
71963 if( p1==SAVEPOINT_BEGIN ){
71964 if( db->nVdbeWrite>0 ){
71965 /* A new savepoint cannot be created if there are active write
71966 ** statements (i.e. open read/write incremental blob handles).
71968 sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
71969 "SQL statements in progress");
71970 rc = SQLITE_BUSY;
71971 }else{
71972 nName = sqlite3Strlen30(zName);
71974 #ifndef SQLITE_OMIT_VIRTUALTABLE
71975 /* This call is Ok even if this savepoint is actually a transaction
71976 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
71977 ** If this is a transaction savepoint being opened, it is guaranteed
71978 ** that the db->aVTrans[] array is empty. */
71979 assert( db->autoCommit==0 || db->nVTrans==0 );
71980 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
71981 db->nStatement+db->nSavepoint);
71982 if( rc!=SQLITE_OK ) goto abort_due_to_error;
71983 #endif
71985 /* Create a new savepoint structure. */
71986 pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
71987 if( pNew ){
71988 pNew->zName = (char *)&pNew[1];
71989 memcpy(pNew->zName, zName, nName+1);
71991 /* If there is no open transaction, then mark this as a special
71992 ** "transaction savepoint". */
71993 if( db->autoCommit ){
71994 db->autoCommit = 0;
71995 db->isTransactionSavepoint = 1;
71996 }else{
71997 db->nSavepoint++;
72000 /* Link the new savepoint into the database handle's list. */
72001 pNew->pNext = db->pSavepoint;
72002 db->pSavepoint = pNew;
72003 pNew->nDeferredCons = db->nDeferredCons;
72004 pNew->nDeferredImmCons = db->nDeferredImmCons;
72007 }else{
72008 iSavepoint = 0;
72010 /* Find the named savepoint. If there is no such savepoint, then an
72011 ** an error is returned to the user. */
72012 for(
72013 pSavepoint = db->pSavepoint;
72014 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
72015 pSavepoint = pSavepoint->pNext
72017 iSavepoint++;
72019 if( !pSavepoint ){
72020 sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
72021 rc = SQLITE_ERROR;
72022 }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
72023 /* It is not possible to release (commit) a savepoint if there are
72024 ** active write statements.
72026 sqlite3SetString(&p->zErrMsg, db,
72027 "cannot release savepoint - SQL statements in progress"
72029 rc = SQLITE_BUSY;
72030 }else{
72032 /* Determine whether or not this is a transaction savepoint. If so,
72033 ** and this is a RELEASE command, then the current transaction
72034 ** is committed.
72036 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
72037 if( isTransaction && p1==SAVEPOINT_RELEASE ){
72038 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
72039 goto vdbe_return;
72041 db->autoCommit = 1;
72042 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
72043 p->pc = pc;
72044 db->autoCommit = 0;
72045 p->rc = rc = SQLITE_BUSY;
72046 goto vdbe_return;
72048 db->isTransactionSavepoint = 0;
72049 rc = p->rc;
72050 }else{
72051 int isSchemaChange;
72052 iSavepoint = db->nSavepoint - iSavepoint - 1;
72053 if( p1==SAVEPOINT_ROLLBACK ){
72054 isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
72055 for(ii=0; ii<db->nDb; ii++){
72056 rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
72057 SQLITE_ABORT_ROLLBACK,
72058 isSchemaChange==0);
72059 if( rc!=SQLITE_OK ) goto abort_due_to_error;
72061 }else{
72062 isSchemaChange = 0;
72064 for(ii=0; ii<db->nDb; ii++){
72065 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
72066 if( rc!=SQLITE_OK ){
72067 goto abort_due_to_error;
72070 if( isSchemaChange ){
72071 sqlite3ExpirePreparedStatements(db);
72072 sqlite3ResetAllSchemasOfConnection(db);
72073 db->flags = (db->flags | SQLITE_InternChanges);
72077 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
72078 ** savepoints nested inside of the savepoint being operated on. */
72079 while( db->pSavepoint!=pSavepoint ){
72080 pTmp = db->pSavepoint;
72081 db->pSavepoint = pTmp->pNext;
72082 sqlite3DbFree(db, pTmp);
72083 db->nSavepoint--;
72086 /* If it is a RELEASE, then destroy the savepoint being operated on
72087 ** too. If it is a ROLLBACK TO, then set the number of deferred
72088 ** constraint violations present in the database to the value stored
72089 ** when the savepoint was created. */
72090 if( p1==SAVEPOINT_RELEASE ){
72091 assert( pSavepoint==db->pSavepoint );
72092 db->pSavepoint = pSavepoint->pNext;
72093 sqlite3DbFree(db, pSavepoint);
72094 if( !isTransaction ){
72095 db->nSavepoint--;
72097 }else{
72098 db->nDeferredCons = pSavepoint->nDeferredCons;
72099 db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
72102 if( !isTransaction ){
72103 rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
72104 if( rc!=SQLITE_OK ) goto abort_due_to_error;
72109 break;
72112 /* Opcode: AutoCommit P1 P2 * * *
72114 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
72115 ** back any currently active btree transactions. If there are any active
72116 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
72117 ** there are active writing VMs or active VMs that use shared cache.
72119 ** This instruction causes the VM to halt.
72121 case OP_AutoCommit: {
72122 int desiredAutoCommit;
72123 int iRollback;
72124 int turnOnAC;
72126 desiredAutoCommit = pOp->p1;
72127 iRollback = pOp->p2;
72128 turnOnAC = desiredAutoCommit && !db->autoCommit;
72129 assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
72130 assert( desiredAutoCommit==1 || iRollback==0 );
72131 assert( db->nVdbeActive>0 ); /* At least this one VM is active */
72132 assert( p->bIsReader );
72134 #if 0
72135 if( turnOnAC && iRollback && db->nVdbeActive>1 ){
72136 /* If this instruction implements a ROLLBACK and other VMs are
72137 ** still running, and a transaction is active, return an error indicating
72138 ** that the other VMs must complete first.
72140 sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
72141 "SQL statements in progress");
72142 rc = SQLITE_BUSY;
72143 }else
72144 #endif
72145 if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
72146 /* If this instruction implements a COMMIT and other VMs are writing
72147 ** return an error indicating that the other VMs must complete first.
72149 sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
72150 "SQL statements in progress");
72151 rc = SQLITE_BUSY;
72152 }else if( desiredAutoCommit!=db->autoCommit ){
72153 if( iRollback ){
72154 assert( desiredAutoCommit==1 );
72155 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
72156 db->autoCommit = 1;
72157 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
72158 goto vdbe_return;
72159 }else{
72160 db->autoCommit = (u8)desiredAutoCommit;
72161 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
72162 p->pc = pc;
72163 db->autoCommit = (u8)(1-desiredAutoCommit);
72164 p->rc = rc = SQLITE_BUSY;
72165 goto vdbe_return;
72168 assert( db->nStatement==0 );
72169 sqlite3CloseSavepoints(db);
72170 if( p->rc==SQLITE_OK ){
72171 rc = SQLITE_DONE;
72172 }else{
72173 rc = SQLITE_ERROR;
72175 goto vdbe_return;
72176 }else{
72177 sqlite3SetString(&p->zErrMsg, db,
72178 (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
72179 (iRollback)?"cannot rollback - no transaction is active":
72180 "cannot commit - no transaction is active"));
72182 rc = SQLITE_ERROR;
72184 break;
72187 /* Opcode: Transaction P1 P2 P3 P4 P5
72189 ** Begin a transaction on database P1 if a transaction is not already
72190 ** active.
72191 ** If P2 is non-zero, then a write-transaction is started, or if a
72192 ** read-transaction is already active, it is upgraded to a write-transaction.
72193 ** If P2 is zero, then a read-transaction is started.
72195 ** P1 is the index of the database file on which the transaction is
72196 ** started. Index 0 is the main database file and index 1 is the
72197 ** file used for temporary tables. Indices of 2 or more are used for
72198 ** attached databases.
72200 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
72201 ** true (this flag is set if the Vdbe may modify more than one row and may
72202 ** throw an ABORT exception), a statement transaction may also be opened.
72203 ** More specifically, a statement transaction is opened iff the database
72204 ** connection is currently not in autocommit mode, or if there are other
72205 ** active statements. A statement transaction allows the changes made by this
72206 ** VDBE to be rolled back after an error without having to roll back the
72207 ** entire transaction. If no error is encountered, the statement transaction
72208 ** will automatically commit when the VDBE halts.
72210 ** If P5!=0 then this opcode also checks the schema cookie against P3
72211 ** and the schema generation counter against P4.
72212 ** The cookie changes its value whenever the database schema changes.
72213 ** This operation is used to detect when that the cookie has changed
72214 ** and that the current process needs to reread the schema. If the schema
72215 ** cookie in P3 differs from the schema cookie in the database header or
72216 ** if the schema generation counter in P4 differs from the current
72217 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
72218 ** halts. The sqlite3_step() wrapper function might then reprepare the
72219 ** statement and rerun it from the beginning.
72221 case OP_Transaction: {
72222 Btree *pBt;
72223 int iMeta;
72224 int iGen;
72226 assert( p->bIsReader );
72227 assert( p->readOnly==0 || pOp->p2==0 );
72228 assert( pOp->p1>=0 && pOp->p1<db->nDb );
72229 assert( DbMaskTest(p->btreeMask, pOp->p1) );
72230 if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
72231 rc = SQLITE_READONLY;
72232 goto abort_due_to_error;
72234 pBt = db->aDb[pOp->p1].pBt;
72236 if( pBt ){
72237 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
72238 if( rc==SQLITE_BUSY ){
72239 p->pc = pc;
72240 p->rc = rc = SQLITE_BUSY;
72241 goto vdbe_return;
72243 if( rc!=SQLITE_OK ){
72244 goto abort_due_to_error;
72247 if( pOp->p2 && p->usesStmtJournal
72248 && (db->autoCommit==0 || db->nVdbeRead>1)
72250 assert( sqlite3BtreeIsInTrans(pBt) );
72251 if( p->iStatement==0 ){
72252 assert( db->nStatement>=0 && db->nSavepoint>=0 );
72253 db->nStatement++;
72254 p->iStatement = db->nSavepoint + db->nStatement;
72257 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
72258 if( rc==SQLITE_OK ){
72259 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
72262 /* Store the current value of the database handles deferred constraint
72263 ** counter. If the statement transaction needs to be rolled back,
72264 ** the value of this counter needs to be restored too. */
72265 p->nStmtDefCons = db->nDeferredCons;
72266 p->nStmtDefImmCons = db->nDeferredImmCons;
72269 /* Gather the schema version number for checking */
72270 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
72271 iGen = db->aDb[pOp->p1].pSchema->iGeneration;
72272 }else{
72273 iGen = iMeta = 0;
72275 assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
72276 if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
72277 sqlite3DbFree(db, p->zErrMsg);
72278 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
72279 /* If the schema-cookie from the database file matches the cookie
72280 ** stored with the in-memory representation of the schema, do
72281 ** not reload the schema from the database file.
72283 ** If virtual-tables are in use, this is not just an optimization.
72284 ** Often, v-tables store their data in other SQLite tables, which
72285 ** are queried from within xNext() and other v-table methods using
72286 ** prepared queries. If such a query is out-of-date, we do not want to
72287 ** discard the database schema, as the user code implementing the
72288 ** v-table would have to be ready for the sqlite3_vtab structure itself
72289 ** to be invalidated whenever sqlite3_step() is called from within
72290 ** a v-table method.
72292 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
72293 sqlite3ResetOneSchema(db, pOp->p1);
72295 p->expired = 1;
72296 rc = SQLITE_SCHEMA;
72298 break;
72301 /* Opcode: ReadCookie P1 P2 P3 * *
72303 ** Read cookie number P3 from database P1 and write it into register P2.
72304 ** P3==1 is the schema version. P3==2 is the database format.
72305 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
72306 ** the main database file and P1==1 is the database file used to store
72307 ** temporary tables.
72309 ** There must be a read-lock on the database (either a transaction
72310 ** must be started or there must be an open cursor) before
72311 ** executing this instruction.
72313 case OP_ReadCookie: { /* out2-prerelease */
72314 int iMeta;
72315 int iDb;
72316 int iCookie;
72318 assert( p->bIsReader );
72319 iDb = pOp->p1;
72320 iCookie = pOp->p3;
72321 assert( pOp->p3<SQLITE_N_BTREE_META );
72322 assert( iDb>=0 && iDb<db->nDb );
72323 assert( db->aDb[iDb].pBt!=0 );
72324 assert( DbMaskTest(p->btreeMask, iDb) );
72326 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
72327 pOut->u.i = iMeta;
72328 break;
72331 /* Opcode: SetCookie P1 P2 P3 * *
72333 ** Write the content of register P3 (interpreted as an integer)
72334 ** into cookie number P2 of database P1. P2==1 is the schema version.
72335 ** P2==2 is the database format. P2==3 is the recommended pager cache
72336 ** size, and so forth. P1==0 is the main database file and P1==1 is the
72337 ** database file used to store temporary tables.
72339 ** A transaction must be started before executing this opcode.
72341 case OP_SetCookie: { /* in3 */
72342 Db *pDb;
72343 assert( pOp->p2<SQLITE_N_BTREE_META );
72344 assert( pOp->p1>=0 && pOp->p1<db->nDb );
72345 assert( DbMaskTest(p->btreeMask, pOp->p1) );
72346 assert( p->readOnly==0 );
72347 pDb = &db->aDb[pOp->p1];
72348 assert( pDb->pBt!=0 );
72349 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
72350 pIn3 = &aMem[pOp->p3];
72351 sqlite3VdbeMemIntegerify(pIn3);
72352 /* See note about index shifting on OP_ReadCookie */
72353 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
72354 if( pOp->p2==BTREE_SCHEMA_VERSION ){
72355 /* When the schema cookie changes, record the new cookie internally */
72356 pDb->pSchema->schema_cookie = (int)pIn3->u.i;
72357 db->flags |= SQLITE_InternChanges;
72358 }else if( pOp->p2==BTREE_FILE_FORMAT ){
72359 /* Record changes in the file format */
72360 pDb->pSchema->file_format = (u8)pIn3->u.i;
72362 if( pOp->p1==1 ){
72363 /* Invalidate all prepared statements whenever the TEMP database
72364 ** schema is changed. Ticket #1644 */
72365 sqlite3ExpirePreparedStatements(db);
72366 p->expired = 0;
72368 break;
72371 /* Opcode: OpenRead P1 P2 P3 P4 P5
72372 ** Synopsis: root=P2 iDb=P3
72374 ** Open a read-only cursor for the database table whose root page is
72375 ** P2 in a database file. The database file is determined by P3.
72376 ** P3==0 means the main database, P3==1 means the database used for
72377 ** temporary tables, and P3>1 means used the corresponding attached
72378 ** database. Give the new cursor an identifier of P1. The P1
72379 ** values need not be contiguous but all P1 values should be small integers.
72380 ** It is an error for P1 to be negative.
72382 ** If P5!=0 then use the content of register P2 as the root page, not
72383 ** the value of P2 itself.
72385 ** There will be a read lock on the database whenever there is an
72386 ** open cursor. If the database was unlocked prior to this instruction
72387 ** then a read lock is acquired as part of this instruction. A read
72388 ** lock allows other processes to read the database but prohibits
72389 ** any other process from modifying the database. The read lock is
72390 ** released when all cursors are closed. If this instruction attempts
72391 ** to get a read lock but fails, the script terminates with an
72392 ** SQLITE_BUSY error code.
72394 ** The P4 value may be either an integer (P4_INT32) or a pointer to
72395 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
72396 ** structure, then said structure defines the content and collating
72397 ** sequence of the index being opened. Otherwise, if P4 is an integer
72398 ** value, it is set to the number of columns in the table.
72400 ** See also: OpenWrite, ReopenIdx
72402 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
72403 ** Synopsis: root=P2 iDb=P3
72405 ** The ReopenIdx opcode works exactly like ReadOpen except that it first
72406 ** checks to see if the cursor on P1 is already open with a root page
72407 ** number of P2 and if it is this opcode becomes a no-op. In other words,
72408 ** if the cursor is already open, do not reopen it.
72410 ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
72411 ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
72412 ** every other ReopenIdx or OpenRead for the same cursor number.
72414 ** See the OpenRead opcode documentation for additional information.
72416 /* Opcode: OpenWrite P1 P2 P3 P4 P5
72417 ** Synopsis: root=P2 iDb=P3
72419 ** Open a read/write cursor named P1 on the table or index whose root
72420 ** page is P2. Or if P5!=0 use the content of register P2 to find the
72421 ** root page.
72423 ** The P4 value may be either an integer (P4_INT32) or a pointer to
72424 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
72425 ** structure, then said structure defines the content and collating
72426 ** sequence of the index being opened. Otherwise, if P4 is an integer
72427 ** value, it is set to the number of columns in the table, or to the
72428 ** largest index of any column of the table that is actually used.
72430 ** This instruction works just like OpenRead except that it opens the cursor
72431 ** in read/write mode. For a given table, there can be one or more read-only
72432 ** cursors or a single read/write cursor but not both.
72434 ** See also OpenRead.
72436 case OP_ReopenIdx: {
72437 VdbeCursor *pCur;
72439 assert( pOp->p5==0 );
72440 assert( pOp->p4type==P4_KEYINFO );
72441 pCur = p->apCsr[pOp->p1];
72442 if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
72443 assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
72444 break;
72446 /* If the cursor is not currently open or is open on a different
72447 ** index, then fall through into OP_OpenRead to force a reopen */
72449 case OP_OpenRead:
72450 case OP_OpenWrite: {
72451 int nField;
72452 KeyInfo *pKeyInfo;
72453 int p2;
72454 int iDb;
72455 int wrFlag;
72456 Btree *pX;
72457 VdbeCursor *pCur;
72458 Db *pDb;
72460 assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
72461 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
72462 assert( p->bIsReader );
72463 assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
72464 || p->readOnly==0 );
72466 if( p->expired ){
72467 rc = SQLITE_ABORT_ROLLBACK;
72468 break;
72471 nField = 0;
72472 pKeyInfo = 0;
72473 p2 = pOp->p2;
72474 iDb = pOp->p3;
72475 assert( iDb>=0 && iDb<db->nDb );
72476 assert( DbMaskTest(p->btreeMask, iDb) );
72477 pDb = &db->aDb[iDb];
72478 pX = pDb->pBt;
72479 assert( pX!=0 );
72480 if( pOp->opcode==OP_OpenWrite ){
72481 wrFlag = 1;
72482 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
72483 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
72484 p->minWriteFileFormat = pDb->pSchema->file_format;
72486 }else{
72487 wrFlag = 0;
72489 if( pOp->p5 & OPFLAG_P2ISREG ){
72490 assert( p2>0 );
72491 assert( p2<=(p->nMem-p->nCursor) );
72492 pIn2 = &aMem[p2];
72493 assert( memIsValid(pIn2) );
72494 assert( (pIn2->flags & MEM_Int)!=0 );
72495 sqlite3VdbeMemIntegerify(pIn2);
72496 p2 = (int)pIn2->u.i;
72497 /* The p2 value always comes from a prior OP_CreateTable opcode and
72498 ** that opcode will always set the p2 value to 2 or more or else fail.
72499 ** If there were a failure, the prepared statement would have halted
72500 ** before reaching this instruction. */
72501 if( NEVER(p2<2) ) {
72502 rc = SQLITE_CORRUPT_BKPT;
72503 goto abort_due_to_error;
72506 if( pOp->p4type==P4_KEYINFO ){
72507 pKeyInfo = pOp->p4.pKeyInfo;
72508 assert( pKeyInfo->enc==ENC(db) );
72509 assert( pKeyInfo->db==db );
72510 nField = pKeyInfo->nField+pKeyInfo->nXField;
72511 }else if( pOp->p4type==P4_INT32 ){
72512 nField = pOp->p4.i;
72514 assert( pOp->p1>=0 );
72515 assert( nField>=0 );
72516 testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
72517 pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
72518 if( pCur==0 ) goto no_mem;
72519 pCur->nullRow = 1;
72520 pCur->isOrdered = 1;
72521 pCur->pgnoRoot = p2;
72522 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
72523 pCur->pKeyInfo = pKeyInfo;
72524 assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
72525 sqlite3BtreeCursorHints(pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
72527 /* Set the VdbeCursor.isTable variable. Previous versions of
72528 ** SQLite used to check if the root-page flags were sane at this point
72529 ** and report database corruption if they were not, but this check has
72530 ** since moved into the btree layer. */
72531 pCur->isTable = pOp->p4type!=P4_KEYINFO;
72532 break;
72535 /* Opcode: OpenEphemeral P1 P2 * P4 P5
72536 ** Synopsis: nColumn=P2
72538 ** Open a new cursor P1 to a transient table.
72539 ** The cursor is always opened read/write even if
72540 ** the main database is read-only. The ephemeral
72541 ** table is deleted automatically when the cursor is closed.
72543 ** P2 is the number of columns in the ephemeral table.
72544 ** The cursor points to a BTree table if P4==0 and to a BTree index
72545 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
72546 ** that defines the format of keys in the index.
72548 ** The P5 parameter can be a mask of the BTREE_* flags defined
72549 ** in btree.h. These flags control aspects of the operation of
72550 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
72551 ** added automatically.
72553 /* Opcode: OpenAutoindex P1 P2 * P4 *
72554 ** Synopsis: nColumn=P2
72556 ** This opcode works the same as OP_OpenEphemeral. It has a
72557 ** different name to distinguish its use. Tables created using
72558 ** by this opcode will be used for automatically created transient
72559 ** indices in joins.
72561 case OP_OpenAutoindex:
72562 case OP_OpenEphemeral: {
72563 VdbeCursor *pCx;
72564 KeyInfo *pKeyInfo;
72566 static const int vfsFlags =
72567 SQLITE_OPEN_READWRITE |
72568 SQLITE_OPEN_CREATE |
72569 SQLITE_OPEN_EXCLUSIVE |
72570 SQLITE_OPEN_DELETEONCLOSE |
72571 SQLITE_OPEN_TRANSIENT_DB;
72572 assert( pOp->p1>=0 );
72573 assert( pOp->p2>=0 );
72574 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
72575 if( pCx==0 ) goto no_mem;
72576 pCx->nullRow = 1;
72577 pCx->isEphemeral = 1;
72578 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
72579 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
72580 if( rc==SQLITE_OK ){
72581 rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
72583 if( rc==SQLITE_OK ){
72584 /* If a transient index is required, create it by calling
72585 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
72586 ** opening it. If a transient table is required, just use the
72587 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
72589 if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
72590 int pgno;
72591 assert( pOp->p4type==P4_KEYINFO );
72592 rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
72593 if( rc==SQLITE_OK ){
72594 assert( pgno==MASTER_ROOT+1 );
72595 assert( pKeyInfo->db==db );
72596 assert( pKeyInfo->enc==ENC(db) );
72597 pCx->pKeyInfo = pKeyInfo;
72598 rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
72600 pCx->isTable = 0;
72601 }else{
72602 rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
72603 pCx->isTable = 1;
72606 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
72607 break;
72610 /* Opcode: SorterOpen P1 P2 P3 P4 *
72612 ** This opcode works like OP_OpenEphemeral except that it opens
72613 ** a transient index that is specifically designed to sort large
72614 ** tables using an external merge-sort algorithm.
72616 ** If argument P3 is non-zero, then it indicates that the sorter may
72617 ** assume that a stable sort considering the first P3 fields of each
72618 ** key is sufficient to produce the required results.
72620 case OP_SorterOpen: {
72621 VdbeCursor *pCx;
72623 assert( pOp->p1>=0 );
72624 assert( pOp->p2>=0 );
72625 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
72626 if( pCx==0 ) goto no_mem;
72627 pCx->pKeyInfo = pOp->p4.pKeyInfo;
72628 assert( pCx->pKeyInfo->db==db );
72629 assert( pCx->pKeyInfo->enc==ENC(db) );
72630 rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
72631 break;
72634 /* Opcode: SequenceTest P1 P2 * * *
72635 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
72637 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
72638 ** to P2. Regardless of whether or not the jump is taken, increment the
72639 ** the sequence value.
72641 case OP_SequenceTest: {
72642 VdbeCursor *pC;
72643 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72644 pC = p->apCsr[pOp->p1];
72645 assert( pC->pSorter );
72646 if( (pC->seqCount++)==0 ){
72647 pc = pOp->p2 - 1;
72649 break;
72652 /* Opcode: OpenPseudo P1 P2 P3 * *
72653 ** Synopsis: P3 columns in r[P2]
72655 ** Open a new cursor that points to a fake table that contains a single
72656 ** row of data. The content of that one row is the content of memory
72657 ** register P2. In other words, cursor P1 becomes an alias for the
72658 ** MEM_Blob content contained in register P2.
72660 ** A pseudo-table created by this opcode is used to hold a single
72661 ** row output from the sorter so that the row can be decomposed into
72662 ** individual columns using the OP_Column opcode. The OP_Column opcode
72663 ** is the only cursor opcode that works with a pseudo-table.
72665 ** P3 is the number of fields in the records that will be stored by
72666 ** the pseudo-table.
72668 case OP_OpenPseudo: {
72669 VdbeCursor *pCx;
72671 assert( pOp->p1>=0 );
72672 assert( pOp->p3>=0 );
72673 pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
72674 if( pCx==0 ) goto no_mem;
72675 pCx->nullRow = 1;
72676 pCx->pseudoTableReg = pOp->p2;
72677 pCx->isTable = 1;
72678 assert( pOp->p5==0 );
72679 break;
72682 /* Opcode: Close P1 * * * *
72684 ** Close a cursor previously opened as P1. If P1 is not
72685 ** currently open, this instruction is a no-op.
72687 case OP_Close: {
72688 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72689 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
72690 p->apCsr[pOp->p1] = 0;
72691 break;
72694 /* Opcode: SeekGE P1 P2 P3 P4 *
72695 ** Synopsis: key=r[P3@P4]
72697 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
72698 ** use the value in register P3 as the key. If cursor P1 refers
72699 ** to an SQL index, then P3 is the first in an array of P4 registers
72700 ** that are used as an unpacked index key.
72702 ** Reposition cursor P1 so that it points to the smallest entry that
72703 ** is greater than or equal to the key value. If there are no records
72704 ** greater than or equal to the key and P2 is not zero, then jump to P2.
72706 ** This opcode leaves the cursor configured to move in forward order,
72707 ** from the beginning toward the end. In other words, the cursor is
72708 ** configured to use Next, not Prev.
72710 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
72712 /* Opcode: SeekGT P1 P2 P3 P4 *
72713 ** Synopsis: key=r[P3@P4]
72715 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
72716 ** use the value in register P3 as a key. If cursor P1 refers
72717 ** to an SQL index, then P3 is the first in an array of P4 registers
72718 ** that are used as an unpacked index key.
72720 ** Reposition cursor P1 so that it points to the smallest entry that
72721 ** is greater than the key value. If there are no records greater than
72722 ** the key and P2 is not zero, then jump to P2.
72724 ** This opcode leaves the cursor configured to move in forward order,
72725 ** from the beginning toward the end. In other words, the cursor is
72726 ** configured to use Next, not Prev.
72728 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
72730 /* Opcode: SeekLT P1 P2 P3 P4 *
72731 ** Synopsis: key=r[P3@P4]
72733 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
72734 ** use the value in register P3 as a key. If cursor P1 refers
72735 ** to an SQL index, then P3 is the first in an array of P4 registers
72736 ** that are used as an unpacked index key.
72738 ** Reposition cursor P1 so that it points to the largest entry that
72739 ** is less than the key value. If there are no records less than
72740 ** the key and P2 is not zero, then jump to P2.
72742 ** This opcode leaves the cursor configured to move in reverse order,
72743 ** from the end toward the beginning. In other words, the cursor is
72744 ** configured to use Prev, not Next.
72746 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
72748 /* Opcode: SeekLE P1 P2 P3 P4 *
72749 ** Synopsis: key=r[P3@P4]
72751 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
72752 ** use the value in register P3 as a key. If cursor P1 refers
72753 ** to an SQL index, then P3 is the first in an array of P4 registers
72754 ** that are used as an unpacked index key.
72756 ** Reposition cursor P1 so that it points to the largest entry that
72757 ** is less than or equal to the key value. If there are no records
72758 ** less than or equal to the key and P2 is not zero, then jump to P2.
72760 ** This opcode leaves the cursor configured to move in reverse order,
72761 ** from the end toward the beginning. In other words, the cursor is
72762 ** configured to use Prev, not Next.
72764 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
72766 case OP_SeekLT: /* jump, in3 */
72767 case OP_SeekLE: /* jump, in3 */
72768 case OP_SeekGE: /* jump, in3 */
72769 case OP_SeekGT: { /* jump, in3 */
72770 int res;
72771 int oc;
72772 VdbeCursor *pC;
72773 UnpackedRecord r;
72774 int nField;
72775 i64 iKey; /* The rowid we are to seek to */
72777 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72778 assert( pOp->p2!=0 );
72779 pC = p->apCsr[pOp->p1];
72780 assert( pC!=0 );
72781 assert( pC->pseudoTableReg==0 );
72782 assert( OP_SeekLE == OP_SeekLT+1 );
72783 assert( OP_SeekGE == OP_SeekLT+2 );
72784 assert( OP_SeekGT == OP_SeekLT+3 );
72785 assert( pC->isOrdered );
72786 assert( pC->pCursor!=0 );
72787 oc = pOp->opcode;
72788 pC->nullRow = 0;
72789 #ifdef SQLITE_DEBUG
72790 pC->seekOp = pOp->opcode;
72791 #endif
72792 if( pC->isTable ){
72793 /* The input value in P3 might be of any type: integer, real, string,
72794 ** blob, or NULL. But it needs to be an integer before we can do
72795 ** the seek, so convert it. */
72796 pIn3 = &aMem[pOp->p3];
72797 if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
72798 applyNumericAffinity(pIn3, 0);
72800 iKey = sqlite3VdbeIntValue(pIn3);
72802 /* If the P3 value could not be converted into an integer without
72803 ** loss of information, then special processing is required... */
72804 if( (pIn3->flags & MEM_Int)==0 ){
72805 if( (pIn3->flags & MEM_Real)==0 ){
72806 /* If the P3 value cannot be converted into any kind of a number,
72807 ** then the seek is not possible, so jump to P2 */
72808 pc = pOp->p2 - 1; VdbeBranchTaken(1,2);
72809 break;
72812 /* If the approximation iKey is larger than the actual real search
72813 ** term, substitute >= for > and < for <=. e.g. if the search term
72814 ** is 4.9 and the integer approximation 5:
72816 ** (x > 4.9) -> (x >= 5)
72817 ** (x <= 4.9) -> (x < 5)
72819 if( pIn3->u.r<(double)iKey ){
72820 assert( OP_SeekGE==(OP_SeekGT-1) );
72821 assert( OP_SeekLT==(OP_SeekLE-1) );
72822 assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
72823 if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
72826 /* If the approximation iKey is smaller than the actual real search
72827 ** term, substitute <= for < and > for >=. */
72828 else if( pIn3->u.r>(double)iKey ){
72829 assert( OP_SeekLE==(OP_SeekLT+1) );
72830 assert( OP_SeekGT==(OP_SeekGE+1) );
72831 assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
72832 if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
72835 rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
72836 pC->movetoTarget = iKey; /* Used by OP_Delete */
72837 if( rc!=SQLITE_OK ){
72838 goto abort_due_to_error;
72840 }else{
72841 nField = pOp->p4.i;
72842 assert( pOp->p4type==P4_INT32 );
72843 assert( nField>0 );
72844 r.pKeyInfo = pC->pKeyInfo;
72845 r.nField = (u16)nField;
72847 /* The next line of code computes as follows, only faster:
72848 ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
72849 ** r.default_rc = -1;
72850 ** }else{
72851 ** r.default_rc = +1;
72852 ** }
72854 r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
72855 assert( oc!=OP_SeekGT || r.default_rc==-1 );
72856 assert( oc!=OP_SeekLE || r.default_rc==-1 );
72857 assert( oc!=OP_SeekGE || r.default_rc==+1 );
72858 assert( oc!=OP_SeekLT || r.default_rc==+1 );
72860 r.aMem = &aMem[pOp->p3];
72861 #ifdef SQLITE_DEBUG
72862 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
72863 #endif
72864 ExpandBlob(r.aMem);
72865 rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
72866 if( rc!=SQLITE_OK ){
72867 goto abort_due_to_error;
72870 pC->deferredMoveto = 0;
72871 pC->cacheStatus = CACHE_STALE;
72872 #ifdef SQLITE_TEST
72873 sqlite3_search_count++;
72874 #endif
72875 if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
72876 if( res<0 || (res==0 && oc==OP_SeekGT) ){
72877 res = 0;
72878 rc = sqlite3BtreeNext(pC->pCursor, &res);
72879 if( rc!=SQLITE_OK ) goto abort_due_to_error;
72880 }else{
72881 res = 0;
72883 }else{
72884 assert( oc==OP_SeekLT || oc==OP_SeekLE );
72885 if( res>0 || (res==0 && oc==OP_SeekLT) ){
72886 res = 0;
72887 rc = sqlite3BtreePrevious(pC->pCursor, &res);
72888 if( rc!=SQLITE_OK ) goto abort_due_to_error;
72889 }else{
72890 /* res might be negative because the table is empty. Check to
72891 ** see if this is the case.
72893 res = sqlite3BtreeEof(pC->pCursor);
72896 assert( pOp->p2>0 );
72897 VdbeBranchTaken(res!=0,2);
72898 if( res ){
72899 pc = pOp->p2 - 1;
72901 break;
72904 /* Opcode: Seek P1 P2 * * *
72905 ** Synopsis: intkey=r[P2]
72907 ** P1 is an open table cursor and P2 is a rowid integer. Arrange
72908 ** for P1 to move so that it points to the rowid given by P2.
72910 ** This is actually a deferred seek. Nothing actually happens until
72911 ** the cursor is used to read a record. That way, if no reads
72912 ** occur, no unnecessary I/O happens.
72914 case OP_Seek: { /* in2 */
72915 VdbeCursor *pC;
72917 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72918 pC = p->apCsr[pOp->p1];
72919 assert( pC!=0 );
72920 assert( pC->pCursor!=0 );
72921 assert( pC->isTable );
72922 pC->nullRow = 0;
72923 pIn2 = &aMem[pOp->p2];
72924 pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
72925 pC->deferredMoveto = 1;
72926 break;
72930 /* Opcode: Found P1 P2 P3 P4 *
72931 ** Synopsis: key=r[P3@P4]
72933 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
72934 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
72935 ** record.
72937 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
72938 ** is a prefix of any entry in P1 then a jump is made to P2 and
72939 ** P1 is left pointing at the matching entry.
72941 ** This operation leaves the cursor in a state where it can be
72942 ** advanced in the forward direction. The Next instruction will work,
72943 ** but not the Prev instruction.
72945 ** See also: NotFound, NoConflict, NotExists. SeekGe
72947 /* Opcode: NotFound P1 P2 P3 P4 *
72948 ** Synopsis: key=r[P3@P4]
72950 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
72951 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
72952 ** record.
72954 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
72955 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
72956 ** does contain an entry whose prefix matches the P3/P4 record then control
72957 ** falls through to the next instruction and P1 is left pointing at the
72958 ** matching entry.
72960 ** This operation leaves the cursor in a state where it cannot be
72961 ** advanced in either direction. In other words, the Next and Prev
72962 ** opcodes do not work after this operation.
72964 ** See also: Found, NotExists, NoConflict
72966 /* Opcode: NoConflict P1 P2 P3 P4 *
72967 ** Synopsis: key=r[P3@P4]
72969 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
72970 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
72971 ** record.
72973 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
72974 ** contains any NULL value, jump immediately to P2. If all terms of the
72975 ** record are not-NULL then a check is done to determine if any row in the
72976 ** P1 index btree has a matching key prefix. If there are no matches, jump
72977 ** immediately to P2. If there is a match, fall through and leave the P1
72978 ** cursor pointing to the matching row.
72980 ** This opcode is similar to OP_NotFound with the exceptions that the
72981 ** branch is always taken if any part of the search key input is NULL.
72983 ** This operation leaves the cursor in a state where it cannot be
72984 ** advanced in either direction. In other words, the Next and Prev
72985 ** opcodes do not work after this operation.
72987 ** See also: NotFound, Found, NotExists
72989 case OP_NoConflict: /* jump, in3 */
72990 case OP_NotFound: /* jump, in3 */
72991 case OP_Found: { /* jump, in3 */
72992 int alreadyExists;
72993 int ii;
72994 VdbeCursor *pC;
72995 int res;
72996 char *pFree;
72997 UnpackedRecord *pIdxKey;
72998 UnpackedRecord r;
72999 char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
73001 #ifdef SQLITE_TEST
73002 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
73003 #endif
73005 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73006 assert( pOp->p4type==P4_INT32 );
73007 pC = p->apCsr[pOp->p1];
73008 assert( pC!=0 );
73009 #ifdef SQLITE_DEBUG
73010 pC->seekOp = pOp->opcode;
73011 #endif
73012 pIn3 = &aMem[pOp->p3];
73013 assert( pC->pCursor!=0 );
73014 assert( pC->isTable==0 );
73015 pFree = 0; /* Not needed. Only used to suppress a compiler warning. */
73016 if( pOp->p4.i>0 ){
73017 r.pKeyInfo = pC->pKeyInfo;
73018 r.nField = (u16)pOp->p4.i;
73019 r.aMem = pIn3;
73020 for(ii=0; ii<r.nField; ii++){
73021 assert( memIsValid(&r.aMem[ii]) );
73022 ExpandBlob(&r.aMem[ii]);
73023 #ifdef SQLITE_DEBUG
73024 if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
73025 #endif
73027 pIdxKey = &r;
73028 }else{
73029 pIdxKey = sqlite3VdbeAllocUnpackedRecord(
73030 pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
73032 if( pIdxKey==0 ) goto no_mem;
73033 assert( pIn3->flags & MEM_Blob );
73034 assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
73035 sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
73037 pIdxKey->default_rc = 0;
73038 if( pOp->opcode==OP_NoConflict ){
73039 /* For the OP_NoConflict opcode, take the jump if any of the
73040 ** input fields are NULL, since any key with a NULL will not
73041 ** conflict */
73042 for(ii=0; ii<r.nField; ii++){
73043 if( r.aMem[ii].flags & MEM_Null ){
73044 pc = pOp->p2 - 1; VdbeBranchTaken(1,2);
73045 break;
73049 rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
73050 if( pOp->p4.i==0 ){
73051 sqlite3DbFree(db, pFree);
73053 if( rc!=SQLITE_OK ){
73054 break;
73056 pC->seekResult = res;
73057 alreadyExists = (res==0);
73058 pC->nullRow = 1-alreadyExists;
73059 pC->deferredMoveto = 0;
73060 pC->cacheStatus = CACHE_STALE;
73061 if( pOp->opcode==OP_Found ){
73062 VdbeBranchTaken(alreadyExists!=0,2);
73063 if( alreadyExists ) pc = pOp->p2 - 1;
73064 }else{
73065 VdbeBranchTaken(alreadyExists==0,2);
73066 if( !alreadyExists ) pc = pOp->p2 - 1;
73068 break;
73071 /* Opcode: NotExists P1 P2 P3 * *
73072 ** Synopsis: intkey=r[P3]
73074 ** P1 is the index of a cursor open on an SQL table btree (with integer
73075 ** keys). P3 is an integer rowid. If P1 does not contain a record with
73076 ** rowid P3 then jump immediately to P2. If P1 does contain a record
73077 ** with rowid P3 then leave the cursor pointing at that record and fall
73078 ** through to the next instruction.
73080 ** The OP_NotFound opcode performs the same operation on index btrees
73081 ** (with arbitrary multi-value keys).
73083 ** This opcode leaves the cursor in a state where it cannot be advanced
73084 ** in either direction. In other words, the Next and Prev opcodes will
73085 ** not work following this opcode.
73087 ** See also: Found, NotFound, NoConflict
73089 case OP_NotExists: { /* jump, in3 */
73090 VdbeCursor *pC;
73091 BtCursor *pCrsr;
73092 int res;
73093 u64 iKey;
73095 pIn3 = &aMem[pOp->p3];
73096 assert( pIn3->flags & MEM_Int );
73097 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73098 pC = p->apCsr[pOp->p1];
73099 assert( pC!=0 );
73100 #ifdef SQLITE_DEBUG
73101 pC->seekOp = 0;
73102 #endif
73103 assert( pC->isTable );
73104 assert( pC->pseudoTableReg==0 );
73105 pCrsr = pC->pCursor;
73106 assert( pCrsr!=0 );
73107 res = 0;
73108 iKey = pIn3->u.i;
73109 rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
73110 pC->movetoTarget = iKey; /* Used by OP_Delete */
73111 pC->nullRow = 0;
73112 pC->cacheStatus = CACHE_STALE;
73113 pC->deferredMoveto = 0;
73114 VdbeBranchTaken(res!=0,2);
73115 if( res!=0 ){
73116 pc = pOp->p2 - 1;
73118 pC->seekResult = res;
73119 break;
73122 /* Opcode: Sequence P1 P2 * * *
73123 ** Synopsis: r[P2]=cursor[P1].ctr++
73125 ** Find the next available sequence number for cursor P1.
73126 ** Write the sequence number into register P2.
73127 ** The sequence number on the cursor is incremented after this
73128 ** instruction.
73130 case OP_Sequence: { /* out2-prerelease */
73131 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73132 assert( p->apCsr[pOp->p1]!=0 );
73133 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
73134 break;
73138 /* Opcode: NewRowid P1 P2 P3 * *
73139 ** Synopsis: r[P2]=rowid
73141 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
73142 ** The record number is not previously used as a key in the database
73143 ** table that cursor P1 points to. The new record number is written
73144 ** written to register P2.
73146 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
73147 ** the largest previously generated record number. No new record numbers are
73148 ** allowed to be less than this value. When this value reaches its maximum,
73149 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
73150 ** generated record number. This P3 mechanism is used to help implement the
73151 ** AUTOINCREMENT feature.
73153 case OP_NewRowid: { /* out2-prerelease */
73154 i64 v; /* The new rowid */
73155 VdbeCursor *pC; /* Cursor of table to get the new rowid */
73156 int res; /* Result of an sqlite3BtreeLast() */
73157 int cnt; /* Counter to limit the number of searches */
73158 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
73159 VdbeFrame *pFrame; /* Root frame of VDBE */
73161 v = 0;
73162 res = 0;
73163 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73164 pC = p->apCsr[pOp->p1];
73165 assert( pC!=0 );
73166 if( NEVER(pC->pCursor==0) ){
73167 /* The zero initialization above is all that is needed */
73168 }else{
73169 /* The next rowid or record number (different terms for the same
73170 ** thing) is obtained in a two-step algorithm.
73172 ** First we attempt to find the largest existing rowid and add one
73173 ** to that. But if the largest existing rowid is already the maximum
73174 ** positive integer, we have to fall through to the second
73175 ** probabilistic algorithm
73177 ** The second algorithm is to select a rowid at random and see if
73178 ** it already exists in the table. If it does not exist, we have
73179 ** succeeded. If the random rowid does exist, we select a new one
73180 ** and try again, up to 100 times.
73182 assert( pC->isTable );
73184 #ifdef SQLITE_32BIT_ROWID
73185 # define MAX_ROWID 0x7fffffff
73186 #else
73187 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
73188 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
73189 ** to provide the constant while making all compilers happy.
73191 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
73192 #endif
73194 if( !pC->useRandomRowid ){
73195 rc = sqlite3BtreeLast(pC->pCursor, &res);
73196 if( rc!=SQLITE_OK ){
73197 goto abort_due_to_error;
73199 if( res ){
73200 v = 1; /* IMP: R-61914-48074 */
73201 }else{
73202 assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
73203 rc = sqlite3BtreeKeySize(pC->pCursor, &v);
73204 assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
73205 if( v>=MAX_ROWID ){
73206 pC->useRandomRowid = 1;
73207 }else{
73208 v++; /* IMP: R-29538-34987 */
73213 #ifndef SQLITE_OMIT_AUTOINCREMENT
73214 if( pOp->p3 ){
73215 /* Assert that P3 is a valid memory cell. */
73216 assert( pOp->p3>0 );
73217 if( p->pFrame ){
73218 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
73219 /* Assert that P3 is a valid memory cell. */
73220 assert( pOp->p3<=pFrame->nMem );
73221 pMem = &pFrame->aMem[pOp->p3];
73222 }else{
73223 /* Assert that P3 is a valid memory cell. */
73224 assert( pOp->p3<=(p->nMem-p->nCursor) );
73225 pMem = &aMem[pOp->p3];
73226 memAboutToChange(p, pMem);
73228 assert( memIsValid(pMem) );
73230 REGISTER_TRACE(pOp->p3, pMem);
73231 sqlite3VdbeMemIntegerify(pMem);
73232 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
73233 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
73234 rc = SQLITE_FULL; /* IMP: R-12275-61338 */
73235 goto abort_due_to_error;
73237 if( v<pMem->u.i+1 ){
73238 v = pMem->u.i + 1;
73240 pMem->u.i = v;
73242 #endif
73243 if( pC->useRandomRowid ){
73244 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
73245 ** largest possible integer (9223372036854775807) then the database
73246 ** engine starts picking positive candidate ROWIDs at random until
73247 ** it finds one that is not previously used. */
73248 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
73249 ** an AUTOINCREMENT table. */
73250 cnt = 0;
73252 sqlite3_randomness(sizeof(v), &v);
73253 v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
73254 }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
73255 0, &res))==SQLITE_OK)
73256 && (res==0)
73257 && (++cnt<100));
73258 if( rc==SQLITE_OK && res==0 ){
73259 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
73260 goto abort_due_to_error;
73262 assert( v>0 ); /* EV: R-40812-03570 */
73264 pC->deferredMoveto = 0;
73265 pC->cacheStatus = CACHE_STALE;
73267 pOut->u.i = v;
73268 break;
73271 /* Opcode: Insert P1 P2 P3 P4 P5
73272 ** Synopsis: intkey=r[P3] data=r[P2]
73274 ** Write an entry into the table of cursor P1. A new entry is
73275 ** created if it doesn't already exist or the data for an existing
73276 ** entry is overwritten. The data is the value MEM_Blob stored in register
73277 ** number P2. The key is stored in register P3. The key must
73278 ** be a MEM_Int.
73280 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
73281 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
73282 ** then rowid is stored for subsequent return by the
73283 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
73285 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
73286 ** the last seek operation (OP_NotExists) was a success, then this
73287 ** operation will not attempt to find the appropriate row before doing
73288 ** the insert but will instead overwrite the row that the cursor is
73289 ** currently pointing to. Presumably, the prior OP_NotExists opcode
73290 ** has already positioned the cursor correctly. This is an optimization
73291 ** that boosts performance by avoiding redundant seeks.
73293 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
73294 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
73295 ** is part of an INSERT operation. The difference is only important to
73296 ** the update hook.
73298 ** Parameter P4 may point to a string containing the table-name, or
73299 ** may be NULL. If it is not NULL, then the update-hook
73300 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
73302 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
73303 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
73304 ** and register P2 becomes ephemeral. If the cursor is changed, the
73305 ** value of register P2 will then change. Make sure this does not
73306 ** cause any problems.)
73308 ** This instruction only works on tables. The equivalent instruction
73309 ** for indices is OP_IdxInsert.
73311 /* Opcode: InsertInt P1 P2 P3 P4 P5
73312 ** Synopsis: intkey=P3 data=r[P2]
73314 ** This works exactly like OP_Insert except that the key is the
73315 ** integer value P3, not the value of the integer stored in register P3.
73317 case OP_Insert:
73318 case OP_InsertInt: {
73319 Mem *pData; /* MEM cell holding data for the record to be inserted */
73320 Mem *pKey; /* MEM cell holding key for the record */
73321 i64 iKey; /* The integer ROWID or key for the record to be inserted */
73322 VdbeCursor *pC; /* Cursor to table into which insert is written */
73323 int nZero; /* Number of zero-bytes to append */
73324 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
73325 const char *zDb; /* database name - used by the update hook */
73326 const char *zTbl; /* Table name - used by the opdate hook */
73327 int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
73329 pData = &aMem[pOp->p2];
73330 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73331 assert( memIsValid(pData) );
73332 pC = p->apCsr[pOp->p1];
73333 assert( pC!=0 );
73334 assert( pC->pCursor!=0 );
73335 assert( pC->pseudoTableReg==0 );
73336 assert( pC->isTable );
73337 REGISTER_TRACE(pOp->p2, pData);
73339 if( pOp->opcode==OP_Insert ){
73340 pKey = &aMem[pOp->p3];
73341 assert( pKey->flags & MEM_Int );
73342 assert( memIsValid(pKey) );
73343 REGISTER_TRACE(pOp->p3, pKey);
73344 iKey = pKey->u.i;
73345 }else{
73346 assert( pOp->opcode==OP_InsertInt );
73347 iKey = pOp->p3;
73350 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
73351 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
73352 if( pData->flags & MEM_Null ){
73353 pData->z = 0;
73354 pData->n = 0;
73355 }else{
73356 assert( pData->flags & (MEM_Blob|MEM_Str) );
73358 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
73359 if( pData->flags & MEM_Zero ){
73360 nZero = pData->u.nZero;
73361 }else{
73362 nZero = 0;
73364 rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
73365 pData->z, pData->n, nZero,
73366 (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
73368 pC->deferredMoveto = 0;
73369 pC->cacheStatus = CACHE_STALE;
73371 /* Invoke the update-hook if required. */
73372 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
73373 zDb = db->aDb[pC->iDb].zName;
73374 zTbl = pOp->p4.z;
73375 op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
73376 assert( pC->isTable );
73377 db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
73378 assert( pC->iDb>=0 );
73380 break;
73383 /* Opcode: Delete P1 P2 * P4 *
73385 ** Delete the record at which the P1 cursor is currently pointing.
73387 ** The cursor will be left pointing at either the next or the previous
73388 ** record in the table. If it is left pointing at the next record, then
73389 ** the next Next instruction will be a no-op. Hence it is OK to delete
73390 ** a record from within a Next loop.
73392 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
73393 ** incremented (otherwise not).
73395 ** P1 must not be pseudo-table. It has to be a real table with
73396 ** multiple rows.
73398 ** If P4 is not NULL, then it is the name of the table that P1 is
73399 ** pointing to. The update hook will be invoked, if it exists.
73400 ** If P4 is not NULL then the P1 cursor must have been positioned
73401 ** using OP_NotFound prior to invoking this opcode.
73403 case OP_Delete: {
73404 VdbeCursor *pC;
73406 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73407 pC = p->apCsr[pOp->p1];
73408 assert( pC!=0 );
73409 assert( pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
73410 assert( pC->deferredMoveto==0 );
73412 #ifdef SQLITE_DEBUG
73413 /* The seek operation that positioned the cursor prior to OP_Delete will
73414 ** have also set the pC->movetoTarget field to the rowid of the row that
73415 ** is being deleted */
73416 if( pOp->p4.z && pC->isTable ){
73417 i64 iKey = 0;
73418 sqlite3BtreeKeySize(pC->pCursor, &iKey);
73419 assert( pC->movetoTarget==iKey );
73421 #endif
73423 rc = sqlite3BtreeDelete(pC->pCursor);
73424 pC->cacheStatus = CACHE_STALE;
73426 /* Invoke the update-hook if required. */
73427 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z && pC->isTable ){
73428 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
73429 db->aDb[pC->iDb].zName, pOp->p4.z, pC->movetoTarget);
73430 assert( pC->iDb>=0 );
73432 if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
73433 break;
73435 /* Opcode: ResetCount * * * * *
73437 ** The value of the change counter is copied to the database handle
73438 ** change counter (returned by subsequent calls to sqlite3_changes()).
73439 ** Then the VMs internal change counter resets to 0.
73440 ** This is used by trigger programs.
73442 case OP_ResetCount: {
73443 sqlite3VdbeSetChanges(db, p->nChange);
73444 p->nChange = 0;
73445 break;
73448 /* Opcode: SorterCompare P1 P2 P3 P4
73449 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
73451 ** P1 is a sorter cursor. This instruction compares a prefix of the
73452 ** record blob in register P3 against a prefix of the entry that
73453 ** the sorter cursor currently points to. Only the first P4 fields
73454 ** of r[P3] and the sorter record are compared.
73456 ** If either P3 or the sorter contains a NULL in one of their significant
73457 ** fields (not counting the P4 fields at the end which are ignored) then
73458 ** the comparison is assumed to be equal.
73460 ** Fall through to next instruction if the two records compare equal to
73461 ** each other. Jump to P2 if they are different.
73463 case OP_SorterCompare: {
73464 VdbeCursor *pC;
73465 int res;
73466 int nKeyCol;
73468 pC = p->apCsr[pOp->p1];
73469 assert( isSorter(pC) );
73470 assert( pOp->p4type==P4_INT32 );
73471 pIn3 = &aMem[pOp->p3];
73472 nKeyCol = pOp->p4.i;
73473 res = 0;
73474 rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
73475 VdbeBranchTaken(res!=0,2);
73476 if( res ){
73477 pc = pOp->p2-1;
73479 break;
73482 /* Opcode: SorterData P1 P2 P3 * *
73483 ** Synopsis: r[P2]=data
73485 ** Write into register P2 the current sorter data for sorter cursor P1.
73486 ** Then clear the column header cache on cursor P3.
73488 ** This opcode is normally use to move a record out of the sorter and into
73489 ** a register that is the source for a pseudo-table cursor created using
73490 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
73491 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
73492 ** us from having to issue a separate NullRow instruction to clear that cache.
73494 case OP_SorterData: {
73495 VdbeCursor *pC;
73497 pOut = &aMem[pOp->p2];
73498 pC = p->apCsr[pOp->p1];
73499 assert( isSorter(pC) );
73500 rc = sqlite3VdbeSorterRowkey(pC, pOut);
73501 assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
73502 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73503 p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
73504 break;
73507 /* Opcode: RowData P1 P2 * * *
73508 ** Synopsis: r[P2]=data
73510 ** Write into register P2 the complete row data for cursor P1.
73511 ** There is no interpretation of the data.
73512 ** It is just copied onto the P2 register exactly as
73513 ** it is found in the database file.
73515 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
73516 ** of a real table, not a pseudo-table.
73518 /* Opcode: RowKey P1 P2 * * *
73519 ** Synopsis: r[P2]=key
73521 ** Write into register P2 the complete row key for cursor P1.
73522 ** There is no interpretation of the data.
73523 ** The key is copied onto the P2 register exactly as
73524 ** it is found in the database file.
73526 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
73527 ** of a real table, not a pseudo-table.
73529 case OP_RowKey:
73530 case OP_RowData: {
73531 VdbeCursor *pC;
73532 BtCursor *pCrsr;
73533 u32 n;
73534 i64 n64;
73536 pOut = &aMem[pOp->p2];
73537 memAboutToChange(p, pOut);
73539 /* Note that RowKey and RowData are really exactly the same instruction */
73540 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73541 pC = p->apCsr[pOp->p1];
73542 assert( isSorter(pC)==0 );
73543 assert( pC->isTable || pOp->opcode!=OP_RowData );
73544 assert( pC->isTable==0 || pOp->opcode==OP_RowData );
73545 assert( pC!=0 );
73546 assert( pC->nullRow==0 );
73547 assert( pC->pseudoTableReg==0 );
73548 assert( pC->pCursor!=0 );
73549 pCrsr = pC->pCursor;
73551 /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
73552 ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
73553 ** the cursor. If this where not the case, on of the following assert()s
73554 ** would fail. Should this ever change (because of changes in the code
73555 ** generator) then the fix would be to insert a call to
73556 ** sqlite3VdbeCursorMoveto().
73558 assert( pC->deferredMoveto==0 );
73559 assert( sqlite3BtreeCursorIsValid(pCrsr) );
73560 #if 0 /* Not required due to the previous to assert() statements */
73561 rc = sqlite3VdbeCursorMoveto(pC);
73562 if( rc!=SQLITE_OK ) goto abort_due_to_error;
73563 #endif
73565 if( pC->isTable==0 ){
73566 assert( !pC->isTable );
73567 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
73568 assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
73569 if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
73570 goto too_big;
73572 n = (u32)n64;
73573 }else{
73574 VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
73575 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
73576 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
73577 goto too_big;
73580 testcase( n==0 );
73581 if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
73582 goto no_mem;
73584 pOut->n = n;
73585 MemSetTypeFlag(pOut, MEM_Blob);
73586 if( pC->isTable==0 ){
73587 rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
73588 }else{
73589 rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
73591 pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
73592 UPDATE_MAX_BLOBSIZE(pOut);
73593 REGISTER_TRACE(pOp->p2, pOut);
73594 break;
73597 /* Opcode: Rowid P1 P2 * * *
73598 ** Synopsis: r[P2]=rowid
73600 ** Store in register P2 an integer which is the key of the table entry that
73601 ** P1 is currently point to.
73603 ** P1 can be either an ordinary table or a virtual table. There used to
73604 ** be a separate OP_VRowid opcode for use with virtual tables, but this
73605 ** one opcode now works for both table types.
73607 case OP_Rowid: { /* out2-prerelease */
73608 VdbeCursor *pC;
73609 i64 v;
73610 sqlite3_vtab *pVtab;
73611 const sqlite3_module *pModule;
73613 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73614 pC = p->apCsr[pOp->p1];
73615 assert( pC!=0 );
73616 assert( pC->pseudoTableReg==0 || pC->nullRow );
73617 if( pC->nullRow ){
73618 pOut->flags = MEM_Null;
73619 break;
73620 }else if( pC->deferredMoveto ){
73621 v = pC->movetoTarget;
73622 #ifndef SQLITE_OMIT_VIRTUALTABLE
73623 }else if( pC->pVtabCursor ){
73624 pVtab = pC->pVtabCursor->pVtab;
73625 pModule = pVtab->pModule;
73626 assert( pModule->xRowid );
73627 rc = pModule->xRowid(pC->pVtabCursor, &v);
73628 sqlite3VtabImportErrmsg(p, pVtab);
73629 #endif /* SQLITE_OMIT_VIRTUALTABLE */
73630 }else{
73631 assert( pC->pCursor!=0 );
73632 rc = sqlite3VdbeCursorRestore(pC);
73633 if( rc ) goto abort_due_to_error;
73634 if( pC->nullRow ){
73635 pOut->flags = MEM_Null;
73636 break;
73638 rc = sqlite3BtreeKeySize(pC->pCursor, &v);
73639 assert( rc==SQLITE_OK ); /* Always so because of CursorRestore() above */
73641 pOut->u.i = v;
73642 break;
73645 /* Opcode: NullRow P1 * * * *
73647 ** Move the cursor P1 to a null row. Any OP_Column operations
73648 ** that occur while the cursor is on the null row will always
73649 ** write a NULL.
73651 case OP_NullRow: {
73652 VdbeCursor *pC;
73654 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73655 pC = p->apCsr[pOp->p1];
73656 assert( pC!=0 );
73657 pC->nullRow = 1;
73658 pC->cacheStatus = CACHE_STALE;
73659 if( pC->pCursor ){
73660 sqlite3BtreeClearCursor(pC->pCursor);
73662 break;
73665 /* Opcode: Last P1 P2 * * *
73667 ** The next use of the Rowid or Column or Prev instruction for P1
73668 ** will refer to the last entry in the database table or index.
73669 ** If the table or index is empty and P2>0, then jump immediately to P2.
73670 ** If P2 is 0 or if the table or index is not empty, fall through
73671 ** to the following instruction.
73673 ** This opcode leaves the cursor configured to move in reverse order,
73674 ** from the end toward the beginning. In other words, the cursor is
73675 ** configured to use Prev, not Next.
73677 case OP_Last: { /* jump */
73678 VdbeCursor *pC;
73679 BtCursor *pCrsr;
73680 int res;
73682 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73683 pC = p->apCsr[pOp->p1];
73684 assert( pC!=0 );
73685 pCrsr = pC->pCursor;
73686 res = 0;
73687 assert( pCrsr!=0 );
73688 rc = sqlite3BtreeLast(pCrsr, &res);
73689 pC->nullRow = (u8)res;
73690 pC->deferredMoveto = 0;
73691 pC->cacheStatus = CACHE_STALE;
73692 #ifdef SQLITE_DEBUG
73693 pC->seekOp = OP_Last;
73694 #endif
73695 if( pOp->p2>0 ){
73696 VdbeBranchTaken(res!=0,2);
73697 if( res ) pc = pOp->p2 - 1;
73699 break;
73703 /* Opcode: Sort P1 P2 * * *
73705 ** This opcode does exactly the same thing as OP_Rewind except that
73706 ** it increments an undocumented global variable used for testing.
73708 ** Sorting is accomplished by writing records into a sorting index,
73709 ** then rewinding that index and playing it back from beginning to
73710 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
73711 ** rewinding so that the global variable will be incremented and
73712 ** regression tests can determine whether or not the optimizer is
73713 ** correctly optimizing out sorts.
73715 case OP_SorterSort: /* jump */
73716 case OP_Sort: { /* jump */
73717 #ifdef SQLITE_TEST
73718 sqlite3_sort_count++;
73719 sqlite3_search_count--;
73720 #endif
73721 p->aCounter[SQLITE_STMTSTATUS_SORT]++;
73722 /* Fall through into OP_Rewind */
73724 /* Opcode: Rewind P1 P2 * * *
73726 ** The next use of the Rowid or Column or Next instruction for P1
73727 ** will refer to the first entry in the database table or index.
73728 ** If the table or index is empty and P2>0, then jump immediately to P2.
73729 ** If P2 is 0 or if the table or index is not empty, fall through
73730 ** to the following instruction.
73732 ** This opcode leaves the cursor configured to move in forward order,
73733 ** from the beginning toward the end. In other words, the cursor is
73734 ** configured to use Next, not Prev.
73736 case OP_Rewind: { /* jump */
73737 VdbeCursor *pC;
73738 BtCursor *pCrsr;
73739 int res;
73741 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73742 pC = p->apCsr[pOp->p1];
73743 assert( pC!=0 );
73744 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
73745 res = 1;
73746 #ifdef SQLITE_DEBUG
73747 pC->seekOp = OP_Rewind;
73748 #endif
73749 if( isSorter(pC) ){
73750 rc = sqlite3VdbeSorterRewind(pC, &res);
73751 }else{
73752 pCrsr = pC->pCursor;
73753 assert( pCrsr );
73754 rc = sqlite3BtreeFirst(pCrsr, &res);
73755 pC->deferredMoveto = 0;
73756 pC->cacheStatus = CACHE_STALE;
73758 pC->nullRow = (u8)res;
73759 assert( pOp->p2>0 && pOp->p2<p->nOp );
73760 VdbeBranchTaken(res!=0,2);
73761 if( res ){
73762 pc = pOp->p2 - 1;
73764 break;
73767 /* Opcode: Next P1 P2 P3 P4 P5
73769 ** Advance cursor P1 so that it points to the next key/data pair in its
73770 ** table or index. If there are no more key/value pairs then fall through
73771 ** to the following instruction. But if the cursor advance was successful,
73772 ** jump immediately to P2.
73774 ** The Next opcode is only valid following an SeekGT, SeekGE, or
73775 ** OP_Rewind opcode used to position the cursor. Next is not allowed
73776 ** to follow SeekLT, SeekLE, or OP_Last.
73778 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
73779 ** been opened prior to this opcode or the program will segfault.
73781 ** The P3 value is a hint to the btree implementation. If P3==1, that
73782 ** means P1 is an SQL index and that this instruction could have been
73783 ** omitted if that index had been unique. P3 is usually 0. P3 is
73784 ** always either 0 or 1.
73786 ** P4 is always of type P4_ADVANCE. The function pointer points to
73787 ** sqlite3BtreeNext().
73789 ** If P5 is positive and the jump is taken, then event counter
73790 ** number P5-1 in the prepared statement is incremented.
73792 ** See also: Prev, NextIfOpen
73794 /* Opcode: NextIfOpen P1 P2 P3 P4 P5
73796 ** This opcode works just like Next except that if cursor P1 is not
73797 ** open it behaves a no-op.
73799 /* Opcode: Prev P1 P2 P3 P4 P5
73801 ** Back up cursor P1 so that it points to the previous key/data pair in its
73802 ** table or index. If there is no previous key/value pairs then fall through
73803 ** to the following instruction. But if the cursor backup was successful,
73804 ** jump immediately to P2.
73807 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
73808 ** OP_Last opcode used to position the cursor. Prev is not allowed
73809 ** to follow SeekGT, SeekGE, or OP_Rewind.
73811 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
73812 ** not open then the behavior is undefined.
73814 ** The P3 value is a hint to the btree implementation. If P3==1, that
73815 ** means P1 is an SQL index and that this instruction could have been
73816 ** omitted if that index had been unique. P3 is usually 0. P3 is
73817 ** always either 0 or 1.
73819 ** P4 is always of type P4_ADVANCE. The function pointer points to
73820 ** sqlite3BtreePrevious().
73822 ** If P5 is positive and the jump is taken, then event counter
73823 ** number P5-1 in the prepared statement is incremented.
73825 /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
73827 ** This opcode works just like Prev except that if cursor P1 is not
73828 ** open it behaves a no-op.
73830 case OP_SorterNext: { /* jump */
73831 VdbeCursor *pC;
73832 int res;
73834 pC = p->apCsr[pOp->p1];
73835 assert( isSorter(pC) );
73836 res = 0;
73837 rc = sqlite3VdbeSorterNext(db, pC, &res);
73838 goto next_tail;
73839 case OP_PrevIfOpen: /* jump */
73840 case OP_NextIfOpen: /* jump */
73841 if( p->apCsr[pOp->p1]==0 ) break;
73842 /* Fall through */
73843 case OP_Prev: /* jump */
73844 case OP_Next: /* jump */
73845 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73846 assert( pOp->p5<ArraySize(p->aCounter) );
73847 pC = p->apCsr[pOp->p1];
73848 res = pOp->p3;
73849 assert( pC!=0 );
73850 assert( pC->deferredMoveto==0 );
73851 assert( pC->pCursor );
73852 assert( res==0 || (res==1 && pC->isTable==0) );
73853 testcase( res==1 );
73854 assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
73855 assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
73856 assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
73857 assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
73859 /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
73860 ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
73861 assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
73862 || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
73863 || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
73864 assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
73865 || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
73866 || pC->seekOp==OP_Last );
73868 rc = pOp->p4.xAdvance(pC->pCursor, &res);
73869 next_tail:
73870 pC->cacheStatus = CACHE_STALE;
73871 VdbeBranchTaken(res==0,2);
73872 if( res==0 ){
73873 pC->nullRow = 0;
73874 pc = pOp->p2 - 1;
73875 p->aCounter[pOp->p5]++;
73876 #ifdef SQLITE_TEST
73877 sqlite3_search_count++;
73878 #endif
73879 }else{
73880 pC->nullRow = 1;
73882 goto check_for_interrupt;
73885 /* Opcode: IdxInsert P1 P2 P3 * P5
73886 ** Synopsis: key=r[P2]
73888 ** Register P2 holds an SQL index key made using the
73889 ** MakeRecord instructions. This opcode writes that key
73890 ** into the index P1. Data for the entry is nil.
73892 ** P3 is a flag that provides a hint to the b-tree layer that this
73893 ** insert is likely to be an append.
73895 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
73896 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
73897 ** then the change counter is unchanged.
73899 ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
73900 ** just done a seek to the spot where the new entry is to be inserted.
73901 ** This flag avoids doing an extra seek.
73903 ** This instruction only works for indices. The equivalent instruction
73904 ** for tables is OP_Insert.
73906 case OP_SorterInsert: /* in2 */
73907 case OP_IdxInsert: { /* in2 */
73908 VdbeCursor *pC;
73909 BtCursor *pCrsr;
73910 int nKey;
73911 const char *zKey;
73913 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73914 pC = p->apCsr[pOp->p1];
73915 assert( pC!=0 );
73916 assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
73917 pIn2 = &aMem[pOp->p2];
73918 assert( pIn2->flags & MEM_Blob );
73919 pCrsr = pC->pCursor;
73920 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
73921 assert( pCrsr!=0 );
73922 assert( pC->isTable==0 );
73923 rc = ExpandBlob(pIn2);
73924 if( rc==SQLITE_OK ){
73925 if( isSorter(pC) ){
73926 rc = sqlite3VdbeSorterWrite(pC, pIn2);
73927 }else{
73928 nKey = pIn2->n;
73929 zKey = pIn2->z;
73930 rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3,
73931 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
73933 assert( pC->deferredMoveto==0 );
73934 pC->cacheStatus = CACHE_STALE;
73937 break;
73940 /* Opcode: IdxDelete P1 P2 P3 * *
73941 ** Synopsis: key=r[P2@P3]
73943 ** The content of P3 registers starting at register P2 form
73944 ** an unpacked index key. This opcode removes that entry from the
73945 ** index opened by cursor P1.
73947 case OP_IdxDelete: {
73948 VdbeCursor *pC;
73949 BtCursor *pCrsr;
73950 int res;
73951 UnpackedRecord r;
73953 assert( pOp->p3>0 );
73954 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
73955 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73956 pC = p->apCsr[pOp->p1];
73957 assert( pC!=0 );
73958 pCrsr = pC->pCursor;
73959 assert( pCrsr!=0 );
73960 assert( pOp->p5==0 );
73961 r.pKeyInfo = pC->pKeyInfo;
73962 r.nField = (u16)pOp->p3;
73963 r.default_rc = 0;
73964 r.aMem = &aMem[pOp->p2];
73965 #ifdef SQLITE_DEBUG
73966 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
73967 #endif
73968 rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
73969 if( rc==SQLITE_OK && res==0 ){
73970 rc = sqlite3BtreeDelete(pCrsr);
73972 assert( pC->deferredMoveto==0 );
73973 pC->cacheStatus = CACHE_STALE;
73974 break;
73977 /* Opcode: IdxRowid P1 P2 * * *
73978 ** Synopsis: r[P2]=rowid
73980 ** Write into register P2 an integer which is the last entry in the record at
73981 ** the end of the index key pointed to by cursor P1. This integer should be
73982 ** the rowid of the table entry to which this index entry points.
73984 ** See also: Rowid, MakeRecord.
73986 case OP_IdxRowid: { /* out2-prerelease */
73987 BtCursor *pCrsr;
73988 VdbeCursor *pC;
73989 i64 rowid;
73991 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73992 pC = p->apCsr[pOp->p1];
73993 assert( pC!=0 );
73994 pCrsr = pC->pCursor;
73995 assert( pCrsr!=0 );
73996 pOut->flags = MEM_Null;
73997 assert( pC->isTable==0 );
73998 assert( pC->deferredMoveto==0 );
74000 /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
74001 ** out from under the cursor. That will never happend for an IdxRowid
74002 ** opcode, hence the NEVER() arround the check of the return value.
74004 rc = sqlite3VdbeCursorRestore(pC);
74005 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
74007 if( !pC->nullRow ){
74008 rowid = 0; /* Not needed. Only used to silence a warning. */
74009 rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
74010 if( rc!=SQLITE_OK ){
74011 goto abort_due_to_error;
74013 pOut->u.i = rowid;
74014 pOut->flags = MEM_Int;
74016 break;
74019 /* Opcode: IdxGE P1 P2 P3 P4 P5
74020 ** Synopsis: key=r[P3@P4]
74022 ** The P4 register values beginning with P3 form an unpacked index
74023 ** key that omits the PRIMARY KEY. Compare this key value against the index
74024 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
74025 ** fields at the end.
74027 ** If the P1 index entry is greater than or equal to the key value
74028 ** then jump to P2. Otherwise fall through to the next instruction.
74030 /* Opcode: IdxGT P1 P2 P3 P4 P5
74031 ** Synopsis: key=r[P3@P4]
74033 ** The P4 register values beginning with P3 form an unpacked index
74034 ** key that omits the PRIMARY KEY. Compare this key value against the index
74035 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
74036 ** fields at the end.
74038 ** If the P1 index entry is greater than the key value
74039 ** then jump to P2. Otherwise fall through to the next instruction.
74041 /* Opcode: IdxLT P1 P2 P3 P4 P5
74042 ** Synopsis: key=r[P3@P4]
74044 ** The P4 register values beginning with P3 form an unpacked index
74045 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
74046 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
74047 ** ROWID on the P1 index.
74049 ** If the P1 index entry is less than the key value then jump to P2.
74050 ** Otherwise fall through to the next instruction.
74052 /* Opcode: IdxLE P1 P2 P3 P4 P5
74053 ** Synopsis: key=r[P3@P4]
74055 ** The P4 register values beginning with P3 form an unpacked index
74056 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
74057 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
74058 ** ROWID on the P1 index.
74060 ** If the P1 index entry is less than or equal to the key value then jump
74061 ** to P2. Otherwise fall through to the next instruction.
74063 case OP_IdxLE: /* jump */
74064 case OP_IdxGT: /* jump */
74065 case OP_IdxLT: /* jump */
74066 case OP_IdxGE: { /* jump */
74067 VdbeCursor *pC;
74068 int res;
74069 UnpackedRecord r;
74071 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74072 pC = p->apCsr[pOp->p1];
74073 assert( pC!=0 );
74074 assert( pC->isOrdered );
74075 assert( pC->pCursor!=0);
74076 assert( pC->deferredMoveto==0 );
74077 assert( pOp->p5==0 || pOp->p5==1 );
74078 assert( pOp->p4type==P4_INT32 );
74079 r.pKeyInfo = pC->pKeyInfo;
74080 r.nField = (u16)pOp->p4.i;
74081 if( pOp->opcode<OP_IdxLT ){
74082 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
74083 r.default_rc = -1;
74084 }else{
74085 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
74086 r.default_rc = 0;
74088 r.aMem = &aMem[pOp->p3];
74089 #ifdef SQLITE_DEBUG
74090 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
74091 #endif
74092 res = 0; /* Not needed. Only used to silence a warning. */
74093 rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
74094 assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
74095 if( (pOp->opcode&1)==(OP_IdxLT&1) ){
74096 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
74097 res = -res;
74098 }else{
74099 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
74100 res++;
74102 VdbeBranchTaken(res>0,2);
74103 if( res>0 ){
74104 pc = pOp->p2 - 1 ;
74106 break;
74109 /* Opcode: Destroy P1 P2 P3 * *
74111 ** Delete an entire database table or index whose root page in the database
74112 ** file is given by P1.
74114 ** The table being destroyed is in the main database file if P3==0. If
74115 ** P3==1 then the table to be clear is in the auxiliary database file
74116 ** that is used to store tables create using CREATE TEMPORARY TABLE.
74118 ** If AUTOVACUUM is enabled then it is possible that another root page
74119 ** might be moved into the newly deleted root page in order to keep all
74120 ** root pages contiguous at the beginning of the database. The former
74121 ** value of the root page that moved - its value before the move occurred -
74122 ** is stored in register P2. If no page
74123 ** movement was required (because the table being dropped was already
74124 ** the last one in the database) then a zero is stored in register P2.
74125 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
74127 ** See also: Clear
74129 case OP_Destroy: { /* out2-prerelease */
74130 int iMoved;
74131 int iCnt;
74132 Vdbe *pVdbe;
74133 int iDb;
74135 assert( p->readOnly==0 );
74136 #ifndef SQLITE_OMIT_VIRTUALTABLE
74137 iCnt = 0;
74138 for(pVdbe=db->pVdbe; pVdbe; pVdbe = pVdbe->pNext){
74139 if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->bIsReader
74140 && pVdbe->inVtabMethod<2 && pVdbe->pc>=0
74142 iCnt++;
74145 #else
74146 iCnt = db->nVdbeRead;
74147 #endif
74148 pOut->flags = MEM_Null;
74149 if( iCnt>1 ){
74150 rc = SQLITE_LOCKED;
74151 p->errorAction = OE_Abort;
74152 }else{
74153 iDb = pOp->p3;
74154 assert( iCnt==1 );
74155 assert( DbMaskTest(p->btreeMask, iDb) );
74156 iMoved = 0; /* Not needed. Only to silence a warning. */
74157 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
74158 pOut->flags = MEM_Int;
74159 pOut->u.i = iMoved;
74160 #ifndef SQLITE_OMIT_AUTOVACUUM
74161 if( rc==SQLITE_OK && iMoved!=0 ){
74162 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
74163 /* All OP_Destroy operations occur on the same btree */
74164 assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
74165 resetSchemaOnFault = iDb+1;
74167 #endif
74169 break;
74172 /* Opcode: Clear P1 P2 P3
74174 ** Delete all contents of the database table or index whose root page
74175 ** in the database file is given by P1. But, unlike Destroy, do not
74176 ** remove the table or index from the database file.
74178 ** The table being clear is in the main database file if P2==0. If
74179 ** P2==1 then the table to be clear is in the auxiliary database file
74180 ** that is used to store tables create using CREATE TEMPORARY TABLE.
74182 ** If the P3 value is non-zero, then the table referred to must be an
74183 ** intkey table (an SQL table, not an index). In this case the row change
74184 ** count is incremented by the number of rows in the table being cleared.
74185 ** If P3 is greater than zero, then the value stored in register P3 is
74186 ** also incremented by the number of rows in the table being cleared.
74188 ** See also: Destroy
74190 case OP_Clear: {
74191 int nChange;
74193 nChange = 0;
74194 assert( p->readOnly==0 );
74195 assert( DbMaskTest(p->btreeMask, pOp->p2) );
74196 rc = sqlite3BtreeClearTable(
74197 db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
74199 if( pOp->p3 ){
74200 p->nChange += nChange;
74201 if( pOp->p3>0 ){
74202 assert( memIsValid(&aMem[pOp->p3]) );
74203 memAboutToChange(p, &aMem[pOp->p3]);
74204 aMem[pOp->p3].u.i += nChange;
74207 break;
74210 /* Opcode: ResetSorter P1 * * * *
74212 ** Delete all contents from the ephemeral table or sorter
74213 ** that is open on cursor P1.
74215 ** This opcode only works for cursors used for sorting and
74216 ** opened with OP_OpenEphemeral or OP_SorterOpen.
74218 case OP_ResetSorter: {
74219 VdbeCursor *pC;
74221 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74222 pC = p->apCsr[pOp->p1];
74223 assert( pC!=0 );
74224 if( pC->pSorter ){
74225 sqlite3VdbeSorterReset(db, pC->pSorter);
74226 }else{
74227 assert( pC->isEphemeral );
74228 rc = sqlite3BtreeClearTableOfCursor(pC->pCursor);
74230 break;
74233 /* Opcode: CreateTable P1 P2 * * *
74234 ** Synopsis: r[P2]=root iDb=P1
74236 ** Allocate a new table in the main database file if P1==0 or in the
74237 ** auxiliary database file if P1==1 or in an attached database if
74238 ** P1>1. Write the root page number of the new table into
74239 ** register P2
74241 ** The difference between a table and an index is this: A table must
74242 ** have a 4-byte integer key and can have arbitrary data. An index
74243 ** has an arbitrary key but no data.
74245 ** See also: CreateIndex
74247 /* Opcode: CreateIndex P1 P2 * * *
74248 ** Synopsis: r[P2]=root iDb=P1
74250 ** Allocate a new index in the main database file if P1==0 or in the
74251 ** auxiliary database file if P1==1 or in an attached database if
74252 ** P1>1. Write the root page number of the new table into
74253 ** register P2.
74255 ** See documentation on OP_CreateTable for additional information.
74257 case OP_CreateIndex: /* out2-prerelease */
74258 case OP_CreateTable: { /* out2-prerelease */
74259 int pgno;
74260 int flags;
74261 Db *pDb;
74263 pgno = 0;
74264 assert( pOp->p1>=0 && pOp->p1<db->nDb );
74265 assert( DbMaskTest(p->btreeMask, pOp->p1) );
74266 assert( p->readOnly==0 );
74267 pDb = &db->aDb[pOp->p1];
74268 assert( pDb->pBt!=0 );
74269 if( pOp->opcode==OP_CreateTable ){
74270 /* flags = BTREE_INTKEY; */
74271 flags = BTREE_INTKEY;
74272 }else{
74273 flags = BTREE_BLOBKEY;
74275 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
74276 pOut->u.i = pgno;
74277 break;
74280 /* Opcode: ParseSchema P1 * * P4 *
74282 ** Read and parse all entries from the SQLITE_MASTER table of database P1
74283 ** that match the WHERE clause P4.
74285 ** This opcode invokes the parser to create a new virtual machine,
74286 ** then runs the new virtual machine. It is thus a re-entrant opcode.
74288 case OP_ParseSchema: {
74289 int iDb;
74290 const char *zMaster;
74291 char *zSql;
74292 InitData initData;
74294 /* Any prepared statement that invokes this opcode will hold mutexes
74295 ** on every btree. This is a prerequisite for invoking
74296 ** sqlite3InitCallback().
74298 #ifdef SQLITE_DEBUG
74299 for(iDb=0; iDb<db->nDb; iDb++){
74300 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
74302 #endif
74304 iDb = pOp->p1;
74305 assert( iDb>=0 && iDb<db->nDb );
74306 assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
74307 /* Used to be a conditional */ {
74308 zMaster = SCHEMA_TABLE(iDb);
74309 initData.db = db;
74310 initData.iDb = pOp->p1;
74311 initData.pzErrMsg = &p->zErrMsg;
74312 zSql = sqlite3MPrintf(db,
74313 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
74314 db->aDb[iDb].zName, zMaster, pOp->p4.z);
74315 if( zSql==0 ){
74316 rc = SQLITE_NOMEM;
74317 }else{
74318 assert( db->init.busy==0 );
74319 db->init.busy = 1;
74320 initData.rc = SQLITE_OK;
74321 assert( !db->mallocFailed );
74322 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
74323 if( rc==SQLITE_OK ) rc = initData.rc;
74324 sqlite3DbFree(db, zSql);
74325 db->init.busy = 0;
74328 if( rc ) sqlite3ResetAllSchemasOfConnection(db);
74329 if( rc==SQLITE_NOMEM ){
74330 goto no_mem;
74332 break;
74335 #if !defined(SQLITE_OMIT_ANALYZE)
74336 /* Opcode: LoadAnalysis P1 * * * *
74338 ** Read the sqlite_stat1 table for database P1 and load the content
74339 ** of that table into the internal index hash table. This will cause
74340 ** the analysis to be used when preparing all subsequent queries.
74342 case OP_LoadAnalysis: {
74343 assert( pOp->p1>=0 && pOp->p1<db->nDb );
74344 rc = sqlite3AnalysisLoad(db, pOp->p1);
74345 break;
74347 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
74349 /* Opcode: DropTable P1 * * P4 *
74351 ** Remove the internal (in-memory) data structures that describe
74352 ** the table named P4 in database P1. This is called after a table
74353 ** is dropped from disk (using the Destroy opcode) in order to keep
74354 ** the internal representation of the
74355 ** schema consistent with what is on disk.
74357 case OP_DropTable: {
74358 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
74359 break;
74362 /* Opcode: DropIndex P1 * * P4 *
74364 ** Remove the internal (in-memory) data structures that describe
74365 ** the index named P4 in database P1. This is called after an index
74366 ** is dropped from disk (using the Destroy opcode)
74367 ** in order to keep the internal representation of the
74368 ** schema consistent with what is on disk.
74370 case OP_DropIndex: {
74371 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
74372 break;
74375 /* Opcode: DropTrigger P1 * * P4 *
74377 ** Remove the internal (in-memory) data structures that describe
74378 ** the trigger named P4 in database P1. This is called after a trigger
74379 ** is dropped from disk (using the Destroy opcode) in order to keep
74380 ** the internal representation of the
74381 ** schema consistent with what is on disk.
74383 case OP_DropTrigger: {
74384 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
74385 break;
74389 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
74390 /* Opcode: IntegrityCk P1 P2 P3 * P5
74392 ** Do an analysis of the currently open database. Store in
74393 ** register P1 the text of an error message describing any problems.
74394 ** If no problems are found, store a NULL in register P1.
74396 ** The register P3 contains the maximum number of allowed errors.
74397 ** At most reg(P3) errors will be reported.
74398 ** In other words, the analysis stops as soon as reg(P1) errors are
74399 ** seen. Reg(P1) is updated with the number of errors remaining.
74401 ** The root page numbers of all tables in the database are integer
74402 ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
74403 ** total.
74405 ** If P5 is not zero, the check is done on the auxiliary database
74406 ** file, not the main database file.
74408 ** This opcode is used to implement the integrity_check pragma.
74410 case OP_IntegrityCk: {
74411 int nRoot; /* Number of tables to check. (Number of root pages.) */
74412 int *aRoot; /* Array of rootpage numbers for tables to be checked */
74413 int j; /* Loop counter */
74414 int nErr; /* Number of errors reported */
74415 char *z; /* Text of the error report */
74416 Mem *pnErr; /* Register keeping track of errors remaining */
74418 assert( p->bIsReader );
74419 nRoot = pOp->p2;
74420 assert( nRoot>0 );
74421 aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
74422 if( aRoot==0 ) goto no_mem;
74423 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
74424 pnErr = &aMem[pOp->p3];
74425 assert( (pnErr->flags & MEM_Int)!=0 );
74426 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
74427 pIn1 = &aMem[pOp->p1];
74428 for(j=0; j<nRoot; j++){
74429 aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
74431 aRoot[j] = 0;
74432 assert( pOp->p5<db->nDb );
74433 assert( DbMaskTest(p->btreeMask, pOp->p5) );
74434 z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
74435 (int)pnErr->u.i, &nErr);
74436 sqlite3DbFree(db, aRoot);
74437 pnErr->u.i -= nErr;
74438 sqlite3VdbeMemSetNull(pIn1);
74439 if( nErr==0 ){
74440 assert( z==0 );
74441 }else if( z==0 ){
74442 goto no_mem;
74443 }else{
74444 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
74446 UPDATE_MAX_BLOBSIZE(pIn1);
74447 sqlite3VdbeChangeEncoding(pIn1, encoding);
74448 break;
74450 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
74452 /* Opcode: RowSetAdd P1 P2 * * *
74453 ** Synopsis: rowset(P1)=r[P2]
74455 ** Insert the integer value held by register P2 into a boolean index
74456 ** held in register P1.
74458 ** An assertion fails if P2 is not an integer.
74460 case OP_RowSetAdd: { /* in1, in2 */
74461 pIn1 = &aMem[pOp->p1];
74462 pIn2 = &aMem[pOp->p2];
74463 assert( (pIn2->flags & MEM_Int)!=0 );
74464 if( (pIn1->flags & MEM_RowSet)==0 ){
74465 sqlite3VdbeMemSetRowSet(pIn1);
74466 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
74468 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
74469 break;
74472 /* Opcode: RowSetRead P1 P2 P3 * *
74473 ** Synopsis: r[P3]=rowset(P1)
74475 ** Extract the smallest value from boolean index P1 and put that value into
74476 ** register P3. Or, if boolean index P1 is initially empty, leave P3
74477 ** unchanged and jump to instruction P2.
74479 case OP_RowSetRead: { /* jump, in1, out3 */
74480 i64 val;
74482 pIn1 = &aMem[pOp->p1];
74483 if( (pIn1->flags & MEM_RowSet)==0
74484 || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
74486 /* The boolean index is empty */
74487 sqlite3VdbeMemSetNull(pIn1);
74488 pc = pOp->p2 - 1;
74489 VdbeBranchTaken(1,2);
74490 }else{
74491 /* A value was pulled from the index */
74492 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
74493 VdbeBranchTaken(0,2);
74495 goto check_for_interrupt;
74498 /* Opcode: RowSetTest P1 P2 P3 P4
74499 ** Synopsis: if r[P3] in rowset(P1) goto P2
74501 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
74502 ** contains a RowSet object and that RowSet object contains
74503 ** the value held in P3, jump to register P2. Otherwise, insert the
74504 ** integer in P3 into the RowSet and continue on to the
74505 ** next opcode.
74507 ** The RowSet object is optimized for the case where successive sets
74508 ** of integers, where each set contains no duplicates. Each set
74509 ** of values is identified by a unique P4 value. The first set
74510 ** must have P4==0, the final set P4=-1. P4 must be either -1 or
74511 ** non-negative. For non-negative values of P4 only the lower 4
74512 ** bits are significant.
74514 ** This allows optimizations: (a) when P4==0 there is no need to test
74515 ** the rowset object for P3, as it is guaranteed not to contain it,
74516 ** (b) when P4==-1 there is no need to insert the value, as it will
74517 ** never be tested for, and (c) when a value that is part of set X is
74518 ** inserted, there is no need to search to see if the same value was
74519 ** previously inserted as part of set X (only if it was previously
74520 ** inserted as part of some other set).
74522 case OP_RowSetTest: { /* jump, in1, in3 */
74523 int iSet;
74524 int exists;
74526 pIn1 = &aMem[pOp->p1];
74527 pIn3 = &aMem[pOp->p3];
74528 iSet = pOp->p4.i;
74529 assert( pIn3->flags&MEM_Int );
74531 /* If there is anything other than a rowset object in memory cell P1,
74532 ** delete it now and initialize P1 with an empty rowset
74534 if( (pIn1->flags & MEM_RowSet)==0 ){
74535 sqlite3VdbeMemSetRowSet(pIn1);
74536 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
74539 assert( pOp->p4type==P4_INT32 );
74540 assert( iSet==-1 || iSet>=0 );
74541 if( iSet ){
74542 exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
74543 VdbeBranchTaken(exists!=0,2);
74544 if( exists ){
74545 pc = pOp->p2 - 1;
74546 break;
74549 if( iSet>=0 ){
74550 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
74552 break;
74556 #ifndef SQLITE_OMIT_TRIGGER
74558 /* Opcode: Program P1 P2 P3 P4 P5
74560 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
74562 ** P1 contains the address of the memory cell that contains the first memory
74563 ** cell in an array of values used as arguments to the sub-program. P2
74564 ** contains the address to jump to if the sub-program throws an IGNORE
74565 ** exception using the RAISE() function. Register P3 contains the address
74566 ** of a memory cell in this (the parent) VM that is used to allocate the
74567 ** memory required by the sub-vdbe at runtime.
74569 ** P4 is a pointer to the VM containing the trigger program.
74571 ** If P5 is non-zero, then recursive program invocation is enabled.
74573 case OP_Program: { /* jump */
74574 int nMem; /* Number of memory registers for sub-program */
74575 int nByte; /* Bytes of runtime space required for sub-program */
74576 Mem *pRt; /* Register to allocate runtime space */
74577 Mem *pMem; /* Used to iterate through memory cells */
74578 Mem *pEnd; /* Last memory cell in new array */
74579 VdbeFrame *pFrame; /* New vdbe frame to execute in */
74580 SubProgram *pProgram; /* Sub-program to execute */
74581 void *t; /* Token identifying trigger */
74583 pProgram = pOp->p4.pProgram;
74584 pRt = &aMem[pOp->p3];
74585 assert( pProgram->nOp>0 );
74587 /* If the p5 flag is clear, then recursive invocation of triggers is
74588 ** disabled for backwards compatibility (p5 is set if this sub-program
74589 ** is really a trigger, not a foreign key action, and the flag set
74590 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
74592 ** It is recursive invocation of triggers, at the SQL level, that is
74593 ** disabled. In some cases a single trigger may generate more than one
74594 ** SubProgram (if the trigger may be executed with more than one different
74595 ** ON CONFLICT algorithm). SubProgram structures associated with a
74596 ** single trigger all have the same value for the SubProgram.token
74597 ** variable. */
74598 if( pOp->p5 ){
74599 t = pProgram->token;
74600 for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
74601 if( pFrame ) break;
74604 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
74605 rc = SQLITE_ERROR;
74606 sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
74607 break;
74610 /* Register pRt is used to store the memory required to save the state
74611 ** of the current program, and the memory required at runtime to execute
74612 ** the trigger program. If this trigger has been fired before, then pRt
74613 ** is already allocated. Otherwise, it must be initialized. */
74614 if( (pRt->flags&MEM_Frame)==0 ){
74615 /* SubProgram.nMem is set to the number of memory cells used by the
74616 ** program stored in SubProgram.aOp. As well as these, one memory
74617 ** cell is required for each cursor used by the program. Set local
74618 ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
74620 nMem = pProgram->nMem + pProgram->nCsr;
74621 nByte = ROUND8(sizeof(VdbeFrame))
74622 + nMem * sizeof(Mem)
74623 + pProgram->nCsr * sizeof(VdbeCursor *)
74624 + pProgram->nOnce * sizeof(u8);
74625 pFrame = sqlite3DbMallocZero(db, nByte);
74626 if( !pFrame ){
74627 goto no_mem;
74629 sqlite3VdbeMemRelease(pRt);
74630 pRt->flags = MEM_Frame;
74631 pRt->u.pFrame = pFrame;
74633 pFrame->v = p;
74634 pFrame->nChildMem = nMem;
74635 pFrame->nChildCsr = pProgram->nCsr;
74636 pFrame->pc = pc;
74637 pFrame->aMem = p->aMem;
74638 pFrame->nMem = p->nMem;
74639 pFrame->apCsr = p->apCsr;
74640 pFrame->nCursor = p->nCursor;
74641 pFrame->aOp = p->aOp;
74642 pFrame->nOp = p->nOp;
74643 pFrame->token = pProgram->token;
74644 pFrame->aOnceFlag = p->aOnceFlag;
74645 pFrame->nOnceFlag = p->nOnceFlag;
74647 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
74648 for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
74649 pMem->flags = MEM_Undefined;
74650 pMem->db = db;
74652 }else{
74653 pFrame = pRt->u.pFrame;
74654 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
74655 assert( pProgram->nCsr==pFrame->nChildCsr );
74656 assert( pc==pFrame->pc );
74659 p->nFrame++;
74660 pFrame->pParent = p->pFrame;
74661 pFrame->lastRowid = lastRowid;
74662 pFrame->nChange = p->nChange;
74663 p->nChange = 0;
74664 p->pFrame = pFrame;
74665 p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
74666 p->nMem = pFrame->nChildMem;
74667 p->nCursor = (u16)pFrame->nChildCsr;
74668 p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
74669 p->aOp = aOp = pProgram->aOp;
74670 p->nOp = pProgram->nOp;
74671 p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
74672 p->nOnceFlag = pProgram->nOnce;
74673 pc = -1;
74674 memset(p->aOnceFlag, 0, p->nOnceFlag);
74676 break;
74679 /* Opcode: Param P1 P2 * * *
74681 ** This opcode is only ever present in sub-programs called via the
74682 ** OP_Program instruction. Copy a value currently stored in a memory
74683 ** cell of the calling (parent) frame to cell P2 in the current frames
74684 ** address space. This is used by trigger programs to access the new.*
74685 ** and old.* values.
74687 ** The address of the cell in the parent frame is determined by adding
74688 ** the value of the P1 argument to the value of the P1 argument to the
74689 ** calling OP_Program instruction.
74691 case OP_Param: { /* out2-prerelease */
74692 VdbeFrame *pFrame;
74693 Mem *pIn;
74694 pFrame = p->pFrame;
74695 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
74696 sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
74697 break;
74700 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
74702 #ifndef SQLITE_OMIT_FOREIGN_KEY
74703 /* Opcode: FkCounter P1 P2 * * *
74704 ** Synopsis: fkctr[P1]+=P2
74706 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
74707 ** If P1 is non-zero, the database constraint counter is incremented
74708 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
74709 ** statement counter is incremented (immediate foreign key constraints).
74711 case OP_FkCounter: {
74712 if( db->flags & SQLITE_DeferFKs ){
74713 db->nDeferredImmCons += pOp->p2;
74714 }else if( pOp->p1 ){
74715 db->nDeferredCons += pOp->p2;
74716 }else{
74717 p->nFkConstraint += pOp->p2;
74719 break;
74722 /* Opcode: FkIfZero P1 P2 * * *
74723 ** Synopsis: if fkctr[P1]==0 goto P2
74725 ** This opcode tests if a foreign key constraint-counter is currently zero.
74726 ** If so, jump to instruction P2. Otherwise, fall through to the next
74727 ** instruction.
74729 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
74730 ** is zero (the one that counts deferred constraint violations). If P1 is
74731 ** zero, the jump is taken if the statement constraint-counter is zero
74732 ** (immediate foreign key constraint violations).
74734 case OP_FkIfZero: { /* jump */
74735 if( pOp->p1 ){
74736 VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
74737 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
74738 }else{
74739 VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
74740 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
74742 break;
74744 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
74746 #ifndef SQLITE_OMIT_AUTOINCREMENT
74747 /* Opcode: MemMax P1 P2 * * *
74748 ** Synopsis: r[P1]=max(r[P1],r[P2])
74750 ** P1 is a register in the root frame of this VM (the root frame is
74751 ** different from the current frame if this instruction is being executed
74752 ** within a sub-program). Set the value of register P1 to the maximum of
74753 ** its current value and the value in register P2.
74755 ** This instruction throws an error if the memory cell is not initially
74756 ** an integer.
74758 case OP_MemMax: { /* in2 */
74759 VdbeFrame *pFrame;
74760 if( p->pFrame ){
74761 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
74762 pIn1 = &pFrame->aMem[pOp->p1];
74763 }else{
74764 pIn1 = &aMem[pOp->p1];
74766 assert( memIsValid(pIn1) );
74767 sqlite3VdbeMemIntegerify(pIn1);
74768 pIn2 = &aMem[pOp->p2];
74769 sqlite3VdbeMemIntegerify(pIn2);
74770 if( pIn1->u.i<pIn2->u.i){
74771 pIn1->u.i = pIn2->u.i;
74773 break;
74775 #endif /* SQLITE_OMIT_AUTOINCREMENT */
74777 /* Opcode: IfPos P1 P2 * * *
74778 ** Synopsis: if r[P1]>0 goto P2
74780 ** If the value of register P1 is 1 or greater, jump to P2.
74782 ** It is illegal to use this instruction on a register that does
74783 ** not contain an integer. An assertion fault will result if you try.
74785 case OP_IfPos: { /* jump, in1 */
74786 pIn1 = &aMem[pOp->p1];
74787 assert( pIn1->flags&MEM_Int );
74788 VdbeBranchTaken( pIn1->u.i>0, 2);
74789 if( pIn1->u.i>0 ){
74790 pc = pOp->p2 - 1;
74792 break;
74795 /* Opcode: IfNeg P1 P2 P3 * *
74796 ** Synopsis: r[P1]+=P3, if r[P1]<0 goto P2
74798 ** Register P1 must contain an integer. Add literal P3 to the value in
74799 ** register P1 then if the value of register P1 is less than zero, jump to P2.
74801 case OP_IfNeg: { /* jump, in1 */
74802 pIn1 = &aMem[pOp->p1];
74803 assert( pIn1->flags&MEM_Int );
74804 pIn1->u.i += pOp->p3;
74805 VdbeBranchTaken(pIn1->u.i<0, 2);
74806 if( pIn1->u.i<0 ){
74807 pc = pOp->p2 - 1;
74809 break;
74812 /* Opcode: IfZero P1 P2 P3 * *
74813 ** Synopsis: r[P1]+=P3, if r[P1]==0 goto P2
74815 ** The register P1 must contain an integer. Add literal P3 to the
74816 ** value in register P1. If the result is exactly 0, jump to P2.
74818 case OP_IfZero: { /* jump, in1 */
74819 pIn1 = &aMem[pOp->p1];
74820 assert( pIn1->flags&MEM_Int );
74821 pIn1->u.i += pOp->p3;
74822 VdbeBranchTaken(pIn1->u.i==0, 2);
74823 if( pIn1->u.i==0 ){
74824 pc = pOp->p2 - 1;
74826 break;
74829 /* Opcode: AggStep * P2 P3 P4 P5
74830 ** Synopsis: accum=r[P3] step(r[P2@P5])
74832 ** Execute the step function for an aggregate. The
74833 ** function has P5 arguments. P4 is a pointer to the FuncDef
74834 ** structure that specifies the function. Use register
74835 ** P3 as the accumulator.
74837 ** The P5 arguments are taken from register P2 and its
74838 ** successors.
74840 case OP_AggStep: {
74841 int n;
74842 int i;
74843 Mem *pMem;
74844 Mem *pRec;
74845 Mem t;
74846 sqlite3_context ctx;
74847 sqlite3_value **apVal;
74849 n = pOp->p5;
74850 assert( n>=0 );
74851 pRec = &aMem[pOp->p2];
74852 apVal = p->apArg;
74853 assert( apVal || n==0 );
74854 for(i=0; i<n; i++, pRec++){
74855 assert( memIsValid(pRec) );
74856 apVal[i] = pRec;
74857 memAboutToChange(p, pRec);
74859 ctx.pFunc = pOp->p4.pFunc;
74860 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
74861 ctx.pMem = pMem = &aMem[pOp->p3];
74862 pMem->n++;
74863 sqlite3VdbeMemInit(&t, db, MEM_Null);
74864 ctx.pOut = &t;
74865 ctx.isError = 0;
74866 ctx.pVdbe = p;
74867 ctx.iOp = pc;
74868 ctx.skipFlag = 0;
74869 (ctx.pFunc->xStep)(&ctx, n, apVal); /* IMP: R-24505-23230 */
74870 if( ctx.isError ){
74871 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&t));
74872 rc = ctx.isError;
74874 if( ctx.skipFlag ){
74875 assert( pOp[-1].opcode==OP_CollSeq );
74876 i = pOp[-1].p1;
74877 if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
74879 sqlite3VdbeMemRelease(&t);
74880 break;
74883 /* Opcode: AggFinal P1 P2 * P4 *
74884 ** Synopsis: accum=r[P1] N=P2
74886 ** Execute the finalizer function for an aggregate. P1 is
74887 ** the memory location that is the accumulator for the aggregate.
74889 ** P2 is the number of arguments that the step function takes and
74890 ** P4 is a pointer to the FuncDef for this function. The P2
74891 ** argument is not used by this opcode. It is only there to disambiguate
74892 ** functions that can take varying numbers of arguments. The
74893 ** P4 argument is only needed for the degenerate case where
74894 ** the step function was not previously called.
74896 case OP_AggFinal: {
74897 Mem *pMem;
74898 assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
74899 pMem = &aMem[pOp->p1];
74900 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
74901 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
74902 if( rc ){
74903 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
74905 sqlite3VdbeChangeEncoding(pMem, encoding);
74906 UPDATE_MAX_BLOBSIZE(pMem);
74907 if( sqlite3VdbeMemTooBig(pMem) ){
74908 goto too_big;
74910 break;
74913 #ifndef SQLITE_OMIT_WAL
74914 /* Opcode: Checkpoint P1 P2 P3 * *
74916 ** Checkpoint database P1. This is a no-op if P1 is not currently in
74917 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
74918 ** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns
74919 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
74920 ** WAL after the checkpoint into mem[P3+1] and the number of pages
74921 ** in the WAL that have been checkpointed after the checkpoint
74922 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
74923 ** mem[P3+2] are initialized to -1.
74925 case OP_Checkpoint: {
74926 int i; /* Loop counter */
74927 int aRes[3]; /* Results */
74928 Mem *pMem; /* Write results here */
74930 assert( p->readOnly==0 );
74931 aRes[0] = 0;
74932 aRes[1] = aRes[2] = -1;
74933 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
74934 || pOp->p2==SQLITE_CHECKPOINT_FULL
74935 || pOp->p2==SQLITE_CHECKPOINT_RESTART
74937 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
74938 if( rc==SQLITE_BUSY ){
74939 rc = SQLITE_OK;
74940 aRes[0] = 1;
74942 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
74943 sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
74945 break;
74947 #endif
74949 #ifndef SQLITE_OMIT_PRAGMA
74950 /* Opcode: JournalMode P1 P2 P3 * *
74952 ** Change the journal mode of database P1 to P3. P3 must be one of the
74953 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
74954 ** modes (delete, truncate, persist, off and memory), this is a simple
74955 ** operation. No IO is required.
74957 ** If changing into or out of WAL mode the procedure is more complicated.
74959 ** Write a string containing the final journal-mode to register P2.
74961 case OP_JournalMode: { /* out2-prerelease */
74962 Btree *pBt; /* Btree to change journal mode of */
74963 Pager *pPager; /* Pager associated with pBt */
74964 int eNew; /* New journal mode */
74965 int eOld; /* The old journal mode */
74966 #ifndef SQLITE_OMIT_WAL
74967 const char *zFilename; /* Name of database file for pPager */
74968 #endif
74970 eNew = pOp->p3;
74971 assert( eNew==PAGER_JOURNALMODE_DELETE
74972 || eNew==PAGER_JOURNALMODE_TRUNCATE
74973 || eNew==PAGER_JOURNALMODE_PERSIST
74974 || eNew==PAGER_JOURNALMODE_OFF
74975 || eNew==PAGER_JOURNALMODE_MEMORY
74976 || eNew==PAGER_JOURNALMODE_WAL
74977 || eNew==PAGER_JOURNALMODE_QUERY
74979 assert( pOp->p1>=0 && pOp->p1<db->nDb );
74980 assert( p->readOnly==0 );
74982 pBt = db->aDb[pOp->p1].pBt;
74983 pPager = sqlite3BtreePager(pBt);
74984 eOld = sqlite3PagerGetJournalMode(pPager);
74985 if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
74986 if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
74988 #ifndef SQLITE_OMIT_WAL
74989 zFilename = sqlite3PagerFilename(pPager, 1);
74991 /* Do not allow a transition to journal_mode=WAL for a database
74992 ** in temporary storage or if the VFS does not support shared memory
74994 if( eNew==PAGER_JOURNALMODE_WAL
74995 && (sqlite3Strlen30(zFilename)==0 /* Temp file */
74996 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
74998 eNew = eOld;
75001 if( (eNew!=eOld)
75002 && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
75004 if( !db->autoCommit || db->nVdbeRead>1 ){
75005 rc = SQLITE_ERROR;
75006 sqlite3SetString(&p->zErrMsg, db,
75007 "cannot change %s wal mode from within a transaction",
75008 (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
75010 break;
75011 }else{
75013 if( eOld==PAGER_JOURNALMODE_WAL ){
75014 /* If leaving WAL mode, close the log file. If successful, the call
75015 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
75016 ** file. An EXCLUSIVE lock may still be held on the database file
75017 ** after a successful return.
75019 rc = sqlite3PagerCloseWal(pPager);
75020 if( rc==SQLITE_OK ){
75021 sqlite3PagerSetJournalMode(pPager, eNew);
75023 }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
75024 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
75025 ** as an intermediate */
75026 sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
75029 /* Open a transaction on the database file. Regardless of the journal
75030 ** mode, this transaction always uses a rollback journal.
75032 assert( sqlite3BtreeIsInTrans(pBt)==0 );
75033 if( rc==SQLITE_OK ){
75034 rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
75038 #endif /* ifndef SQLITE_OMIT_WAL */
75040 if( rc ){
75041 eNew = eOld;
75043 eNew = sqlite3PagerSetJournalMode(pPager, eNew);
75045 pOut = &aMem[pOp->p2];
75046 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
75047 pOut->z = (char *)sqlite3JournalModename(eNew);
75048 pOut->n = sqlite3Strlen30(pOut->z);
75049 pOut->enc = SQLITE_UTF8;
75050 sqlite3VdbeChangeEncoding(pOut, encoding);
75051 break;
75053 #endif /* SQLITE_OMIT_PRAGMA */
75055 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
75056 /* Opcode: Vacuum * * * * *
75058 ** Vacuum the entire database. This opcode will cause other virtual
75059 ** machines to be created and run. It may not be called from within
75060 ** a transaction.
75062 case OP_Vacuum: {
75063 assert( p->readOnly==0 );
75064 rc = sqlite3RunVacuum(&p->zErrMsg, db);
75065 break;
75067 #endif
75069 #if !defined(SQLITE_OMIT_AUTOVACUUM)
75070 /* Opcode: IncrVacuum P1 P2 * * *
75072 ** Perform a single step of the incremental vacuum procedure on
75073 ** the P1 database. If the vacuum has finished, jump to instruction
75074 ** P2. Otherwise, fall through to the next instruction.
75076 case OP_IncrVacuum: { /* jump */
75077 Btree *pBt;
75079 assert( pOp->p1>=0 && pOp->p1<db->nDb );
75080 assert( DbMaskTest(p->btreeMask, pOp->p1) );
75081 assert( p->readOnly==0 );
75082 pBt = db->aDb[pOp->p1].pBt;
75083 rc = sqlite3BtreeIncrVacuum(pBt);
75084 VdbeBranchTaken(rc==SQLITE_DONE,2);
75085 if( rc==SQLITE_DONE ){
75086 pc = pOp->p2 - 1;
75087 rc = SQLITE_OK;
75089 break;
75091 #endif
75093 /* Opcode: Expire P1 * * * *
75095 ** Cause precompiled statements to expire. When an expired statement
75096 ** is executed using sqlite3_step() it will either automatically
75097 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
75098 ** or it will fail with SQLITE_SCHEMA.
75100 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
75101 ** then only the currently executing statement is expired.
75103 case OP_Expire: {
75104 if( !pOp->p1 ){
75105 sqlite3ExpirePreparedStatements(db);
75106 }else{
75107 p->expired = 1;
75109 break;
75112 #ifndef SQLITE_OMIT_SHARED_CACHE
75113 /* Opcode: TableLock P1 P2 P3 P4 *
75114 ** Synopsis: iDb=P1 root=P2 write=P3
75116 ** Obtain a lock on a particular table. This instruction is only used when
75117 ** the shared-cache feature is enabled.
75119 ** P1 is the index of the database in sqlite3.aDb[] of the database
75120 ** on which the lock is acquired. A readlock is obtained if P3==0 or
75121 ** a write lock if P3==1.
75123 ** P2 contains the root-page of the table to lock.
75125 ** P4 contains a pointer to the name of the table being locked. This is only
75126 ** used to generate an error message if the lock cannot be obtained.
75128 case OP_TableLock: {
75129 u8 isWriteLock = (u8)pOp->p3;
75130 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
75131 int p1 = pOp->p1;
75132 assert( p1>=0 && p1<db->nDb );
75133 assert( DbMaskTest(p->btreeMask, p1) );
75134 assert( isWriteLock==0 || isWriteLock==1 );
75135 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
75136 if( (rc&0xFF)==SQLITE_LOCKED ){
75137 const char *z = pOp->p4.z;
75138 sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
75141 break;
75143 #endif /* SQLITE_OMIT_SHARED_CACHE */
75145 #ifndef SQLITE_OMIT_VIRTUALTABLE
75146 /* Opcode: VBegin * * * P4 *
75148 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
75149 ** xBegin method for that table.
75151 ** Also, whether or not P4 is set, check that this is not being called from
75152 ** within a callback to a virtual table xSync() method. If it is, the error
75153 ** code will be set to SQLITE_LOCKED.
75155 case OP_VBegin: {
75156 VTable *pVTab;
75157 pVTab = pOp->p4.pVtab;
75158 rc = sqlite3VtabBegin(db, pVTab);
75159 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
75160 break;
75162 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75164 #ifndef SQLITE_OMIT_VIRTUALTABLE
75165 /* Opcode: VCreate P1 * * P4 *
75167 ** P4 is the name of a virtual table in database P1. Call the xCreate method
75168 ** for that table.
75170 case OP_VCreate: {
75171 rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
75172 break;
75174 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75176 #ifndef SQLITE_OMIT_VIRTUALTABLE
75177 /* Opcode: VDestroy P1 * * P4 *
75179 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
75180 ** of that table.
75182 case OP_VDestroy: {
75183 p->inVtabMethod = 2;
75184 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
75185 p->inVtabMethod = 0;
75186 break;
75188 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75190 #ifndef SQLITE_OMIT_VIRTUALTABLE
75191 /* Opcode: VOpen P1 * * P4 *
75193 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
75194 ** P1 is a cursor number. This opcode opens a cursor to the virtual
75195 ** table and stores that cursor in P1.
75197 case OP_VOpen: {
75198 VdbeCursor *pCur;
75199 sqlite3_vtab_cursor *pVtabCursor;
75200 sqlite3_vtab *pVtab;
75201 sqlite3_module *pModule;
75203 assert( p->bIsReader );
75204 pCur = 0;
75205 pVtabCursor = 0;
75206 pVtab = pOp->p4.pVtab->pVtab;
75207 pModule = (sqlite3_module *)pVtab->pModule;
75208 assert(pVtab && pModule);
75209 rc = pModule->xOpen(pVtab, &pVtabCursor);
75210 sqlite3VtabImportErrmsg(p, pVtab);
75211 if( SQLITE_OK==rc ){
75212 /* Initialize sqlite3_vtab_cursor base class */
75213 pVtabCursor->pVtab = pVtab;
75215 /* Initialize vdbe cursor object */
75216 pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
75217 if( pCur ){
75218 pCur->pVtabCursor = pVtabCursor;
75219 }else{
75220 db->mallocFailed = 1;
75221 pModule->xClose(pVtabCursor);
75224 break;
75226 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75228 #ifndef SQLITE_OMIT_VIRTUALTABLE
75229 /* Opcode: VFilter P1 P2 P3 P4 *
75230 ** Synopsis: iplan=r[P3] zplan='P4'
75232 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
75233 ** the filtered result set is empty.
75235 ** P4 is either NULL or a string that was generated by the xBestIndex
75236 ** method of the module. The interpretation of the P4 string is left
75237 ** to the module implementation.
75239 ** This opcode invokes the xFilter method on the virtual table specified
75240 ** by P1. The integer query plan parameter to xFilter is stored in register
75241 ** P3. Register P3+1 stores the argc parameter to be passed to the
75242 ** xFilter method. Registers P3+2..P3+1+argc are the argc
75243 ** additional parameters which are passed to
75244 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
75246 ** A jump is made to P2 if the result set after filtering would be empty.
75248 case OP_VFilter: { /* jump */
75249 int nArg;
75250 int iQuery;
75251 const sqlite3_module *pModule;
75252 Mem *pQuery;
75253 Mem *pArgc;
75254 sqlite3_vtab_cursor *pVtabCursor;
75255 sqlite3_vtab *pVtab;
75256 VdbeCursor *pCur;
75257 int res;
75258 int i;
75259 Mem **apArg;
75261 pQuery = &aMem[pOp->p3];
75262 pArgc = &pQuery[1];
75263 pCur = p->apCsr[pOp->p1];
75264 assert( memIsValid(pQuery) );
75265 REGISTER_TRACE(pOp->p3, pQuery);
75266 assert( pCur->pVtabCursor );
75267 pVtabCursor = pCur->pVtabCursor;
75268 pVtab = pVtabCursor->pVtab;
75269 pModule = pVtab->pModule;
75271 /* Grab the index number and argc parameters */
75272 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
75273 nArg = (int)pArgc->u.i;
75274 iQuery = (int)pQuery->u.i;
75276 /* Invoke the xFilter method */
75278 res = 0;
75279 apArg = p->apArg;
75280 for(i = 0; i<nArg; i++){
75281 apArg[i] = &pArgc[i+1];
75284 p->inVtabMethod = 1;
75285 rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
75286 p->inVtabMethod = 0;
75287 sqlite3VtabImportErrmsg(p, pVtab);
75288 if( rc==SQLITE_OK ){
75289 res = pModule->xEof(pVtabCursor);
75291 VdbeBranchTaken(res!=0,2);
75292 if( res ){
75293 pc = pOp->p2 - 1;
75296 pCur->nullRow = 0;
75298 break;
75300 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75302 #ifndef SQLITE_OMIT_VIRTUALTABLE
75303 /* Opcode: VColumn P1 P2 P3 * *
75304 ** Synopsis: r[P3]=vcolumn(P2)
75306 ** Store the value of the P2-th column of
75307 ** the row of the virtual-table that the
75308 ** P1 cursor is pointing to into register P3.
75310 case OP_VColumn: {
75311 sqlite3_vtab *pVtab;
75312 const sqlite3_module *pModule;
75313 Mem *pDest;
75314 sqlite3_context sContext;
75316 VdbeCursor *pCur = p->apCsr[pOp->p1];
75317 assert( pCur->pVtabCursor );
75318 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
75319 pDest = &aMem[pOp->p3];
75320 memAboutToChange(p, pDest);
75321 if( pCur->nullRow ){
75322 sqlite3VdbeMemSetNull(pDest);
75323 break;
75325 pVtab = pCur->pVtabCursor->pVtab;
75326 pModule = pVtab->pModule;
75327 assert( pModule->xColumn );
75328 memset(&sContext, 0, sizeof(sContext));
75329 sContext.pOut = pDest;
75330 MemSetTypeFlag(pDest, MEM_Null);
75331 rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
75332 sqlite3VtabImportErrmsg(p, pVtab);
75333 if( sContext.isError ){
75334 rc = sContext.isError;
75336 sqlite3VdbeChangeEncoding(pDest, encoding);
75337 REGISTER_TRACE(pOp->p3, pDest);
75338 UPDATE_MAX_BLOBSIZE(pDest);
75340 if( sqlite3VdbeMemTooBig(pDest) ){
75341 goto too_big;
75343 break;
75345 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75347 #ifndef SQLITE_OMIT_VIRTUALTABLE
75348 /* Opcode: VNext P1 P2 * * *
75350 ** Advance virtual table P1 to the next row in its result set and
75351 ** jump to instruction P2. Or, if the virtual table has reached
75352 ** the end of its result set, then fall through to the next instruction.
75354 case OP_VNext: { /* jump */
75355 sqlite3_vtab *pVtab;
75356 const sqlite3_module *pModule;
75357 int res;
75358 VdbeCursor *pCur;
75360 res = 0;
75361 pCur = p->apCsr[pOp->p1];
75362 assert( pCur->pVtabCursor );
75363 if( pCur->nullRow ){
75364 break;
75366 pVtab = pCur->pVtabCursor->pVtab;
75367 pModule = pVtab->pModule;
75368 assert( pModule->xNext );
75370 /* Invoke the xNext() method of the module. There is no way for the
75371 ** underlying implementation to return an error if one occurs during
75372 ** xNext(). Instead, if an error occurs, true is returned (indicating that
75373 ** data is available) and the error code returned when xColumn or
75374 ** some other method is next invoked on the save virtual table cursor.
75376 p->inVtabMethod = 1;
75377 rc = pModule->xNext(pCur->pVtabCursor);
75378 p->inVtabMethod = 0;
75379 sqlite3VtabImportErrmsg(p, pVtab);
75380 if( rc==SQLITE_OK ){
75381 res = pModule->xEof(pCur->pVtabCursor);
75383 VdbeBranchTaken(!res,2);
75384 if( !res ){
75385 /* If there is data, jump to P2 */
75386 pc = pOp->p2 - 1;
75388 goto check_for_interrupt;
75390 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75392 #ifndef SQLITE_OMIT_VIRTUALTABLE
75393 /* Opcode: VRename P1 * * P4 *
75395 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
75396 ** This opcode invokes the corresponding xRename method. The value
75397 ** in register P1 is passed as the zName argument to the xRename method.
75399 case OP_VRename: {
75400 sqlite3_vtab *pVtab;
75401 Mem *pName;
75403 pVtab = pOp->p4.pVtab->pVtab;
75404 pName = &aMem[pOp->p1];
75405 assert( pVtab->pModule->xRename );
75406 assert( memIsValid(pName) );
75407 assert( p->readOnly==0 );
75408 REGISTER_TRACE(pOp->p1, pName);
75409 assert( pName->flags & MEM_Str );
75410 testcase( pName->enc==SQLITE_UTF8 );
75411 testcase( pName->enc==SQLITE_UTF16BE );
75412 testcase( pName->enc==SQLITE_UTF16LE );
75413 rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
75414 if( rc==SQLITE_OK ){
75415 rc = pVtab->pModule->xRename(pVtab, pName->z);
75416 sqlite3VtabImportErrmsg(p, pVtab);
75417 p->expired = 0;
75419 break;
75421 #endif
75423 #ifndef SQLITE_OMIT_VIRTUALTABLE
75424 /* Opcode: VUpdate P1 P2 P3 P4 P5
75425 ** Synopsis: data=r[P3@P2]
75427 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
75428 ** This opcode invokes the corresponding xUpdate method. P2 values
75429 ** are contiguous memory cells starting at P3 to pass to the xUpdate
75430 ** invocation. The value in register (P3+P2-1) corresponds to the
75431 ** p2th element of the argv array passed to xUpdate.
75433 ** The xUpdate method will do a DELETE or an INSERT or both.
75434 ** The argv[0] element (which corresponds to memory cell P3)
75435 ** is the rowid of a row to delete. If argv[0] is NULL then no
75436 ** deletion occurs. The argv[1] element is the rowid of the new
75437 ** row. This can be NULL to have the virtual table select the new
75438 ** rowid for itself. The subsequent elements in the array are
75439 ** the values of columns in the new row.
75441 ** If P2==1 then no insert is performed. argv[0] is the rowid of
75442 ** a row to delete.
75444 ** P1 is a boolean flag. If it is set to true and the xUpdate call
75445 ** is successful, then the value returned by sqlite3_last_insert_rowid()
75446 ** is set to the value of the rowid for the row just inserted.
75448 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
75449 ** apply in the case of a constraint failure on an insert or update.
75451 case OP_VUpdate: {
75452 sqlite3_vtab *pVtab;
75453 sqlite3_module *pModule;
75454 int nArg;
75455 int i;
75456 sqlite_int64 rowid;
75457 Mem **apArg;
75458 Mem *pX;
75460 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
75461 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
75463 assert( p->readOnly==0 );
75464 pVtab = pOp->p4.pVtab->pVtab;
75465 pModule = (sqlite3_module *)pVtab->pModule;
75466 nArg = pOp->p2;
75467 assert( pOp->p4type==P4_VTAB );
75468 if( ALWAYS(pModule->xUpdate) ){
75469 u8 vtabOnConflict = db->vtabOnConflict;
75470 apArg = p->apArg;
75471 pX = &aMem[pOp->p3];
75472 for(i=0; i<nArg; i++){
75473 assert( memIsValid(pX) );
75474 memAboutToChange(p, pX);
75475 apArg[i] = pX;
75476 pX++;
75478 db->vtabOnConflict = pOp->p5;
75479 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
75480 db->vtabOnConflict = vtabOnConflict;
75481 sqlite3VtabImportErrmsg(p, pVtab);
75482 if( rc==SQLITE_OK && pOp->p1 ){
75483 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
75484 db->lastRowid = lastRowid = rowid;
75486 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
75487 if( pOp->p5==OE_Ignore ){
75488 rc = SQLITE_OK;
75489 }else{
75490 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
75492 }else{
75493 p->nChange++;
75496 break;
75498 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75500 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
75501 /* Opcode: Pagecount P1 P2 * * *
75503 ** Write the current number of pages in database P1 to memory cell P2.
75505 case OP_Pagecount: { /* out2-prerelease */
75506 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
75507 break;
75509 #endif
75512 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
75513 /* Opcode: MaxPgcnt P1 P2 P3 * *
75515 ** Try to set the maximum page count for database P1 to the value in P3.
75516 ** Do not let the maximum page count fall below the current page count and
75517 ** do not change the maximum page count value if P3==0.
75519 ** Store the maximum page count after the change in register P2.
75521 case OP_MaxPgcnt: { /* out2-prerelease */
75522 unsigned int newMax;
75523 Btree *pBt;
75525 pBt = db->aDb[pOp->p1].pBt;
75526 newMax = 0;
75527 if( pOp->p3 ){
75528 newMax = sqlite3BtreeLastPage(pBt);
75529 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
75531 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
75532 break;
75534 #endif
75537 /* Opcode: Init * P2 * P4 *
75538 ** Synopsis: Start at P2
75540 ** Programs contain a single instance of this opcode as the very first
75541 ** opcode.
75543 ** If tracing is enabled (by the sqlite3_trace()) interface, then
75544 ** the UTF-8 string contained in P4 is emitted on the trace callback.
75545 ** Or if P4 is blank, use the string returned by sqlite3_sql().
75547 ** If P2 is not zero, jump to instruction P2.
75549 case OP_Init: { /* jump */
75550 char *zTrace;
75551 char *z;
75553 if( pOp->p2 ){
75554 pc = pOp->p2 - 1;
75556 #ifndef SQLITE_OMIT_TRACE
75557 if( db->xTrace
75558 && !p->doingRerun
75559 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
75561 z = sqlite3VdbeExpandSql(p, zTrace);
75562 db->xTrace(db->pTraceArg, z);
75563 sqlite3DbFree(db, z);
75565 #ifdef SQLITE_USE_FCNTL_TRACE
75566 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
75567 if( zTrace ){
75568 int i;
75569 for(i=0; i<db->nDb; i++){
75570 if( DbMaskTest(p->btreeMask, i)==0 ) continue;
75571 sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
75574 #endif /* SQLITE_USE_FCNTL_TRACE */
75575 #ifdef SQLITE_DEBUG
75576 if( (db->flags & SQLITE_SqlTrace)!=0
75577 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
75579 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
75581 #endif /* SQLITE_DEBUG */
75582 #endif /* SQLITE_OMIT_TRACE */
75583 break;
75587 /* Opcode: Noop * * * * *
75589 ** Do nothing. This instruction is often useful as a jump
75590 ** destination.
75593 ** The magic Explain opcode are only inserted when explain==2 (which
75594 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
75595 ** This opcode records information from the optimizer. It is the
75596 ** the same as a no-op. This opcodesnever appears in a real VM program.
75598 default: { /* This is really OP_Noop and OP_Explain */
75599 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
75600 break;
75603 /*****************************************************************************
75604 ** The cases of the switch statement above this line should all be indented
75605 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
75606 ** readability. From this point on down, the normal indentation rules are
75607 ** restored.
75608 *****************************************************************************/
75611 #ifdef VDBE_PROFILE
75613 u64 endTime = sqlite3Hwtime();
75614 if( endTime>start ) pOp->cycles += endTime - start;
75615 pOp->cnt++;
75617 #endif
75619 /* The following code adds nothing to the actual functionality
75620 ** of the program. It is only here for testing and debugging.
75621 ** On the other hand, it does burn CPU cycles every time through
75622 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
75624 #ifndef NDEBUG
75625 assert( pc>=-1 && pc<p->nOp );
75627 #ifdef SQLITE_DEBUG
75628 if( db->flags & SQLITE_VdbeTrace ){
75629 if( rc!=0 ) printf("rc=%d\n",rc);
75630 if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
75631 registerTrace(pOp->p2, &aMem[pOp->p2]);
75633 if( pOp->opflags & OPFLG_OUT3 ){
75634 registerTrace(pOp->p3, &aMem[pOp->p3]);
75637 #endif /* SQLITE_DEBUG */
75638 #endif /* NDEBUG */
75639 } /* The end of the for(;;) loop the loops through opcodes */
75641 /* If we reach this point, it means that execution is finished with
75642 ** an error of some kind.
75644 vdbe_error_halt:
75645 assert( rc );
75646 p->rc = rc;
75647 testcase( sqlite3GlobalConfig.xLog!=0 );
75648 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
75649 pc, p->zSql, p->zErrMsg);
75650 sqlite3VdbeHalt(p);
75651 if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
75652 rc = SQLITE_ERROR;
75653 if( resetSchemaOnFault>0 ){
75654 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
75657 /* This is the only way out of this procedure. We have to
75658 ** release the mutexes on btrees that were acquired at the
75659 ** top. */
75660 vdbe_return:
75661 db->lastRowid = lastRowid;
75662 testcase( nVmStep>0 );
75663 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
75664 sqlite3VdbeLeave(p);
75665 return rc;
75667 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
75668 ** is encountered.
75670 too_big:
75671 sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
75672 rc = SQLITE_TOOBIG;
75673 goto vdbe_error_halt;
75675 /* Jump to here if a malloc() fails.
75677 no_mem:
75678 db->mallocFailed = 1;
75679 sqlite3SetString(&p->zErrMsg, db, "out of memory");
75680 rc = SQLITE_NOMEM;
75681 goto vdbe_error_halt;
75683 /* Jump to here for any other kind of fatal error. The "rc" variable
75684 ** should hold the error number.
75686 abort_due_to_error:
75687 assert( p->zErrMsg==0 );
75688 if( db->mallocFailed ) rc = SQLITE_NOMEM;
75689 if( rc!=SQLITE_IOERR_NOMEM ){
75690 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
75692 goto vdbe_error_halt;
75694 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
75695 ** flag.
75697 abort_due_to_interrupt:
75698 assert( db->u1.isInterrupted );
75699 rc = SQLITE_INTERRUPT;
75700 p->rc = rc;
75701 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
75702 goto vdbe_error_halt;
75706 /************** End of vdbe.c ************************************************/
75707 /************** Begin file vdbeblob.c ****************************************/
75709 ** 2007 May 1
75711 ** The author disclaims copyright to this source code. In place of
75712 ** a legal notice, here is a blessing:
75714 ** May you do good and not evil.
75715 ** May you find forgiveness for yourself and forgive others.
75716 ** May you share freely, never taking more than you give.
75718 *************************************************************************
75720 ** This file contains code used to implement incremental BLOB I/O.
75724 #ifndef SQLITE_OMIT_INCRBLOB
75727 ** Valid sqlite3_blob* handles point to Incrblob structures.
75729 typedef struct Incrblob Incrblob;
75730 struct Incrblob {
75731 int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
75732 int nByte; /* Size of open blob, in bytes */
75733 int iOffset; /* Byte offset of blob in cursor data */
75734 int iCol; /* Table column this handle is open on */
75735 BtCursor *pCsr; /* Cursor pointing at blob row */
75736 sqlite3_stmt *pStmt; /* Statement holding cursor open */
75737 sqlite3 *db; /* The associated database */
75742 ** This function is used by both blob_open() and blob_reopen(). It seeks
75743 ** the b-tree cursor associated with blob handle p to point to row iRow.
75744 ** If successful, SQLITE_OK is returned and subsequent calls to
75745 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
75747 ** If an error occurs, or if the specified row does not exist or does not
75748 ** contain a value of type TEXT or BLOB in the column nominated when the
75749 ** blob handle was opened, then an error code is returned and *pzErr may
75750 ** be set to point to a buffer containing an error message. It is the
75751 ** responsibility of the caller to free the error message buffer using
75752 ** sqlite3DbFree().
75754 ** If an error does occur, then the b-tree cursor is closed. All subsequent
75755 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
75756 ** immediately return SQLITE_ABORT.
75758 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
75759 int rc; /* Error code */
75760 char *zErr = 0; /* Error message */
75761 Vdbe *v = (Vdbe *)p->pStmt;
75763 /* Set the value of the SQL statements only variable to integer iRow.
75764 ** This is done directly instead of using sqlite3_bind_int64() to avoid
75765 ** triggering asserts related to mutexes.
75767 assert( v->aVar[0].flags&MEM_Int );
75768 v->aVar[0].u.i = iRow;
75770 rc = sqlite3_step(p->pStmt);
75771 if( rc==SQLITE_ROW ){
75772 VdbeCursor *pC = v->apCsr[0];
75773 u32 type = pC->aType[p->iCol];
75774 if( type<12 ){
75775 zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
75776 type==0?"null": type==7?"real": "integer"
75778 rc = SQLITE_ERROR;
75779 sqlite3_finalize(p->pStmt);
75780 p->pStmt = 0;
75781 }else{
75782 p->iOffset = pC->aType[p->iCol + pC->nField];
75783 p->nByte = sqlite3VdbeSerialTypeLen(type);
75784 p->pCsr = pC->pCursor;
75785 sqlite3BtreeIncrblobCursor(p->pCsr);
75789 if( rc==SQLITE_ROW ){
75790 rc = SQLITE_OK;
75791 }else if( p->pStmt ){
75792 rc = sqlite3_finalize(p->pStmt);
75793 p->pStmt = 0;
75794 if( rc==SQLITE_OK ){
75795 zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
75796 rc = SQLITE_ERROR;
75797 }else{
75798 zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
75802 assert( rc!=SQLITE_OK || zErr==0 );
75803 assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
75805 *pzErr = zErr;
75806 return rc;
75810 ** Open a blob handle.
75812 SQLITE_API int sqlite3_blob_open(
75813 sqlite3* db, /* The database connection */
75814 const char *zDb, /* The attached database containing the blob */
75815 const char *zTable, /* The table containing the blob */
75816 const char *zColumn, /* The column containing the blob */
75817 sqlite_int64 iRow, /* The row containing the glob */
75818 int flags, /* True -> read/write access, false -> read-only */
75819 sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
75821 int nAttempt = 0;
75822 int iCol; /* Index of zColumn in row-record */
75824 /* This VDBE program seeks a btree cursor to the identified
75825 ** db/table/row entry. The reason for using a vdbe program instead
75826 ** of writing code to use the b-tree layer directly is that the
75827 ** vdbe program will take advantage of the various transaction,
75828 ** locking and error handling infrastructure built into the vdbe.
75830 ** After seeking the cursor, the vdbe executes an OP_ResultRow.
75831 ** Code external to the Vdbe then "borrows" the b-tree cursor and
75832 ** uses it to implement the blob_read(), blob_write() and
75833 ** blob_bytes() functions.
75835 ** The sqlite3_blob_close() function finalizes the vdbe program,
75836 ** which closes the b-tree cursor and (possibly) commits the
75837 ** transaction.
75839 static const int iLn = VDBE_OFFSET_LINENO(4);
75840 static const VdbeOpList openBlob[] = {
75841 /* {OP_Transaction, 0, 0, 0}, // 0: Inserted separately */
75842 {OP_TableLock, 0, 0, 0}, /* 1: Acquire a read or write lock */
75843 /* One of the following two instructions is replaced by an OP_Noop. */
75844 {OP_OpenRead, 0, 0, 0}, /* 2: Open cursor 0 for reading */
75845 {OP_OpenWrite, 0, 0, 0}, /* 3: Open cursor 0 for read/write */
75846 {OP_Variable, 1, 1, 1}, /* 4: Push the rowid to the stack */
75847 {OP_NotExists, 0, 10, 1}, /* 5: Seek the cursor */
75848 {OP_Column, 0, 0, 1}, /* 6 */
75849 {OP_ResultRow, 1, 0, 0}, /* 7 */
75850 {OP_Goto, 0, 4, 0}, /* 8 */
75851 {OP_Close, 0, 0, 0}, /* 9 */
75852 {OP_Halt, 0, 0, 0}, /* 10 */
75855 int rc = SQLITE_OK;
75856 char *zErr = 0;
75857 Table *pTab;
75858 Parse *pParse = 0;
75859 Incrblob *pBlob = 0;
75861 flags = !!flags; /* flags = (flags ? 1 : 0); */
75862 *ppBlob = 0;
75864 sqlite3_mutex_enter(db->mutex);
75866 pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
75867 if( !pBlob ) goto blob_open_out;
75868 pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
75869 if( !pParse ) goto blob_open_out;
75871 do {
75872 memset(pParse, 0, sizeof(Parse));
75873 pParse->db = db;
75874 sqlite3DbFree(db, zErr);
75875 zErr = 0;
75877 sqlite3BtreeEnterAll(db);
75878 pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
75879 if( pTab && IsVirtual(pTab) ){
75880 pTab = 0;
75881 sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
75883 if( pTab && !HasRowid(pTab) ){
75884 pTab = 0;
75885 sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
75887 #ifndef SQLITE_OMIT_VIEW
75888 if( pTab && pTab->pSelect ){
75889 pTab = 0;
75890 sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
75892 #endif
75893 if( !pTab ){
75894 if( pParse->zErrMsg ){
75895 sqlite3DbFree(db, zErr);
75896 zErr = pParse->zErrMsg;
75897 pParse->zErrMsg = 0;
75899 rc = SQLITE_ERROR;
75900 sqlite3BtreeLeaveAll(db);
75901 goto blob_open_out;
75904 /* Now search pTab for the exact column. */
75905 for(iCol=0; iCol<pTab->nCol; iCol++) {
75906 if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
75907 break;
75910 if( iCol==pTab->nCol ){
75911 sqlite3DbFree(db, zErr);
75912 zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
75913 rc = SQLITE_ERROR;
75914 sqlite3BtreeLeaveAll(db);
75915 goto blob_open_out;
75918 /* If the value is being opened for writing, check that the
75919 ** column is not indexed, and that it is not part of a foreign key.
75920 ** It is against the rules to open a column to which either of these
75921 ** descriptions applies for writing. */
75922 if( flags ){
75923 const char *zFault = 0;
75924 Index *pIdx;
75925 #ifndef SQLITE_OMIT_FOREIGN_KEY
75926 if( db->flags&SQLITE_ForeignKeys ){
75927 /* Check that the column is not part of an FK child key definition. It
75928 ** is not necessary to check if it is part of a parent key, as parent
75929 ** key columns must be indexed. The check below will pick up this
75930 ** case. */
75931 FKey *pFKey;
75932 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
75933 int j;
75934 for(j=0; j<pFKey->nCol; j++){
75935 if( pFKey->aCol[j].iFrom==iCol ){
75936 zFault = "foreign key";
75941 #endif
75942 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
75943 int j;
75944 for(j=0; j<pIdx->nKeyCol; j++){
75945 if( pIdx->aiColumn[j]==iCol ){
75946 zFault = "indexed";
75950 if( zFault ){
75951 sqlite3DbFree(db, zErr);
75952 zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
75953 rc = SQLITE_ERROR;
75954 sqlite3BtreeLeaveAll(db);
75955 goto blob_open_out;
75959 pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
75960 assert( pBlob->pStmt || db->mallocFailed );
75961 if( pBlob->pStmt ){
75962 Vdbe *v = (Vdbe *)pBlob->pStmt;
75963 int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75966 sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
75967 pTab->pSchema->schema_cookie,
75968 pTab->pSchema->iGeneration);
75969 sqlite3VdbeChangeP5(v, 1);
75970 sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
75972 /* Make sure a mutex is held on the table to be accessed */
75973 sqlite3VdbeUsesBtree(v, iDb);
75975 /* Configure the OP_TableLock instruction */
75976 #ifdef SQLITE_OMIT_SHARED_CACHE
75977 sqlite3VdbeChangeToNoop(v, 1);
75978 #else
75979 sqlite3VdbeChangeP1(v, 1, iDb);
75980 sqlite3VdbeChangeP2(v, 1, pTab->tnum);
75981 sqlite3VdbeChangeP3(v, 1, flags);
75982 sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
75983 #endif
75985 /* Remove either the OP_OpenWrite or OpenRead. Set the P2
75986 ** parameter of the other to pTab->tnum. */
75987 sqlite3VdbeChangeToNoop(v, 3 - flags);
75988 sqlite3VdbeChangeP2(v, 2 + flags, pTab->tnum);
75989 sqlite3VdbeChangeP3(v, 2 + flags, iDb);
75991 /* Configure the number of columns. Configure the cursor to
75992 ** think that the table has one more column than it really
75993 ** does. An OP_Column to retrieve this imaginary column will
75994 ** always return an SQL NULL. This is useful because it means
75995 ** we can invoke OP_Column to fill in the vdbe cursors type
75996 ** and offset cache without causing any IO.
75998 sqlite3VdbeChangeP4(v, 2+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
75999 sqlite3VdbeChangeP2(v, 6, pTab->nCol);
76000 if( !db->mallocFailed ){
76001 pParse->nVar = 1;
76002 pParse->nMem = 1;
76003 pParse->nTab = 1;
76004 sqlite3VdbeMakeReady(v, pParse);
76008 pBlob->flags = flags;
76009 pBlob->iCol = iCol;
76010 pBlob->db = db;
76011 sqlite3BtreeLeaveAll(db);
76012 if( db->mallocFailed ){
76013 goto blob_open_out;
76015 sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
76016 rc = blobSeekToRow(pBlob, iRow, &zErr);
76017 } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
76019 blob_open_out:
76020 if( rc==SQLITE_OK && db->mallocFailed==0 ){
76021 *ppBlob = (sqlite3_blob *)pBlob;
76022 }else{
76023 if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
76024 sqlite3DbFree(db, pBlob);
76026 sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
76027 sqlite3DbFree(db, zErr);
76028 sqlite3ParserReset(pParse);
76029 sqlite3StackFree(db, pParse);
76030 rc = sqlite3ApiExit(db, rc);
76031 sqlite3_mutex_leave(db->mutex);
76032 return rc;
76036 ** Close a blob handle that was previously created using
76037 ** sqlite3_blob_open().
76039 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
76040 Incrblob *p = (Incrblob *)pBlob;
76041 int rc;
76042 sqlite3 *db;
76044 if( p ){
76045 db = p->db;
76046 sqlite3_mutex_enter(db->mutex);
76047 rc = sqlite3_finalize(p->pStmt);
76048 sqlite3DbFree(db, p);
76049 sqlite3_mutex_leave(db->mutex);
76050 }else{
76051 rc = SQLITE_OK;
76053 return rc;
76057 ** Perform a read or write operation on a blob
76059 static int blobReadWrite(
76060 sqlite3_blob *pBlob,
76061 void *z,
76062 int n,
76063 int iOffset,
76064 int (*xCall)(BtCursor*, u32, u32, void*)
76066 int rc;
76067 Incrblob *p = (Incrblob *)pBlob;
76068 Vdbe *v;
76069 sqlite3 *db;
76071 if( p==0 ) return SQLITE_MISUSE_BKPT;
76072 db = p->db;
76073 sqlite3_mutex_enter(db->mutex);
76074 v = (Vdbe*)p->pStmt;
76076 if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
76077 /* Request is out of range. Return a transient error. */
76078 rc = SQLITE_ERROR;
76079 sqlite3Error(db, SQLITE_ERROR);
76080 }else if( v==0 ){
76081 /* If there is no statement handle, then the blob-handle has
76082 ** already been invalidated. Return SQLITE_ABORT in this case.
76084 rc = SQLITE_ABORT;
76085 }else{
76086 /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
76087 ** returned, clean-up the statement handle.
76089 assert( db == v->db );
76090 sqlite3BtreeEnterCursor(p->pCsr);
76091 rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
76092 sqlite3BtreeLeaveCursor(p->pCsr);
76093 if( rc==SQLITE_ABORT ){
76094 sqlite3VdbeFinalize(v);
76095 p->pStmt = 0;
76096 }else{
76097 db->errCode = rc;
76098 v->rc = rc;
76101 rc = sqlite3ApiExit(db, rc);
76102 sqlite3_mutex_leave(db->mutex);
76103 return rc;
76107 ** Read data from a blob handle.
76109 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
76110 return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
76114 ** Write data to a blob handle.
76116 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
76117 return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
76121 ** Query a blob handle for the size of the data.
76123 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
76124 ** so no mutex is required for access.
76126 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
76127 Incrblob *p = (Incrblob *)pBlob;
76128 return (p && p->pStmt) ? p->nByte : 0;
76132 ** Move an existing blob handle to point to a different row of the same
76133 ** database table.
76135 ** If an error occurs, or if the specified row does not exist or does not
76136 ** contain a blob or text value, then an error code is returned and the
76137 ** database handle error code and message set. If this happens, then all
76138 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
76139 ** immediately return SQLITE_ABORT.
76141 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
76142 int rc;
76143 Incrblob *p = (Incrblob *)pBlob;
76144 sqlite3 *db;
76146 if( p==0 ) return SQLITE_MISUSE_BKPT;
76147 db = p->db;
76148 sqlite3_mutex_enter(db->mutex);
76150 if( p->pStmt==0 ){
76151 /* If there is no statement handle, then the blob-handle has
76152 ** already been invalidated. Return SQLITE_ABORT in this case.
76154 rc = SQLITE_ABORT;
76155 }else{
76156 char *zErr;
76157 rc = blobSeekToRow(p, iRow, &zErr);
76158 if( rc!=SQLITE_OK ){
76159 sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
76160 sqlite3DbFree(db, zErr);
76162 assert( rc!=SQLITE_SCHEMA );
76165 rc = sqlite3ApiExit(db, rc);
76166 assert( rc==SQLITE_OK || p->pStmt==0 );
76167 sqlite3_mutex_leave(db->mutex);
76168 return rc;
76171 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
76173 /************** End of vdbeblob.c ********************************************/
76174 /************** Begin file vdbesort.c ****************************************/
76176 ** 2011-07-09
76178 ** The author disclaims copyright to this source code. In place of
76179 ** a legal notice, here is a blessing:
76181 ** May you do good and not evil.
76182 ** May you find forgiveness for yourself and forgive others.
76183 ** May you share freely, never taking more than you give.
76185 *************************************************************************
76186 ** This file contains code for the VdbeSorter object, used in concert with
76187 ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
76188 ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
76189 ** using indexes and without LIMIT clauses.
76191 ** The VdbeSorter object implements a multi-threaded external merge sort
76192 ** algorithm that is efficient even if the number of elements being sorted
76193 ** exceeds the available memory.
76195 ** Here is the (internal, non-API) interface between this module and the
76196 ** rest of the SQLite system:
76198 ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
76200 ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
76201 ** object. The row is a binary blob in the
76202 ** OP_MakeRecord format that contains both
76203 ** the ORDER BY key columns and result columns
76204 ** in the case of a SELECT w/ ORDER BY, or
76205 ** the complete record for an index entry
76206 ** in the case of a CREATE INDEX.
76208 ** sqlite3VdbeSorterRewind() Sort all content previously added.
76209 ** Position the read cursor on the
76210 ** first sorted element.
76212 ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
76213 ** element.
76215 ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
76216 ** row currently under the read cursor.
76218 ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
76219 ** currently under the read cursor against
76220 ** another binary blob X and report if
76221 ** X is strictly less than the read cursor.
76222 ** Used to enforce uniqueness in a
76223 ** CREATE UNIQUE INDEX statement.
76225 ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
76226 ** all resources.
76228 ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
76229 ** is like Close() followed by Init() only
76230 ** much faster.
76232 ** The interfaces above must be called in a particular order. Write() can
76233 ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
76234 ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
76236 ** Init()
76237 ** for each record: Write()
76238 ** Rewind()
76239 ** Rowkey()/Compare()
76240 ** Next()
76241 ** Close()
76243 ** Algorithm:
76245 ** Records passed to the sorter via calls to Write() are initially held
76246 ** unsorted in main memory. Assuming the amount of memory used never exceeds
76247 ** a threshold, when Rewind() is called the set of records is sorted using
76248 ** an in-memory merge sort. In this case, no temporary files are required
76249 ** and subsequent calls to Rowkey(), Next() and Compare() read records
76250 ** directly from main memory.
76252 ** If the amount of space used to store records in main memory exceeds the
76253 ** threshold, then the set of records currently in memory are sorted and
76254 ** written to a temporary file in "Packed Memory Array" (PMA) format.
76255 ** A PMA created at this point is known as a "level-0 PMA". Higher levels
76256 ** of PMAs may be created by merging existing PMAs together - for example
76257 ** merging two or more level-0 PMAs together creates a level-1 PMA.
76259 ** The threshold for the amount of main memory to use before flushing
76260 ** records to a PMA is roughly the same as the limit configured for the
76261 ** page-cache of the main database. Specifically, the threshold is set to
76262 ** the value returned by "PRAGMA main.page_size" multipled by
76263 ** that returned by "PRAGMA main.cache_size", in bytes.
76265 ** If the sorter is running in single-threaded mode, then all PMAs generated
76266 ** are appended to a single temporary file. Or, if the sorter is running in
76267 ** multi-threaded mode then up to (N+1) temporary files may be opened, where
76268 ** N is the configured number of worker threads. In this case, instead of
76269 ** sorting the records and writing the PMA to a temporary file itself, the
76270 ** calling thread usually launches a worker thread to do so. Except, if
76271 ** there are already N worker threads running, the main thread does the work
76272 ** itself.
76274 ** The sorter is running in multi-threaded mode if (a) the library was built
76275 ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
76276 ** than zero, and (b) worker threads have been enabled at runtime by calling
76277 ** sqlite3_config(SQLITE_CONFIG_WORKER_THREADS, ...).
76279 ** When Rewind() is called, any data remaining in memory is flushed to a
76280 ** final PMA. So at this point the data is stored in some number of sorted
76281 ** PMAs within temporary files on disk.
76283 ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
76284 ** sorter is running in single-threaded mode, then these PMAs are merged
76285 ** incrementally as keys are retreived from the sorter by the VDBE. The
76286 ** MergeEngine object, described in further detail below, performs this
76287 ** merge.
76289 ** Or, if running in multi-threaded mode, then a background thread is
76290 ** launched to merge the existing PMAs. Once the background thread has
76291 ** merged T bytes of data into a single sorted PMA, the main thread
76292 ** begins reading keys from that PMA while the background thread proceeds
76293 ** with merging the next T bytes of data. And so on.
76295 ** Parameter T is set to half the value of the memory threshold used
76296 ** by Write() above to determine when to create a new PMA.
76298 ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
76299 ** Rewind() is called, then a hierarchy of incremental-merges is used.
76300 ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
76301 ** disk are merged together. Then T bytes of data from the second set, and
76302 ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
76303 ** PMAs at a time. This done is to improve locality.
76305 ** If running in multi-threaded mode and there are more than
76306 ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
76307 ** than one background thread may be created. Specifically, there may be
76308 ** one background thread for each temporary file on disk, and one background
76309 ** thread to merge the output of each of the others to a single PMA for
76310 ** the main thread to read from.
76314 ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
76315 ** messages to stderr that may be helpful in understanding the performance
76316 ** characteristics of the sorter in multi-threaded mode.
76318 #if 0
76319 # define SQLITE_DEBUG_SORTER_THREADS 1
76320 #endif
76323 ** Private objects used by the sorter
76325 typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
76326 typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
76327 typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
76328 typedef struct SorterRecord SorterRecord; /* A record being sorted */
76329 typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
76330 typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
76331 typedef struct SorterList SorterList; /* In-memory list of records */
76332 typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
76335 ** A container for a temp file handle and the current amount of data
76336 ** stored in the file.
76338 struct SorterFile {
76339 sqlite3_file *pFd; /* File handle */
76340 i64 iEof; /* Bytes of data stored in pFd */
76344 ** An in-memory list of objects to be sorted.
76346 ** If aMemory==0 then each object is allocated separately and the objects
76347 ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
76348 ** are stored in the aMemory[] bulk memory, one right after the other, and
76349 ** are connected using SorterRecord.u.iNext.
76351 struct SorterList {
76352 SorterRecord *pList; /* Linked list of records */
76353 u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
76354 int szPMA; /* Size of pList as PMA in bytes */
76358 ** The MergeEngine object is used to combine two or more smaller PMAs into
76359 ** one big PMA using a merge operation. Separate PMAs all need to be
76360 ** combined into one big PMA in order to be able to step through the sorted
76361 ** records in order.
76363 ** The aReadr[] array contains a PmaReader object for each of the PMAs being
76364 ** merged. An aReadr[] object either points to a valid key or else is at EOF.
76365 ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
76366 ** For the purposes of the paragraphs below, we assume that the array is
76367 ** actually N elements in size, where N is the smallest power of 2 greater
76368 ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
76369 ** are treated as if they are empty (always at EOF).
76371 ** The aTree[] array is also N elements in size. The value of N is stored in
76372 ** the MergeEngine.nTree variable.
76374 ** The final (N/2) elements of aTree[] contain the results of comparing
76375 ** pairs of PMA keys together. Element i contains the result of
76376 ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
76377 ** aTree element is set to the index of it.
76379 ** For the purposes of this comparison, EOF is considered greater than any
76380 ** other key value. If the keys are equal (only possible with two EOF
76381 ** values), it doesn't matter which index is stored.
76383 ** The (N/4) elements of aTree[] that precede the final (N/2) described
76384 ** above contains the index of the smallest of each block of 4 PmaReaders
76385 ** And so on. So that aTree[1] contains the index of the PmaReader that
76386 ** currently points to the smallest key value. aTree[0] is unused.
76388 ** Example:
76390 ** aReadr[0] -> Banana
76391 ** aReadr[1] -> Feijoa
76392 ** aReadr[2] -> Elderberry
76393 ** aReadr[3] -> Currant
76394 ** aReadr[4] -> Grapefruit
76395 ** aReadr[5] -> Apple
76396 ** aReadr[6] -> Durian
76397 ** aReadr[7] -> EOF
76399 ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
76401 ** The current element is "Apple" (the value of the key indicated by
76402 ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
76403 ** be advanced to the next key in its segment. Say the next key is
76404 ** "Eggplant":
76406 ** aReadr[5] -> Eggplant
76408 ** The contents of aTree[] are updated first by comparing the new PmaReader
76409 ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
76410 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
76411 ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
76412 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
76413 ** so the value written into element 1 of the array is 0. As follows:
76415 ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
76417 ** In other words, each time we advance to the next sorter element, log2(N)
76418 ** key comparison operations are required, where N is the number of segments
76419 ** being merged (rounded up to the next power of 2).
76421 struct MergeEngine {
76422 int nTree; /* Used size of aTree/aReadr (power of 2) */
76423 SortSubtask *pTask; /* Used by this thread only */
76424 int *aTree; /* Current state of incremental merge */
76425 PmaReader *aReadr; /* Array of PmaReaders to merge data from */
76429 ** This object represents a single thread of control in a sort operation.
76430 ** Exactly VdbeSorter.nTask instances of this object are allocated
76431 ** as part of each VdbeSorter object. Instances are never allocated any
76432 ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
76433 ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
76434 ** single-threaded operation, there is exactly one instance of this object
76435 ** and for multi-threaded operation there are two or more instances.
76437 ** Essentially, this structure contains all those fields of the VdbeSorter
76438 ** structure for which each thread requires a separate instance. For example,
76439 ** each thread requries its own UnpackedRecord object to unpack records in
76440 ** as part of comparison operations.
76442 ** Before a background thread is launched, variable bDone is set to 0. Then,
76443 ** right before it exits, the thread itself sets bDone to 1. This is used for
76444 ** two purposes:
76446 ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
76447 ** attempt to select a SortSubtask for which there is not already an
76448 ** active background thread (since doing so causes the main thread
76449 ** to block until it finishes).
76451 ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
76452 ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
76453 ** block provoke debugging output.
76455 ** In both cases, the effects of the main thread seeing (bDone==0) even
76456 ** after the thread has finished are not dire. So we don't worry about
76457 ** memory barriers and such here.
76459 struct SortSubtask {
76460 SQLiteThread *pThread; /* Background thread, if any */
76461 int bDone; /* Set if thread is finished but not joined */
76462 VdbeSorter *pSorter; /* Sorter that owns this sub-task */
76463 UnpackedRecord *pUnpacked; /* Space to unpack a record */
76464 SorterList list; /* List for thread to write to a PMA */
76465 int nPMA; /* Number of PMAs currently in file */
76466 SorterFile file; /* Temp file for level-0 PMAs */
76467 SorterFile file2; /* Space for other PMAs */
76471 ** Main sorter structure. A single instance of this is allocated for each
76472 ** sorter cursor created by the VDBE.
76474 ** mxKeysize:
76475 ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
76476 ** this variable is updated so as to be set to the size on disk of the
76477 ** largest record in the sorter.
76479 struct VdbeSorter {
76480 int mnPmaSize; /* Minimum PMA size, in bytes */
76481 int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
76482 int mxKeysize; /* Largest serialized key seen so far */
76483 int pgsz; /* Main database page size */
76484 PmaReader *pReader; /* Readr data from here after Rewind() */
76485 MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
76486 sqlite3 *db; /* Database connection */
76487 KeyInfo *pKeyInfo; /* How to compare records */
76488 UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
76489 SorterList list; /* List of in-memory records */
76490 int iMemory; /* Offset of free space in list.aMemory */
76491 int nMemory; /* Size of list.aMemory allocation in bytes */
76492 u8 bUsePMA; /* True if one or more PMAs created */
76493 u8 bUseThreads; /* True to use background threads */
76494 u8 iPrev; /* Previous thread used to flush PMA */
76495 u8 nTask; /* Size of aTask[] array */
76496 SortSubtask aTask[1]; /* One or more subtasks */
76500 ** An instance of the following object is used to read records out of a
76501 ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
76502 ** aKey might point into aMap or into aBuffer. If neither of those locations
76503 ** contain a contiguous representation of the key, then aAlloc is allocated
76504 ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
76506 ** pFd==0 at EOF.
76508 struct PmaReader {
76509 i64 iReadOff; /* Current read offset */
76510 i64 iEof; /* 1 byte past EOF for this PmaReader */
76511 int nAlloc; /* Bytes of space at aAlloc */
76512 int nKey; /* Number of bytes in key */
76513 sqlite3_file *pFd; /* File handle we are reading from */
76514 u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
76515 u8 *aKey; /* Pointer to current key */
76516 u8 *aBuffer; /* Current read buffer */
76517 int nBuffer; /* Size of read buffer in bytes */
76518 u8 *aMap; /* Pointer to mapping of entire file */
76519 IncrMerger *pIncr; /* Incremental merger */
76523 ** Normally, a PmaReader object iterates through an existing PMA stored
76524 ** within a temp file. However, if the PmaReader.pIncr variable points to
76525 ** an object of the following type, it may be used to iterate/merge through
76526 ** multiple PMAs simultaneously.
76528 ** There are two types of IncrMerger object - single (bUseThread==0) and
76529 ** multi-threaded (bUseThread==1).
76531 ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
76532 ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
76533 ** size. When the IncrMerger is initialized, it reads enough data from
76534 ** pMerger to populate aFile[0]. It then sets variables within the
76535 ** corresponding PmaReader object to read from that file and kicks off
76536 ** a background thread to populate aFile[1] with the next mxSz bytes of
76537 ** sorted record data from pMerger.
76539 ** When the PmaReader reaches the end of aFile[0], it blocks until the
76540 ** background thread has finished populating aFile[1]. It then exchanges
76541 ** the contents of the aFile[0] and aFile[1] variables within this structure,
76542 ** sets the PmaReader fields to read from the new aFile[0] and kicks off
76543 ** another background thread to populate the new aFile[1]. And so on, until
76544 ** the contents of pMerger are exhausted.
76546 ** A single-threaded IncrMerger does not open any temporary files of its
76547 ** own. Instead, it has exclusive access to mxSz bytes of space beginning
76548 ** at offset iStartOff of file pTask->file2. And instead of using a
76549 ** background thread to prepare data for the PmaReader, with a single
76550 ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
76551 ** keys from pMerger by the calling thread whenever the PmaReader runs out
76552 ** of data.
76554 struct IncrMerger {
76555 SortSubtask *pTask; /* Task that owns this merger */
76556 MergeEngine *pMerger; /* Merge engine thread reads data from */
76557 i64 iStartOff; /* Offset to start writing file at */
76558 int mxSz; /* Maximum bytes of data to store */
76559 int bEof; /* Set to true when merge is finished */
76560 int bUseThread; /* True to use a bg thread for this object */
76561 SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
76565 ** An instance of this object is used for writing a PMA.
76567 ** The PMA is written one record at a time. Each record is of an arbitrary
76568 ** size. But I/O is more efficient if it occurs in page-sized blocks where
76569 ** each block is aligned on a page boundary. This object caches writes to
76570 ** the PMA so that aligned, page-size blocks are written.
76572 struct PmaWriter {
76573 int eFWErr; /* Non-zero if in an error state */
76574 u8 *aBuffer; /* Pointer to write buffer */
76575 int nBuffer; /* Size of write buffer in bytes */
76576 int iBufStart; /* First byte of buffer to write */
76577 int iBufEnd; /* Last byte of buffer to write */
76578 i64 iWriteOff; /* Offset of start of buffer in file */
76579 sqlite3_file *pFd; /* File handle to write to */
76583 ** This object is the header on a single record while that record is being
76584 ** held in memory and prior to being written out as part of a PMA.
76586 ** How the linked list is connected depends on how memory is being managed
76587 ** by this module. If using a separate allocation for each in-memory record
76588 ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
76589 ** SorterRecord.u.pNext pointers.
76591 ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
76592 ** then while records are being accumulated the list is linked using the
76593 ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
76594 ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
76595 ** has finished passing records to the sorter, or when the in-memory buffer
76596 ** is full, the list is sorted. As part of the sorting process, it is
76597 ** converted to use the SorterRecord.u.pNext pointers. See function
76598 ** vdbeSorterSort() for details.
76600 struct SorterRecord {
76601 int nVal; /* Size of the record in bytes */
76602 union {
76603 SorterRecord *pNext; /* Pointer to next record in list */
76604 int iNext; /* Offset within aMemory of next record */
76605 } u;
76606 /* The data for the record immediately follows this header */
76609 /* Return a pointer to the buffer containing the record data for SorterRecord
76610 ** object p. Should be used as if:
76612 ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
76614 #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
76616 /* The minimum PMA size is set to this value multiplied by the database
76617 ** page size in bytes. */
76618 #define SORTER_MIN_WORKING 10
76620 /* Maximum number of PMAs that a single MergeEngine can merge */
76621 #define SORTER_MAX_MERGE_COUNT 16
76623 static int vdbeIncrSwap(IncrMerger*);
76624 static void vdbeIncrFree(IncrMerger *);
76627 ** Free all memory belonging to the PmaReader object passed as the
76628 ** argument. All structure fields are set to zero before returning.
76630 static void vdbePmaReaderClear(PmaReader *pReadr){
76631 sqlite3_free(pReadr->aAlloc);
76632 sqlite3_free(pReadr->aBuffer);
76633 if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
76634 vdbeIncrFree(pReadr->pIncr);
76635 memset(pReadr, 0, sizeof(PmaReader));
76639 ** Read the next nByte bytes of data from the PMA p.
76640 ** If successful, set *ppOut to point to a buffer containing the data
76641 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
76642 ** error code.
76644 ** The buffer returned in *ppOut is only valid until the
76645 ** next call to this function.
76647 static int vdbePmaReadBlob(
76648 PmaReader *p, /* PmaReader from which to take the blob */
76649 int nByte, /* Bytes of data to read */
76650 u8 **ppOut /* OUT: Pointer to buffer containing data */
76652 int iBuf; /* Offset within buffer to read from */
76653 int nAvail; /* Bytes of data available in buffer */
76655 if( p->aMap ){
76656 *ppOut = &p->aMap[p->iReadOff];
76657 p->iReadOff += nByte;
76658 return SQLITE_OK;
76661 assert( p->aBuffer );
76663 /* If there is no more data to be read from the buffer, read the next
76664 ** p->nBuffer bytes of data from the file into it. Or, if there are less
76665 ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
76666 iBuf = p->iReadOff % p->nBuffer;
76667 if( iBuf==0 ){
76668 int nRead; /* Bytes to read from disk */
76669 int rc; /* sqlite3OsRead() return code */
76671 /* Determine how many bytes of data to read. */
76672 if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
76673 nRead = p->nBuffer;
76674 }else{
76675 nRead = (int)(p->iEof - p->iReadOff);
76677 assert( nRead>0 );
76679 /* Readr data from the file. Return early if an error occurs. */
76680 rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
76681 assert( rc!=SQLITE_IOERR_SHORT_READ );
76682 if( rc!=SQLITE_OK ) return rc;
76684 nAvail = p->nBuffer - iBuf;
76686 if( nByte<=nAvail ){
76687 /* The requested data is available in the in-memory buffer. In this
76688 ** case there is no need to make a copy of the data, just return a
76689 ** pointer into the buffer to the caller. */
76690 *ppOut = &p->aBuffer[iBuf];
76691 p->iReadOff += nByte;
76692 }else{
76693 /* The requested data is not all available in the in-memory buffer.
76694 ** In this case, allocate space at p->aAlloc[] to copy the requested
76695 ** range into. Then return a copy of pointer p->aAlloc to the caller. */
76696 int nRem; /* Bytes remaining to copy */
76698 /* Extend the p->aAlloc[] allocation if required. */
76699 if( p->nAlloc<nByte ){
76700 u8 *aNew;
76701 int nNew = MAX(128, p->nAlloc*2);
76702 while( nByte>nNew ) nNew = nNew*2;
76703 aNew = sqlite3Realloc(p->aAlloc, nNew);
76704 if( !aNew ) return SQLITE_NOMEM;
76705 p->nAlloc = nNew;
76706 p->aAlloc = aNew;
76709 /* Copy as much data as is available in the buffer into the start of
76710 ** p->aAlloc[]. */
76711 memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
76712 p->iReadOff += nAvail;
76713 nRem = nByte - nAvail;
76715 /* The following loop copies up to p->nBuffer bytes per iteration into
76716 ** the p->aAlloc[] buffer. */
76717 while( nRem>0 ){
76718 int rc; /* vdbePmaReadBlob() return code */
76719 int nCopy; /* Number of bytes to copy */
76720 u8 *aNext; /* Pointer to buffer to copy data from */
76722 nCopy = nRem;
76723 if( nRem>p->nBuffer ) nCopy = p->nBuffer;
76724 rc = vdbePmaReadBlob(p, nCopy, &aNext);
76725 if( rc!=SQLITE_OK ) return rc;
76726 assert( aNext!=p->aAlloc );
76727 memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
76728 nRem -= nCopy;
76731 *ppOut = p->aAlloc;
76734 return SQLITE_OK;
76738 ** Read a varint from the stream of data accessed by p. Set *pnOut to
76739 ** the value read.
76741 static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
76742 int iBuf;
76744 if( p->aMap ){
76745 p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
76746 }else{
76747 iBuf = p->iReadOff % p->nBuffer;
76748 if( iBuf && (p->nBuffer-iBuf)>=9 ){
76749 p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
76750 }else{
76751 u8 aVarint[16], *a;
76752 int i = 0, rc;
76754 rc = vdbePmaReadBlob(p, 1, &a);
76755 if( rc ) return rc;
76756 aVarint[(i++)&0xf] = a[0];
76757 }while( (a[0]&0x80)!=0 );
76758 sqlite3GetVarint(aVarint, pnOut);
76762 return SQLITE_OK;
76766 ** Attempt to memory map file pFile. If successful, set *pp to point to the
76767 ** new mapping and return SQLITE_OK. If the mapping is not attempted
76768 ** (because the file is too large or the VFS layer is configured not to use
76769 ** mmap), return SQLITE_OK and set *pp to NULL.
76771 ** Or, if an error occurs, return an SQLite error code. The final value of
76772 ** *pp is undefined in this case.
76774 static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
76775 int rc = SQLITE_OK;
76776 if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
76777 sqlite3_file *pFd = pFile->pFd;
76778 if( pFd->pMethods->iVersion>=3 ){
76779 rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
76780 testcase( rc!=SQLITE_OK );
76783 return rc;
76787 ** Attach PmaReader pReadr to file pFile (if it is not already attached to
76788 ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
76789 ** if successful, or an SQLite error code if an error occurs.
76791 static int vdbePmaReaderSeek(
76792 SortSubtask *pTask, /* Task context */
76793 PmaReader *pReadr, /* Reader whose cursor is to be moved */
76794 SorterFile *pFile, /* Sorter file to read from */
76795 i64 iOff /* Offset in pFile */
76797 int rc = SQLITE_OK;
76799 assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
76801 if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
76802 if( pReadr->aMap ){
76803 sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
76804 pReadr->aMap = 0;
76806 pReadr->iReadOff = iOff;
76807 pReadr->iEof = pFile->iEof;
76808 pReadr->pFd = pFile->pFd;
76810 rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
76811 if( rc==SQLITE_OK && pReadr->aMap==0 ){
76812 int pgsz = pTask->pSorter->pgsz;
76813 int iBuf = pReadr->iReadOff % pgsz;
76814 if( pReadr->aBuffer==0 ){
76815 pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
76816 if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM;
76817 pReadr->nBuffer = pgsz;
76819 if( rc==SQLITE_OK && iBuf ){
76820 int nRead = pgsz - iBuf;
76821 if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
76822 nRead = (int)(pReadr->iEof - pReadr->iReadOff);
76824 rc = sqlite3OsRead(
76825 pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
76827 testcase( rc!=SQLITE_OK );
76831 return rc;
76835 ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
76836 ** no error occurs, or an SQLite error code if one does.
76838 static int vdbePmaReaderNext(PmaReader *pReadr){
76839 int rc = SQLITE_OK; /* Return Code */
76840 u64 nRec = 0; /* Size of record in bytes */
76843 if( pReadr->iReadOff>=pReadr->iEof ){
76844 IncrMerger *pIncr = pReadr->pIncr;
76845 int bEof = 1;
76846 if( pIncr ){
76847 rc = vdbeIncrSwap(pIncr);
76848 if( rc==SQLITE_OK && pIncr->bEof==0 ){
76849 rc = vdbePmaReaderSeek(
76850 pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
76852 bEof = 0;
76856 if( bEof ){
76857 /* This is an EOF condition */
76858 vdbePmaReaderClear(pReadr);
76859 testcase( rc!=SQLITE_OK );
76860 return rc;
76864 if( rc==SQLITE_OK ){
76865 rc = vdbePmaReadVarint(pReadr, &nRec);
76867 if( rc==SQLITE_OK ){
76868 pReadr->nKey = (int)nRec;
76869 rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
76870 testcase( rc!=SQLITE_OK );
76873 return rc;
76877 ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
76878 ** starting at offset iStart and ending at offset iEof-1. This function
76879 ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
76880 ** PMA is empty).
76882 ** If the pnByte parameter is NULL, then it is assumed that the file
76883 ** contains a single PMA, and that that PMA omits the initial length varint.
76885 static int vdbePmaReaderInit(
76886 SortSubtask *pTask, /* Task context */
76887 SorterFile *pFile, /* Sorter file to read from */
76888 i64 iStart, /* Start offset in pFile */
76889 PmaReader *pReadr, /* PmaReader to populate */
76890 i64 *pnByte /* IN/OUT: Increment this value by PMA size */
76892 int rc;
76894 assert( pFile->iEof>iStart );
76895 assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
76896 assert( pReadr->aBuffer==0 );
76897 assert( pReadr->aMap==0 );
76899 rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
76900 if( rc==SQLITE_OK ){
76901 u64 nByte; /* Size of PMA in bytes */
76902 rc = vdbePmaReadVarint(pReadr, &nByte);
76903 pReadr->iEof = pReadr->iReadOff + nByte;
76904 *pnByte += nByte;
76907 if( rc==SQLITE_OK ){
76908 rc = vdbePmaReaderNext(pReadr);
76910 return rc;
76915 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
76916 ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
76917 ** used by the comparison. Return the result of the comparison.
76919 ** Before returning, object (pTask->pUnpacked) is populated with the
76920 ** unpacked version of key2. Or, if pKey2 is passed a NULL pointer, then it
76921 ** is assumed that the (pTask->pUnpacked) structure already contains the
76922 ** unpacked key to use as key2.
76924 ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
76925 ** to SQLITE_NOMEM.
76927 static int vdbeSorterCompare(
76928 SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
76929 const void *pKey1, int nKey1, /* Left side of comparison */
76930 const void *pKey2, int nKey2 /* Right side of comparison */
76932 UnpackedRecord *r2 = pTask->pUnpacked;
76933 if( pKey2 ){
76934 sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
76936 return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
76940 ** Initialize the temporary index cursor just opened as a sorter cursor.
76942 ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
76943 ** to determine the number of fields that should be compared from the
76944 ** records being sorted. However, if the value passed as argument nField
76945 ** is non-zero and the sorter is able to guarantee a stable sort, nField
76946 ** is used instead. This is used when sorting records for a CREATE INDEX
76947 ** statement. In this case, keys are always delivered to the sorter in
76948 ** order of the primary key, which happens to be make up the final part
76949 ** of the records being sorted. So if the sort is stable, there is never
76950 ** any reason to compare PK fields and they can be ignored for a small
76951 ** performance boost.
76953 ** The sorter can guarantee a stable sort when running in single-threaded
76954 ** mode, but not in multi-threaded mode.
76956 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
76958 SQLITE_PRIVATE int sqlite3VdbeSorterInit(
76959 sqlite3 *db, /* Database connection (for malloc()) */
76960 int nField, /* Number of key fields in each record */
76961 VdbeCursor *pCsr /* Cursor that holds the new sorter */
76963 int pgsz; /* Page size of main database */
76964 int i; /* Used to iterate through aTask[] */
76965 int mxCache; /* Cache size */
76966 VdbeSorter *pSorter; /* The new sorter */
76967 KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
76968 int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
76969 int sz; /* Size of pSorter in bytes */
76970 int rc = SQLITE_OK;
76971 #if SQLITE_MAX_WORKER_THREADS==0
76972 # define nWorker 0
76973 #else
76974 int nWorker;
76975 #endif
76977 /* Initialize the upper limit on the number of worker threads */
76978 #if SQLITE_MAX_WORKER_THREADS>0
76979 if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
76980 nWorker = 0;
76981 }else{
76982 nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
76984 #endif
76986 /* Do not allow the total number of threads (main thread + all workers)
76987 ** to exceed the maximum merge count */
76988 #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
76989 if( nWorker>=SORTER_MAX_MERGE_COUNT ){
76990 nWorker = SORTER_MAX_MERGE_COUNT-1;
76992 #endif
76994 assert( pCsr->pKeyInfo && pCsr->pBt==0 );
76995 szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
76996 sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
76998 pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
76999 pCsr->pSorter = pSorter;
77000 if( pSorter==0 ){
77001 rc = SQLITE_NOMEM;
77002 }else{
77003 pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
77004 memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
77005 pKeyInfo->db = 0;
77006 if( nField && nWorker==0 ) pKeyInfo->nField = nField;
77007 pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
77008 pSorter->nTask = nWorker + 1;
77009 pSorter->bUseThreads = (pSorter->nTask>1);
77010 pSorter->db = db;
77011 for(i=0; i<pSorter->nTask; i++){
77012 SortSubtask *pTask = &pSorter->aTask[i];
77013 pTask->pSorter = pSorter;
77016 if( !sqlite3TempInMemory(db) ){
77017 pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
77018 mxCache = db->aDb[0].pSchema->cache_size;
77019 if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
77020 pSorter->mxPmaSize = mxCache * pgsz;
77022 /* If the application has not configure scratch memory using
77023 ** SQLITE_CONFIG_SCRATCH then we assume it is OK to do large memory
77024 ** allocations. If scratch memory has been configured, then assume
77025 ** large memory allocations should be avoided to prevent heap
77026 ** fragmentation.
77028 if( sqlite3GlobalConfig.pScratch==0 ){
77029 assert( pSorter->iMemory==0 );
77030 pSorter->nMemory = pgsz;
77031 pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
77032 if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM;
77037 return rc;
77039 #undef nWorker /* Defined at the top of this function */
77042 ** Free the list of sorted records starting at pRecord.
77044 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
77045 SorterRecord *p;
77046 SorterRecord *pNext;
77047 for(p=pRecord; p; p=pNext){
77048 pNext = p->u.pNext;
77049 sqlite3DbFree(db, p);
77054 ** Free all resources owned by the object indicated by argument pTask. All
77055 ** fields of *pTask are zeroed before returning.
77057 static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
77058 sqlite3DbFree(db, pTask->pUnpacked);
77059 pTask->pUnpacked = 0;
77060 #if SQLITE_MAX_WORKER_THREADS>0
77061 /* pTask->list.aMemory can only be non-zero if it was handed memory
77062 ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
77063 if( pTask->list.aMemory ){
77064 sqlite3_free(pTask->list.aMemory);
77065 pTask->list.aMemory = 0;
77066 }else
77067 #endif
77069 assert( pTask->list.aMemory==0 );
77070 vdbeSorterRecordFree(0, pTask->list.pList);
77072 pTask->list.pList = 0;
77073 if( pTask->file.pFd ){
77074 sqlite3OsCloseFree(pTask->file.pFd);
77075 pTask->file.pFd = 0;
77076 pTask->file.iEof = 0;
77078 if( pTask->file2.pFd ){
77079 sqlite3OsCloseFree(pTask->file2.pFd);
77080 pTask->file2.pFd = 0;
77081 pTask->file2.iEof = 0;
77085 #ifdef SQLITE_DEBUG_SORTER_THREADS
77086 static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
77087 i64 t;
77088 int iTask = (pTask - pTask->pSorter->aTask);
77089 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
77090 fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
77092 static void vdbeSorterRewindDebug(const char *zEvent){
77093 i64 t;
77094 sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
77095 fprintf(stderr, "%lld:X %s\n", t, zEvent);
77097 static void vdbeSorterPopulateDebug(
77098 SortSubtask *pTask,
77099 const char *zEvent
77101 i64 t;
77102 int iTask = (pTask - pTask->pSorter->aTask);
77103 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
77104 fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
77106 static void vdbeSorterBlockDebug(
77107 SortSubtask *pTask,
77108 int bBlocked,
77109 const char *zEvent
77111 if( bBlocked ){
77112 i64 t;
77113 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
77114 fprintf(stderr, "%lld:main %s\n", t, zEvent);
77117 #else
77118 # define vdbeSorterWorkDebug(x,y)
77119 # define vdbeSorterRewindDebug(y)
77120 # define vdbeSorterPopulateDebug(x,y)
77121 # define vdbeSorterBlockDebug(x,y,z)
77122 #endif
77124 #if SQLITE_MAX_WORKER_THREADS>0
77126 ** Join thread pTask->thread.
77128 static int vdbeSorterJoinThread(SortSubtask *pTask){
77129 int rc = SQLITE_OK;
77130 if( pTask->pThread ){
77131 #ifdef SQLITE_DEBUG_SORTER_THREADS
77132 int bDone = pTask->bDone;
77133 #endif
77134 void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
77135 vdbeSorterBlockDebug(pTask, !bDone, "enter");
77136 (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
77137 vdbeSorterBlockDebug(pTask, !bDone, "exit");
77138 rc = SQLITE_PTR_TO_INT(pRet);
77139 assert( pTask->bDone==1 );
77140 pTask->bDone = 0;
77141 pTask->pThread = 0;
77143 return rc;
77147 ** Launch a background thread to run xTask(pIn).
77149 static int vdbeSorterCreateThread(
77150 SortSubtask *pTask, /* Thread will use this task object */
77151 void *(*xTask)(void*), /* Routine to run in a separate thread */
77152 void *pIn /* Argument passed into xTask() */
77154 assert( pTask->pThread==0 && pTask->bDone==0 );
77155 return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
77159 ** Join all outstanding threads launched by SorterWrite() to create
77160 ** level-0 PMAs.
77162 static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
77163 int rc = rcin;
77164 int i;
77166 /* This function is always called by the main user thread.
77168 ** If this function is being called after SorterRewind() has been called,
77169 ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
77170 ** is currently attempt to join one of the other threads. To avoid a race
77171 ** condition where this thread also attempts to join the same object, join
77172 ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
77173 for(i=pSorter->nTask-1; i>=0; i--){
77174 SortSubtask *pTask = &pSorter->aTask[i];
77175 int rc2 = vdbeSorterJoinThread(pTask);
77176 if( rc==SQLITE_OK ) rc = rc2;
77178 return rc;
77180 #else
77181 # define vdbeSorterJoinAll(x,rcin) (rcin)
77182 # define vdbeSorterJoinThread(pTask) SQLITE_OK
77183 #endif
77186 ** Allocate a new MergeEngine object capable of handling up to
77187 ** nReader PmaReader inputs.
77189 ** nReader is automatically rounded up to the next power of two.
77190 ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
77192 static MergeEngine *vdbeMergeEngineNew(int nReader){
77193 int N = 2; /* Smallest power of two >= nReader */
77194 int nByte; /* Total bytes of space to allocate */
77195 MergeEngine *pNew; /* Pointer to allocated object to return */
77197 assert( nReader<=SORTER_MAX_MERGE_COUNT );
77199 while( N<nReader ) N += N;
77200 nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
77202 pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
77203 if( pNew ){
77204 pNew->nTree = N;
77205 pNew->pTask = 0;
77206 pNew->aReadr = (PmaReader*)&pNew[1];
77207 pNew->aTree = (int*)&pNew->aReadr[N];
77209 return pNew;
77213 ** Free the MergeEngine object passed as the only argument.
77215 static void vdbeMergeEngineFree(MergeEngine *pMerger){
77216 int i;
77217 if( pMerger ){
77218 for(i=0; i<pMerger->nTree; i++){
77219 vdbePmaReaderClear(&pMerger->aReadr[i]);
77222 sqlite3_free(pMerger);
77226 ** Free all resources associated with the IncrMerger object indicated by
77227 ** the first argument.
77229 static void vdbeIncrFree(IncrMerger *pIncr){
77230 if( pIncr ){
77231 #if SQLITE_MAX_WORKER_THREADS>0
77232 if( pIncr->bUseThread ){
77233 vdbeSorterJoinThread(pIncr->pTask);
77234 if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
77235 if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
77237 #endif
77238 vdbeMergeEngineFree(pIncr->pMerger);
77239 sqlite3_free(pIncr);
77244 ** Reset a sorting cursor back to its original empty state.
77246 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
77247 int i;
77248 (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
77249 assert( pSorter->bUseThreads || pSorter->pReader==0 );
77250 #if SQLITE_MAX_WORKER_THREADS>0
77251 if( pSorter->pReader ){
77252 vdbePmaReaderClear(pSorter->pReader);
77253 sqlite3DbFree(db, pSorter->pReader);
77254 pSorter->pReader = 0;
77256 #endif
77257 vdbeMergeEngineFree(pSorter->pMerger);
77258 pSorter->pMerger = 0;
77259 for(i=0; i<pSorter->nTask; i++){
77260 SortSubtask *pTask = &pSorter->aTask[i];
77261 vdbeSortSubtaskCleanup(db, pTask);
77263 if( pSorter->list.aMemory==0 ){
77264 vdbeSorterRecordFree(0, pSorter->list.pList);
77266 pSorter->list.pList = 0;
77267 pSorter->list.szPMA = 0;
77268 pSorter->bUsePMA = 0;
77269 pSorter->iMemory = 0;
77270 pSorter->mxKeysize = 0;
77271 sqlite3DbFree(db, pSorter->pUnpacked);
77272 pSorter->pUnpacked = 0;
77276 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
77278 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
77279 VdbeSorter *pSorter = pCsr->pSorter;
77280 if( pSorter ){
77281 sqlite3VdbeSorterReset(db, pSorter);
77282 sqlite3_free(pSorter->list.aMemory);
77283 sqlite3DbFree(db, pSorter);
77284 pCsr->pSorter = 0;
77288 #if SQLITE_MAX_MMAP_SIZE>0
77290 ** The first argument is a file-handle open on a temporary file. The file
77291 ** is guaranteed to be nByte bytes or smaller in size. This function
77292 ** attempts to extend the file to nByte bytes in size and to ensure that
77293 ** the VFS has memory mapped it.
77295 ** Whether or not the file does end up memory mapped of course depends on
77296 ** the specific VFS implementation.
77298 static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
77299 if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
77300 int rc = sqlite3OsTruncate(pFd, nByte);
77301 if( rc==SQLITE_OK ){
77302 void *p = 0;
77303 sqlite3OsFetch(pFd, 0, (int)nByte, &p);
77304 sqlite3OsUnfetch(pFd, 0, p);
77308 #else
77309 # define vdbeSorterExtendFile(x,y,z)
77310 #endif
77313 ** Allocate space for a file-handle and open a temporary file. If successful,
77314 ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
77315 ** Otherwise, set *ppFd to 0 and return an SQLite error code.
77317 static int vdbeSorterOpenTempFile(
77318 sqlite3 *db, /* Database handle doing sort */
77319 i64 nExtend, /* Attempt to extend file to this size */
77320 sqlite3_file **ppFd
77322 int rc;
77323 rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
77324 SQLITE_OPEN_TEMP_JOURNAL |
77325 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
77326 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
77328 if( rc==SQLITE_OK ){
77329 i64 max = SQLITE_MAX_MMAP_SIZE;
77330 sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
77331 if( nExtend>0 ){
77332 vdbeSorterExtendFile(db, *ppFd, nExtend);
77335 return rc;
77339 ** If it has not already been allocated, allocate the UnpackedRecord
77340 ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
77341 ** if no allocation was required), or SQLITE_NOMEM otherwise.
77343 static int vdbeSortAllocUnpacked(SortSubtask *pTask){
77344 if( pTask->pUnpacked==0 ){
77345 char *pFree;
77346 pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
77347 pTask->pSorter->pKeyInfo, 0, 0, &pFree
77349 assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
77350 if( pFree==0 ) return SQLITE_NOMEM;
77351 pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
77352 pTask->pUnpacked->errCode = 0;
77354 return SQLITE_OK;
77359 ** Merge the two sorted lists p1 and p2 into a single list.
77360 ** Set *ppOut to the head of the new list.
77362 static void vdbeSorterMerge(
77363 SortSubtask *pTask, /* Calling thread context */
77364 SorterRecord *p1, /* First list to merge */
77365 SorterRecord *p2, /* Second list to merge */
77366 SorterRecord **ppOut /* OUT: Head of merged list */
77368 SorterRecord *pFinal = 0;
77369 SorterRecord **pp = &pFinal;
77370 void *pVal2 = p2 ? SRVAL(p2) : 0;
77372 while( p1 && p2 ){
77373 int res;
77374 res = vdbeSorterCompare(pTask, SRVAL(p1), p1->nVal, pVal2, p2->nVal);
77375 if( res<=0 ){
77376 *pp = p1;
77377 pp = &p1->u.pNext;
77378 p1 = p1->u.pNext;
77379 pVal2 = 0;
77380 }else{
77381 *pp = p2;
77382 pp = &p2->u.pNext;
77383 p2 = p2->u.pNext;
77384 if( p2==0 ) break;
77385 pVal2 = SRVAL(p2);
77388 *pp = p1 ? p1 : p2;
77389 *ppOut = pFinal;
77393 ** Sort the linked list of records headed at pTask->pList. Return
77394 ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
77395 ** an error occurs.
77397 static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
77398 int i;
77399 SorterRecord **aSlot;
77400 SorterRecord *p;
77401 int rc;
77403 rc = vdbeSortAllocUnpacked(pTask);
77404 if( rc!=SQLITE_OK ) return rc;
77406 aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
77407 if( !aSlot ){
77408 return SQLITE_NOMEM;
77411 p = pList->pList;
77412 while( p ){
77413 SorterRecord *pNext;
77414 if( pList->aMemory ){
77415 if( (u8*)p==pList->aMemory ){
77416 pNext = 0;
77417 }else{
77418 assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
77419 pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
77421 }else{
77422 pNext = p->u.pNext;
77425 p->u.pNext = 0;
77426 for(i=0; aSlot[i]; i++){
77427 vdbeSorterMerge(pTask, p, aSlot[i], &p);
77428 aSlot[i] = 0;
77430 aSlot[i] = p;
77431 p = pNext;
77434 p = 0;
77435 for(i=0; i<64; i++){
77436 vdbeSorterMerge(pTask, p, aSlot[i], &p);
77438 pList->pList = p;
77440 sqlite3_free(aSlot);
77441 assert( pTask->pUnpacked->errCode==SQLITE_OK
77442 || pTask->pUnpacked->errCode==SQLITE_NOMEM
77444 return pTask->pUnpacked->errCode;
77448 ** Initialize a PMA-writer object.
77450 static void vdbePmaWriterInit(
77451 sqlite3_file *pFd, /* File handle to write to */
77452 PmaWriter *p, /* Object to populate */
77453 int nBuf, /* Buffer size */
77454 i64 iStart /* Offset of pFd to begin writing at */
77456 memset(p, 0, sizeof(PmaWriter));
77457 p->aBuffer = (u8*)sqlite3Malloc(nBuf);
77458 if( !p->aBuffer ){
77459 p->eFWErr = SQLITE_NOMEM;
77460 }else{
77461 p->iBufEnd = p->iBufStart = (iStart % nBuf);
77462 p->iWriteOff = iStart - p->iBufStart;
77463 p->nBuffer = nBuf;
77464 p->pFd = pFd;
77469 ** Write nData bytes of data to the PMA. Return SQLITE_OK
77470 ** if successful, or an SQLite error code if an error occurs.
77472 static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
77473 int nRem = nData;
77474 while( nRem>0 && p->eFWErr==0 ){
77475 int nCopy = nRem;
77476 if( nCopy>(p->nBuffer - p->iBufEnd) ){
77477 nCopy = p->nBuffer - p->iBufEnd;
77480 memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
77481 p->iBufEnd += nCopy;
77482 if( p->iBufEnd==p->nBuffer ){
77483 p->eFWErr = sqlite3OsWrite(p->pFd,
77484 &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
77485 p->iWriteOff + p->iBufStart
77487 p->iBufStart = p->iBufEnd = 0;
77488 p->iWriteOff += p->nBuffer;
77490 assert( p->iBufEnd<p->nBuffer );
77492 nRem -= nCopy;
77497 ** Flush any buffered data to disk and clean up the PMA-writer object.
77498 ** The results of using the PMA-writer after this call are undefined.
77499 ** Return SQLITE_OK if flushing the buffered data succeeds or is not
77500 ** required. Otherwise, return an SQLite error code.
77502 ** Before returning, set *piEof to the offset immediately following the
77503 ** last byte written to the file.
77505 static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
77506 int rc;
77507 if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
77508 p->eFWErr = sqlite3OsWrite(p->pFd,
77509 &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
77510 p->iWriteOff + p->iBufStart
77513 *piEof = (p->iWriteOff + p->iBufEnd);
77514 sqlite3_free(p->aBuffer);
77515 rc = p->eFWErr;
77516 memset(p, 0, sizeof(PmaWriter));
77517 return rc;
77521 ** Write value iVal encoded as a varint to the PMA. Return
77522 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
77524 static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
77525 int nByte;
77526 u8 aByte[10];
77527 nByte = sqlite3PutVarint(aByte, iVal);
77528 vdbePmaWriteBlob(p, aByte, nByte);
77532 ** Write the current contents of in-memory linked-list pList to a level-0
77533 ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
77534 ** successful, or an SQLite error code otherwise.
77536 ** The format of a PMA is:
77538 ** * A varint. This varint contains the total number of bytes of content
77539 ** in the PMA (not including the varint itself).
77541 ** * One or more records packed end-to-end in order of ascending keys.
77542 ** Each record consists of a varint followed by a blob of data (the
77543 ** key). The varint is the number of bytes in the blob of data.
77545 static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
77546 sqlite3 *db = pTask->pSorter->db;
77547 int rc = SQLITE_OK; /* Return code */
77548 PmaWriter writer; /* Object used to write to the file */
77550 #ifdef SQLITE_DEBUG
77551 /* Set iSz to the expected size of file pTask->file after writing the PMA.
77552 ** This is used by an assert() statement at the end of this function. */
77553 i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
77554 #endif
77556 vdbeSorterWorkDebug(pTask, "enter");
77557 memset(&writer, 0, sizeof(PmaWriter));
77558 assert( pList->szPMA>0 );
77560 /* If the first temporary PMA file has not been opened, open it now. */
77561 if( pTask->file.pFd==0 ){
77562 rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
77563 assert( rc!=SQLITE_OK || pTask->file.pFd );
77564 assert( pTask->file.iEof==0 );
77565 assert( pTask->nPMA==0 );
77568 /* Try to get the file to memory map */
77569 if( rc==SQLITE_OK ){
77570 vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
77573 /* Sort the list */
77574 if( rc==SQLITE_OK ){
77575 rc = vdbeSorterSort(pTask, pList);
77578 if( rc==SQLITE_OK ){
77579 SorterRecord *p;
77580 SorterRecord *pNext = 0;
77582 vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
77583 pTask->file.iEof);
77584 pTask->nPMA++;
77585 vdbePmaWriteVarint(&writer, pList->szPMA);
77586 for(p=pList->pList; p; p=pNext){
77587 pNext = p->u.pNext;
77588 vdbePmaWriteVarint(&writer, p->nVal);
77589 vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
77590 if( pList->aMemory==0 ) sqlite3_free(p);
77592 pList->pList = p;
77593 rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
77596 vdbeSorterWorkDebug(pTask, "exit");
77597 assert( rc!=SQLITE_OK || pList->pList==0 );
77598 assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
77599 return rc;
77603 ** Advance the MergeEngine to its next entry.
77604 ** Set *pbEof to true there is no next entry because
77605 ** the MergeEngine has reached the end of all its inputs.
77607 ** Return SQLITE_OK if successful or an error code if an error occurs.
77609 static int vdbeMergeEngineStep(
77610 MergeEngine *pMerger, /* The merge engine to advance to the next row */
77611 int *pbEof /* Set TRUE at EOF. Set false for more content */
77613 int rc;
77614 int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
77615 SortSubtask *pTask = pMerger->pTask;
77617 /* Advance the current PmaReader */
77618 rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
77620 /* Update contents of aTree[] */
77621 if( rc==SQLITE_OK ){
77622 int i; /* Index of aTree[] to recalculate */
77623 PmaReader *pReadr1; /* First PmaReader to compare */
77624 PmaReader *pReadr2; /* Second PmaReader to compare */
77625 u8 *pKey2; /* To pReadr2->aKey, or 0 if record cached */
77627 /* Find the first two PmaReaders to compare. The one that was just
77628 ** advanced (iPrev) and the one next to it in the array. */
77629 pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
77630 pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
77631 pKey2 = pReadr2->aKey;
77633 for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
77634 /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
77635 int iRes;
77636 if( pReadr1->pFd==0 ){
77637 iRes = +1;
77638 }else if( pReadr2->pFd==0 ){
77639 iRes = -1;
77640 }else{
77641 iRes = vdbeSorterCompare(pTask,
77642 pReadr1->aKey, pReadr1->nKey, pKey2, pReadr2->nKey
77646 /* If pReadr1 contained the smaller value, set aTree[i] to its index.
77647 ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
77648 ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
77649 ** pKey2 to point to the record belonging to pReadr2.
77651 ** Alternatively, if pReadr2 contains the smaller of the two values,
77652 ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
77653 ** was actually called above, then pTask->pUnpacked now contains
77654 ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
77655 ** vdbeSorterCompare() from decoding pReadr2 again.
77657 ** If the two values were equal, then the value from the oldest
77658 ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
77659 ** is sorted from oldest to newest, so pReadr1 contains older values
77660 ** than pReadr2 iff (pReadr1<pReadr2). */
77661 if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
77662 pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
77663 pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
77664 pKey2 = pReadr2->aKey;
77665 }else{
77666 if( pReadr1->pFd ) pKey2 = 0;
77667 pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
77668 pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
77671 *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
77674 return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
77677 #if SQLITE_MAX_WORKER_THREADS>0
77679 ** The main routine for background threads that write level-0 PMAs.
77681 static void *vdbeSorterFlushThread(void *pCtx){
77682 SortSubtask *pTask = (SortSubtask*)pCtx;
77683 int rc; /* Return code */
77684 assert( pTask->bDone==0 );
77685 rc = vdbeSorterListToPMA(pTask, &pTask->list);
77686 pTask->bDone = 1;
77687 return SQLITE_INT_TO_PTR(rc);
77689 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
77692 ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
77693 ** using a background thread.
77695 static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
77696 #if SQLITE_MAX_WORKER_THREADS==0
77697 pSorter->bUsePMA = 1;
77698 return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
77699 #else
77700 int rc = SQLITE_OK;
77701 int i;
77702 SortSubtask *pTask = 0; /* Thread context used to create new PMA */
77703 int nWorker = (pSorter->nTask-1);
77705 /* Set the flag to indicate that at least one PMA has been written.
77706 ** Or will be, anyhow. */
77707 pSorter->bUsePMA = 1;
77709 /* Select a sub-task to sort and flush the current list of in-memory
77710 ** records to disk. If the sorter is running in multi-threaded mode,
77711 ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
77712 ** the background thread from a sub-tasks previous turn is still running,
77713 ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
77714 ** fall back to using the final sub-task. The first (pSorter->nTask-1)
77715 ** sub-tasks are prefered as they use background threads - the final
77716 ** sub-task uses the main thread. */
77717 for(i=0; i<nWorker; i++){
77718 int iTest = (pSorter->iPrev + i + 1) % nWorker;
77719 pTask = &pSorter->aTask[iTest];
77720 if( pTask->bDone ){
77721 rc = vdbeSorterJoinThread(pTask);
77723 if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
77726 if( rc==SQLITE_OK ){
77727 if( i==nWorker ){
77728 /* Use the foreground thread for this operation */
77729 rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
77730 }else{
77731 /* Launch a background thread for this operation */
77732 u8 *aMem = pTask->list.aMemory;
77733 void *pCtx = (void*)pTask;
77735 assert( pTask->pThread==0 && pTask->bDone==0 );
77736 assert( pTask->list.pList==0 );
77737 assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
77739 pSorter->iPrev = (u8)(pTask - pSorter->aTask);
77740 pTask->list = pSorter->list;
77741 pSorter->list.pList = 0;
77742 pSorter->list.szPMA = 0;
77743 if( aMem ){
77744 pSorter->list.aMemory = aMem;
77745 pSorter->nMemory = sqlite3MallocSize(aMem);
77746 }else if( pSorter->list.aMemory ){
77747 pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
77748 if( !pSorter->list.aMemory ) return SQLITE_NOMEM;
77751 rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
77755 return rc;
77756 #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
77760 ** Add a record to the sorter.
77762 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
77763 const VdbeCursor *pCsr, /* Sorter cursor */
77764 Mem *pVal /* Memory cell containing record */
77766 VdbeSorter *pSorter = pCsr->pSorter;
77767 int rc = SQLITE_OK; /* Return Code */
77768 SorterRecord *pNew; /* New list element */
77770 int bFlush; /* True to flush contents of memory to PMA */
77771 int nReq; /* Bytes of memory required */
77772 int nPMA; /* Bytes of PMA space required */
77774 assert( pSorter );
77776 /* Figure out whether or not the current contents of memory should be
77777 ** flushed to a PMA before continuing. If so, do so.
77779 ** If using the single large allocation mode (pSorter->aMemory!=0), then
77780 ** flush the contents of memory to a new PMA if (a) at least one value is
77781 ** already in memory and (b) the new value will not fit in memory.
77783 ** Or, if using separate allocations for each record, flush the contents
77784 ** of memory to a PMA if either of the following are true:
77786 ** * The total memory allocated for the in-memory list is greater
77787 ** than (page-size * cache-size), or
77789 ** * The total memory allocated for the in-memory list is greater
77790 ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
77792 nReq = pVal->n + sizeof(SorterRecord);
77793 nPMA = pVal->n + sqlite3VarintLen(pVal->n);
77794 if( pSorter->mxPmaSize ){
77795 if( pSorter->list.aMemory ){
77796 bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
77797 }else{
77798 bFlush = (
77799 (pSorter->list.szPMA > pSorter->mxPmaSize)
77800 || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
77803 if( bFlush ){
77804 rc = vdbeSorterFlushPMA(pSorter);
77805 pSorter->list.szPMA = 0;
77806 pSorter->iMemory = 0;
77807 assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
77811 pSorter->list.szPMA += nPMA;
77812 if( nPMA>pSorter->mxKeysize ){
77813 pSorter->mxKeysize = nPMA;
77816 if( pSorter->list.aMemory ){
77817 int nMin = pSorter->iMemory + nReq;
77819 if( nMin>pSorter->nMemory ){
77820 u8 *aNew;
77821 int nNew = pSorter->nMemory * 2;
77822 while( nNew < nMin ) nNew = nNew*2;
77823 if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
77824 if( nNew < nMin ) nNew = nMin;
77826 aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
77827 if( !aNew ) return SQLITE_NOMEM;
77828 pSorter->list.pList = (SorterRecord*)(
77829 aNew + ((u8*)pSorter->list.pList - pSorter->list.aMemory)
77831 pSorter->list.aMemory = aNew;
77832 pSorter->nMemory = nNew;
77835 pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
77836 pSorter->iMemory += ROUND8(nReq);
77837 pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
77838 }else{
77839 pNew = (SorterRecord *)sqlite3Malloc(nReq);
77840 if( pNew==0 ){
77841 return SQLITE_NOMEM;
77843 pNew->u.pNext = pSorter->list.pList;
77846 memcpy(SRVAL(pNew), pVal->z, pVal->n);
77847 pNew->nVal = pVal->n;
77848 pSorter->list.pList = pNew;
77850 return rc;
77854 ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
77855 ** of the data stored in aFile[1] is the same as that used by regular PMAs,
77856 ** except that the number-of-bytes varint is omitted from the start.
77858 static int vdbeIncrPopulate(IncrMerger *pIncr){
77859 int rc = SQLITE_OK;
77860 int rc2;
77861 i64 iStart = pIncr->iStartOff;
77862 SorterFile *pOut = &pIncr->aFile[1];
77863 SortSubtask *pTask = pIncr->pTask;
77864 MergeEngine *pMerger = pIncr->pMerger;
77865 PmaWriter writer;
77866 assert( pIncr->bEof==0 );
77868 vdbeSorterPopulateDebug(pTask, "enter");
77870 vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
77871 while( rc==SQLITE_OK ){
77872 int dummy;
77873 PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
77874 int nKey = pReader->nKey;
77875 i64 iEof = writer.iWriteOff + writer.iBufEnd;
77877 /* Check if the output file is full or if the input has been exhausted.
77878 ** In either case exit the loop. */
77879 if( pReader->pFd==0 ) break;
77880 if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
77882 /* Write the next key to the output. */
77883 vdbePmaWriteVarint(&writer, nKey);
77884 vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
77885 assert( pIncr->pMerger->pTask==pTask );
77886 rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
77889 rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
77890 if( rc==SQLITE_OK ) rc = rc2;
77891 vdbeSorterPopulateDebug(pTask, "exit");
77892 return rc;
77895 #if SQLITE_MAX_WORKER_THREADS>0
77897 ** The main routine for background threads that populate aFile[1] of
77898 ** multi-threaded IncrMerger objects.
77900 static void *vdbeIncrPopulateThread(void *pCtx){
77901 IncrMerger *pIncr = (IncrMerger*)pCtx;
77902 void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
77903 pIncr->pTask->bDone = 1;
77904 return pRet;
77908 ** Launch a background thread to populate aFile[1] of pIncr.
77910 static int vdbeIncrBgPopulate(IncrMerger *pIncr){
77911 void *p = (void*)pIncr;
77912 assert( pIncr->bUseThread );
77913 return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
77915 #endif
77918 ** This function is called when the PmaReader corresponding to pIncr has
77919 ** finished reading the contents of aFile[0]. Its purpose is to "refill"
77920 ** aFile[0] such that the PmaReader should start rereading it from the
77921 ** beginning.
77923 ** For single-threaded objects, this is accomplished by literally reading
77924 ** keys from pIncr->pMerger and repopulating aFile[0].
77926 ** For multi-threaded objects, all that is required is to wait until the
77927 ** background thread is finished (if it is not already) and then swap
77928 ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
77929 ** been exhausted, this function also launches a new background thread
77930 ** to populate the new aFile[1].
77932 ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
77934 static int vdbeIncrSwap(IncrMerger *pIncr){
77935 int rc = SQLITE_OK;
77937 #if SQLITE_MAX_WORKER_THREADS>0
77938 if( pIncr->bUseThread ){
77939 rc = vdbeSorterJoinThread(pIncr->pTask);
77941 if( rc==SQLITE_OK ){
77942 SorterFile f0 = pIncr->aFile[0];
77943 pIncr->aFile[0] = pIncr->aFile[1];
77944 pIncr->aFile[1] = f0;
77947 if( rc==SQLITE_OK ){
77948 if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
77949 pIncr->bEof = 1;
77950 }else{
77951 rc = vdbeIncrBgPopulate(pIncr);
77954 }else
77955 #endif
77957 rc = vdbeIncrPopulate(pIncr);
77958 pIncr->aFile[0] = pIncr->aFile[1];
77959 if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
77960 pIncr->bEof = 1;
77964 return rc;
77968 ** Allocate and return a new IncrMerger object to read data from pMerger.
77970 ** If an OOM condition is encountered, return NULL. In this case free the
77971 ** pMerger argument before returning.
77973 static int vdbeIncrMergerNew(
77974 SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
77975 MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
77976 IncrMerger **ppOut /* Write the new IncrMerger here */
77978 int rc = SQLITE_OK;
77979 IncrMerger *pIncr = *ppOut = (IncrMerger*)
77980 (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
77981 if( pIncr ){
77982 pIncr->pMerger = pMerger;
77983 pIncr->pTask = pTask;
77984 pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
77985 pTask->file2.iEof += pIncr->mxSz;
77986 }else{
77987 vdbeMergeEngineFree(pMerger);
77988 rc = SQLITE_NOMEM;
77990 return rc;
77993 #if SQLITE_MAX_WORKER_THREADS>0
77995 ** Set the "use-threads" flag on object pIncr.
77997 static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
77998 pIncr->bUseThread = 1;
77999 pIncr->pTask->file2.iEof -= pIncr->mxSz;
78001 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
78006 ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
78007 ** two PmaReaders that feed that entry. Neither of the PmaReaders
78008 ** are advanced. This routine merely does the comparison.
78010 static void vdbeMergeEngineCompare(
78011 MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
78012 int iOut /* Store the result in pMerger->aTree[iOut] */
78014 int i1;
78015 int i2;
78016 int iRes;
78017 PmaReader *p1;
78018 PmaReader *p2;
78020 assert( iOut<pMerger->nTree && iOut>0 );
78022 if( iOut>=(pMerger->nTree/2) ){
78023 i1 = (iOut - pMerger->nTree/2) * 2;
78024 i2 = i1 + 1;
78025 }else{
78026 i1 = pMerger->aTree[iOut*2];
78027 i2 = pMerger->aTree[iOut*2+1];
78030 p1 = &pMerger->aReadr[i1];
78031 p2 = &pMerger->aReadr[i2];
78033 if( p1->pFd==0 ){
78034 iRes = i2;
78035 }else if( p2->pFd==0 ){
78036 iRes = i1;
78037 }else{
78038 int res;
78039 assert( pMerger->pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
78040 res = vdbeSorterCompare(
78041 pMerger->pTask, p1->aKey, p1->nKey, p2->aKey, p2->nKey
78043 if( res<=0 ){
78044 iRes = i1;
78045 }else{
78046 iRes = i2;
78050 pMerger->aTree[iOut] = iRes;
78054 ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
78055 ** and vdbePmaReaderIncrMergeInit().
78057 ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
78058 ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
78059 ** when there exists one or more separate worker threads.
78061 #define INCRINIT_NORMAL 0
78062 #define INCRINIT_TASK 1
78063 #define INCRINIT_ROOT 2
78065 /* Forward reference.
78066 ** The vdbeIncrMergeInit() and vdbePmaReaderIncrMergeInit() routines call each
78067 ** other (when building a merge tree).
78069 static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode);
78072 ** Initialize the MergeEngine object passed as the second argument. Once this
78073 ** function returns, the first key of merged data may be read from the
78074 ** MergeEngine object in the usual fashion.
78076 ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
78077 ** objects attached to the PmaReader objects that the merger reads from have
78078 ** already been populated, but that they have not yet populated aFile[0] and
78079 ** set the PmaReader objects up to read from it. In this case all that is
78080 ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
78081 ** its first key.
78083 ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
78084 ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
78085 ** to pMerger.
78087 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
78089 static int vdbeMergeEngineInit(
78090 SortSubtask *pTask, /* Thread that will run pMerger */
78091 MergeEngine *pMerger, /* MergeEngine to initialize */
78092 int eMode /* One of the INCRINIT_XXX constants */
78094 int rc = SQLITE_OK; /* Return code */
78095 int i; /* For looping over PmaReader objects */
78096 int nTree = pMerger->nTree;
78098 /* eMode is always INCRINIT_NORMAL in single-threaded mode */
78099 assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
78101 /* Verify that the MergeEngine is assigned to a single thread */
78102 assert( pMerger->pTask==0 );
78103 pMerger->pTask = pTask;
78105 for(i=0; i<nTree; i++){
78106 if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
78107 /* PmaReaders should be normally initialized in order, as if they are
78108 ** reading from the same temp file this makes for more linear file IO.
78109 ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
78110 ** in use it will block the vdbePmaReaderNext() call while it uses
78111 ** the main thread to fill its buffer. So calling PmaReaderNext()
78112 ** on this PmaReader before any of the multi-threaded PmaReaders takes
78113 ** better advantage of multi-processor hardware. */
78114 rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
78115 }else{
78116 rc = vdbePmaReaderIncrMergeInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
78118 if( rc!=SQLITE_OK ) return rc;
78121 for(i=pMerger->nTree-1; i>0; i--){
78122 vdbeMergeEngineCompare(pMerger, i);
78124 return pTask->pUnpacked->errCode;
78128 ** Initialize the IncrMerge field of a PmaReader.
78130 ** If the PmaReader passed as the first argument is not an incremental-reader
78131 ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it serves
78132 ** to open and/or initialize the temp file related fields of the IncrMerge
78133 ** object at (pReadr->pIncr).
78135 ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
78136 ** in the sub-tree headed by pReadr are also initialized. Data is then loaded
78137 ** into the buffers belonging to pReadr and it is set to
78138 ** point to the first key in its range.
78140 ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
78141 ** to be a multi-threaded PmaReader and this function is being called in a
78142 ** background thread. In this case all PmaReaders in the sub-tree are
78143 ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
78144 ** pReadr is populated. However, pReadr itself is not set up to point
78145 ** to its first key. A call to vdbePmaReaderNext() is still required to do
78146 ** that.
78148 ** The reason this function does not call vdbePmaReaderNext() immediately
78149 ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
78150 ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
78151 ** this entire function is being run by thread (pTask->thread), that will
78152 ** lead to the current background thread attempting to join itself.
78154 ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
78155 ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
78156 ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
78157 ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
78158 ** the current PmaReader set to point to the first key in its range.
78160 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
78162 static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
78163 int rc = SQLITE_OK;
78164 IncrMerger *pIncr = pReadr->pIncr;
78166 /* eMode is always INCRINIT_NORMAL in single-threaded mode */
78167 assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
78169 if( pIncr ){
78170 SortSubtask *pTask = pIncr->pTask;
78171 sqlite3 *db = pTask->pSorter->db;
78173 rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
78175 /* Set up the required files for pIncr. A multi-theaded IncrMerge object
78176 ** requires two temp files to itself, whereas a single-threaded object
78177 ** only requires a region of pTask->file2. */
78178 if( rc==SQLITE_OK ){
78179 int mxSz = pIncr->mxSz;
78180 #if SQLITE_MAX_WORKER_THREADS>0
78181 if( pIncr->bUseThread ){
78182 rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
78183 if( rc==SQLITE_OK ){
78184 rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
78186 }else
78187 #endif
78188 /*if( !pIncr->bUseThread )*/{
78189 if( pTask->file2.pFd==0 ){
78190 assert( pTask->file2.iEof>0 );
78191 rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
78192 pTask->file2.iEof = 0;
78194 if( rc==SQLITE_OK ){
78195 pIncr->aFile[1].pFd = pTask->file2.pFd;
78196 pIncr->iStartOff = pTask->file2.iEof;
78197 pTask->file2.iEof += mxSz;
78202 #if SQLITE_MAX_WORKER_THREADS>0
78203 if( rc==SQLITE_OK && pIncr->bUseThread ){
78204 /* Use the current thread to populate aFile[1], even though this
78205 ** PmaReader is multi-threaded. The reason being that this function
78206 ** is already running in background thread pIncr->pTask->thread. */
78207 assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
78208 rc = vdbeIncrPopulate(pIncr);
78210 #endif
78212 if( rc==SQLITE_OK
78213 && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK)
78215 rc = vdbePmaReaderNext(pReadr);
78218 return rc;
78221 #if SQLITE_MAX_WORKER_THREADS>0
78223 ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
78224 ** background threads.
78226 static void *vdbePmaReaderBgInit(void *pCtx){
78227 PmaReader *pReader = (PmaReader*)pCtx;
78228 void *pRet = SQLITE_INT_TO_PTR(
78229 vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
78231 pReader->pIncr->pTask->bDone = 1;
78232 return pRet;
78236 ** Use a background thread to invoke vdbePmaReaderIncrMergeInit(INCRINIT_TASK)
78237 ** on the PmaReader object passed as the first argument.
78239 ** This call will initialize the various fields of the pReadr->pIncr
78240 ** structure and, if it is a multi-threaded IncrMerger, launch a
78241 ** background thread to populate aFile[1].
78243 static int vdbePmaReaderBgIncrInit(PmaReader *pReadr){
78244 void *pCtx = (void*)pReadr;
78245 return vdbeSorterCreateThread(pReadr->pIncr->pTask, vdbePmaReaderBgInit, pCtx);
78247 #endif
78250 ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
78251 ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
78252 ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
78253 ** to NULL and return an SQLite error code.
78255 ** When this function is called, *piOffset is set to the offset of the
78256 ** first PMA to read from pTask->file. Assuming no error occurs, it is
78257 ** set to the offset immediately following the last byte of the last
78258 ** PMA before returning. If an error does occur, then the final value of
78259 ** *piOffset is undefined.
78261 static int vdbeMergeEngineLevel0(
78262 SortSubtask *pTask, /* Sorter task to read from */
78263 int nPMA, /* Number of PMAs to read */
78264 i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
78265 MergeEngine **ppOut /* OUT: New merge-engine */
78267 MergeEngine *pNew; /* Merge engine to return */
78268 i64 iOff = *piOffset;
78269 int i;
78270 int rc = SQLITE_OK;
78272 *ppOut = pNew = vdbeMergeEngineNew(nPMA);
78273 if( pNew==0 ) rc = SQLITE_NOMEM;
78275 for(i=0; i<nPMA && rc==SQLITE_OK; i++){
78276 i64 nDummy;
78277 PmaReader *pReadr = &pNew->aReadr[i];
78278 rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
78279 iOff = pReadr->iEof;
78282 if( rc!=SQLITE_OK ){
78283 vdbeMergeEngineFree(pNew);
78284 *ppOut = 0;
78286 *piOffset = iOff;
78287 return rc;
78291 ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
78292 ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
78294 ** i.e.
78296 ** nPMA<=16 -> TreeDepth() == 0
78297 ** nPMA<=256 -> TreeDepth() == 1
78298 ** nPMA<=65536 -> TreeDepth() == 2
78300 static int vdbeSorterTreeDepth(int nPMA){
78301 int nDepth = 0;
78302 i64 nDiv = SORTER_MAX_MERGE_COUNT;
78303 while( nDiv < (i64)nPMA ){
78304 nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
78305 nDepth++;
78307 return nDepth;
78311 ** pRoot is the root of an incremental merge-tree with depth nDepth (according
78312 ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
78313 ** tree, counting from zero. This function adds pLeaf to the tree.
78315 ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
78316 ** code is returned and pLeaf is freed.
78318 static int vdbeSorterAddToTree(
78319 SortSubtask *pTask, /* Task context */
78320 int nDepth, /* Depth of tree according to TreeDepth() */
78321 int iSeq, /* Sequence number of leaf within tree */
78322 MergeEngine *pRoot, /* Root of tree */
78323 MergeEngine *pLeaf /* Leaf to add to tree */
78325 int rc = SQLITE_OK;
78326 int nDiv = 1;
78327 int i;
78328 MergeEngine *p = pRoot;
78329 IncrMerger *pIncr;
78331 rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
78333 for(i=1; i<nDepth; i++){
78334 nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
78337 for(i=1; i<nDepth && rc==SQLITE_OK; i++){
78338 int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
78339 PmaReader *pReadr = &p->aReadr[iIter];
78341 if( pReadr->pIncr==0 ){
78342 MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
78343 if( pNew==0 ){
78344 rc = SQLITE_NOMEM;
78345 }else{
78346 rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
78349 if( rc==SQLITE_OK ){
78350 p = pReadr->pIncr->pMerger;
78351 nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
78355 if( rc==SQLITE_OK ){
78356 p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
78357 }else{
78358 vdbeIncrFree(pIncr);
78360 return rc;
78364 ** This function is called as part of a SorterRewind() operation on a sorter
78365 ** that has already written two or more level-0 PMAs to one or more temp
78366 ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
78367 ** can be used to incrementally merge all PMAs on disk.
78369 ** If successful, SQLITE_OK is returned and *ppOut set to point to the
78370 ** MergeEngine object at the root of the tree before returning. Or, if an
78371 ** error occurs, an SQLite error code is returned and the final value
78372 ** of *ppOut is undefined.
78374 static int vdbeSorterMergeTreeBuild(
78375 VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
78376 MergeEngine **ppOut /* Write the MergeEngine here */
78378 MergeEngine *pMain = 0;
78379 int rc = SQLITE_OK;
78380 int iTask;
78382 #if SQLITE_MAX_WORKER_THREADS>0
78383 /* If the sorter uses more than one task, then create the top-level
78384 ** MergeEngine here. This MergeEngine will read data from exactly
78385 ** one PmaReader per sub-task. */
78386 assert( pSorter->bUseThreads || pSorter->nTask==1 );
78387 if( pSorter->nTask>1 ){
78388 pMain = vdbeMergeEngineNew(pSorter->nTask);
78389 if( pMain==0 ) rc = SQLITE_NOMEM;
78391 #endif
78393 for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
78394 SortSubtask *pTask = &pSorter->aTask[iTask];
78395 assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
78396 if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
78397 MergeEngine *pRoot = 0; /* Root node of tree for this task */
78398 int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
78399 i64 iReadOff = 0;
78401 if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
78402 rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
78403 }else{
78404 int i;
78405 int iSeq = 0;
78406 pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
78407 if( pRoot==0 ) rc = SQLITE_NOMEM;
78408 for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
78409 MergeEngine *pMerger = 0; /* New level-0 PMA merger */
78410 int nReader; /* Number of level-0 PMAs to merge */
78412 nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
78413 rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
78414 if( rc==SQLITE_OK ){
78415 rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
78420 if( rc==SQLITE_OK ){
78421 #if SQLITE_MAX_WORKER_THREADS>0
78422 if( pMain!=0 ){
78423 rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
78424 }else
78425 #endif
78427 assert( pMain==0 );
78428 pMain = pRoot;
78430 }else{
78431 vdbeMergeEngineFree(pRoot);
78436 if( rc!=SQLITE_OK ){
78437 vdbeMergeEngineFree(pMain);
78438 pMain = 0;
78440 *ppOut = pMain;
78441 return rc;
78445 ** This function is called as part of an sqlite3VdbeSorterRewind() operation
78446 ** on a sorter that has written two or more PMAs to temporary files. It sets
78447 ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
78448 ** (for multi-threaded sorters) so that it can be used to iterate through
78449 ** all records stored in the sorter.
78451 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
78453 static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
78454 int rc; /* Return code */
78455 SortSubtask *pTask0 = &pSorter->aTask[0];
78456 MergeEngine *pMain = 0;
78457 #if SQLITE_MAX_WORKER_THREADS
78458 sqlite3 *db = pTask0->pSorter->db;
78459 #endif
78461 rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
78462 if( rc==SQLITE_OK ){
78463 #if SQLITE_MAX_WORKER_THREADS
78464 assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
78465 if( pSorter->bUseThreads ){
78466 int iTask;
78467 PmaReader *pReadr = 0;
78468 SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
78469 rc = vdbeSortAllocUnpacked(pLast);
78470 if( rc==SQLITE_OK ){
78471 pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
78472 pSorter->pReader = pReadr;
78473 if( pReadr==0 ) rc = SQLITE_NOMEM;
78475 if( rc==SQLITE_OK ){
78476 rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
78477 if( rc==SQLITE_OK ){
78478 vdbeIncrMergerSetThreads(pReadr->pIncr);
78479 for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
78480 IncrMerger *pIncr;
78481 if( (pIncr = pMain->aReadr[iTask].pIncr) ){
78482 vdbeIncrMergerSetThreads(pIncr);
78483 assert( pIncr->pTask!=pLast );
78486 for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
78487 PmaReader *p = &pMain->aReadr[iTask];
78488 assert( p->pIncr==0 || p->pIncr->pTask==&pSorter->aTask[iTask] );
78489 if( p->pIncr ){
78490 if( iTask==pSorter->nTask-1 ){
78491 rc = vdbePmaReaderIncrMergeInit(p, INCRINIT_TASK);
78492 }else{
78493 rc = vdbePmaReaderBgIncrInit(p);
78498 pMain = 0;
78500 if( rc==SQLITE_OK ){
78501 rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
78503 }else
78504 #endif
78506 rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
78507 pSorter->pMerger = pMain;
78508 pMain = 0;
78512 if( rc!=SQLITE_OK ){
78513 vdbeMergeEngineFree(pMain);
78515 return rc;
78520 ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
78521 ** this function is called to prepare for iterating through the records
78522 ** in sorted order.
78524 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
78525 VdbeSorter *pSorter = pCsr->pSorter;
78526 int rc = SQLITE_OK; /* Return code */
78528 assert( pSorter );
78530 /* If no data has been written to disk, then do not do so now. Instead,
78531 ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
78532 ** from the in-memory list. */
78533 if( pSorter->bUsePMA==0 ){
78534 if( pSorter->list.pList ){
78535 *pbEof = 0;
78536 rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
78537 }else{
78538 *pbEof = 1;
78540 return rc;
78543 /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
78544 ** function flushes the contents of memory to disk, it immediately always
78545 ** creates a new list consisting of a single key immediately afterwards.
78546 ** So the list is never empty at this point. */
78547 assert( pSorter->list.pList );
78548 rc = vdbeSorterFlushPMA(pSorter);
78550 /* Join all threads */
78551 rc = vdbeSorterJoinAll(pSorter, rc);
78553 vdbeSorterRewindDebug("rewind");
78555 /* Assuming no errors have occurred, set up a merger structure to
78556 ** incrementally read and merge all remaining PMAs. */
78557 assert( pSorter->pReader==0 );
78558 if( rc==SQLITE_OK ){
78559 rc = vdbeSorterSetupMerge(pSorter);
78560 *pbEof = 0;
78563 vdbeSorterRewindDebug("rewinddone");
78564 return rc;
78568 ** Advance to the next element in the sorter.
78570 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
78571 VdbeSorter *pSorter = pCsr->pSorter;
78572 int rc; /* Return code */
78574 assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
78575 if( pSorter->bUsePMA ){
78576 assert( pSorter->pReader==0 || pSorter->pMerger==0 );
78577 assert( pSorter->bUseThreads==0 || pSorter->pReader );
78578 assert( pSorter->bUseThreads==1 || pSorter->pMerger );
78579 #if SQLITE_MAX_WORKER_THREADS>0
78580 if( pSorter->bUseThreads ){
78581 rc = vdbePmaReaderNext(pSorter->pReader);
78582 *pbEof = (pSorter->pReader->pFd==0);
78583 }else
78584 #endif
78585 /*if( !pSorter->bUseThreads )*/ {
78586 assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
78587 rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
78589 }else{
78590 SorterRecord *pFree = pSorter->list.pList;
78591 pSorter->list.pList = pFree->u.pNext;
78592 pFree->u.pNext = 0;
78593 if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
78594 *pbEof = !pSorter->list.pList;
78595 rc = SQLITE_OK;
78597 return rc;
78601 ** Return a pointer to a buffer owned by the sorter that contains the
78602 ** current key.
78604 static void *vdbeSorterRowkey(
78605 const VdbeSorter *pSorter, /* Sorter object */
78606 int *pnKey /* OUT: Size of current key in bytes */
78608 void *pKey;
78609 if( pSorter->bUsePMA ){
78610 PmaReader *pReader;
78611 #if SQLITE_MAX_WORKER_THREADS>0
78612 if( pSorter->bUseThreads ){
78613 pReader = pSorter->pReader;
78614 }else
78615 #endif
78616 /*if( !pSorter->bUseThreads )*/{
78617 pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
78619 *pnKey = pReader->nKey;
78620 pKey = pReader->aKey;
78621 }else{
78622 *pnKey = pSorter->list.pList->nVal;
78623 pKey = SRVAL(pSorter->list.pList);
78625 return pKey;
78629 ** Copy the current sorter key into the memory cell pOut.
78631 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
78632 VdbeSorter *pSorter = pCsr->pSorter;
78633 void *pKey; int nKey; /* Sorter key to copy into pOut */
78635 pKey = vdbeSorterRowkey(pSorter, &nKey);
78636 if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
78637 return SQLITE_NOMEM;
78639 pOut->n = nKey;
78640 MemSetTypeFlag(pOut, MEM_Blob);
78641 memcpy(pOut->z, pKey, nKey);
78643 return SQLITE_OK;
78647 ** Compare the key in memory cell pVal with the key that the sorter cursor
78648 ** passed as the first argument currently points to. For the purposes of
78649 ** the comparison, ignore the rowid field at the end of each record.
78651 ** If the sorter cursor key contains any NULL values, consider it to be
78652 ** less than pVal. Even if pVal also contains NULL values.
78654 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
78655 ** Otherwise, set *pRes to a negative, zero or positive value if the
78656 ** key in pVal is smaller than, equal to or larger than the current sorter
78657 ** key.
78659 ** This routine forms the core of the OP_SorterCompare opcode, which in
78660 ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
78662 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
78663 const VdbeCursor *pCsr, /* Sorter cursor */
78664 Mem *pVal, /* Value to compare to current sorter key */
78665 int nKeyCol, /* Compare this many columns */
78666 int *pRes /* OUT: Result of comparison */
78668 VdbeSorter *pSorter = pCsr->pSorter;
78669 UnpackedRecord *r2 = pSorter->pUnpacked;
78670 KeyInfo *pKeyInfo = pCsr->pKeyInfo;
78671 int i;
78672 void *pKey; int nKey; /* Sorter key to compare pVal with */
78674 if( r2==0 ){
78675 char *p;
78676 r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
78677 assert( pSorter->pUnpacked==(UnpackedRecord*)p );
78678 if( r2==0 ) return SQLITE_NOMEM;
78679 r2->nField = nKeyCol;
78681 assert( r2->nField==nKeyCol );
78683 pKey = vdbeSorterRowkey(pSorter, &nKey);
78684 sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
78685 for(i=0; i<nKeyCol; i++){
78686 if( r2->aMem[i].flags & MEM_Null ){
78687 *pRes = -1;
78688 return SQLITE_OK;
78692 *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
78693 return SQLITE_OK;
78696 /************** End of vdbesort.c ********************************************/
78697 /************** Begin file journal.c *****************************************/
78699 ** 2007 August 22
78701 ** The author disclaims copyright to this source code. In place of
78702 ** a legal notice, here is a blessing:
78704 ** May you do good and not evil.
78705 ** May you find forgiveness for yourself and forgive others.
78706 ** May you share freely, never taking more than you give.
78708 *************************************************************************
78710 ** This file implements a special kind of sqlite3_file object used
78711 ** by SQLite to create journal files if the atomic-write optimization
78712 ** is enabled.
78714 ** The distinctive characteristic of this sqlite3_file is that the
78715 ** actual on disk file is created lazily. When the file is created,
78716 ** the caller specifies a buffer size for an in-memory buffer to
78717 ** be used to service read() and write() requests. The actual file
78718 ** on disk is not created or populated until either:
78720 ** 1) The in-memory representation grows too large for the allocated
78721 ** buffer, or
78722 ** 2) The sqlite3JournalCreate() function is called.
78724 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
78728 ** A JournalFile object is a subclass of sqlite3_file used by
78729 ** as an open file handle for journal files.
78731 struct JournalFile {
78732 sqlite3_io_methods *pMethod; /* I/O methods on journal files */
78733 int nBuf; /* Size of zBuf[] in bytes */
78734 char *zBuf; /* Space to buffer journal writes */
78735 int iSize; /* Amount of zBuf[] currently used */
78736 int flags; /* xOpen flags */
78737 sqlite3_vfs *pVfs; /* The "real" underlying VFS */
78738 sqlite3_file *pReal; /* The "real" underlying file descriptor */
78739 const char *zJournal; /* Name of the journal file */
78741 typedef struct JournalFile JournalFile;
78744 ** If it does not already exists, create and populate the on-disk file
78745 ** for JournalFile p.
78747 static int createFile(JournalFile *p){
78748 int rc = SQLITE_OK;
78749 if( !p->pReal ){
78750 sqlite3_file *pReal = (sqlite3_file *)&p[1];
78751 rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
78752 if( rc==SQLITE_OK ){
78753 p->pReal = pReal;
78754 if( p->iSize>0 ){
78755 assert(p->iSize<=p->nBuf);
78756 rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
78758 if( rc!=SQLITE_OK ){
78759 /* If an error occurred while writing to the file, close it before
78760 ** returning. This way, SQLite uses the in-memory journal data to
78761 ** roll back changes made to the internal page-cache before this
78762 ** function was called. */
78763 sqlite3OsClose(pReal);
78764 p->pReal = 0;
78768 return rc;
78772 ** Close the file.
78774 static int jrnlClose(sqlite3_file *pJfd){
78775 JournalFile *p = (JournalFile *)pJfd;
78776 if( p->pReal ){
78777 sqlite3OsClose(p->pReal);
78779 sqlite3_free(p->zBuf);
78780 return SQLITE_OK;
78784 ** Read data from the file.
78786 static int jrnlRead(
78787 sqlite3_file *pJfd, /* The journal file from which to read */
78788 void *zBuf, /* Put the results here */
78789 int iAmt, /* Number of bytes to read */
78790 sqlite_int64 iOfst /* Begin reading at this offset */
78792 int rc = SQLITE_OK;
78793 JournalFile *p = (JournalFile *)pJfd;
78794 if( p->pReal ){
78795 rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
78796 }else if( (iAmt+iOfst)>p->iSize ){
78797 rc = SQLITE_IOERR_SHORT_READ;
78798 }else{
78799 memcpy(zBuf, &p->zBuf[iOfst], iAmt);
78801 return rc;
78805 ** Write data to the file.
78807 static int jrnlWrite(
78808 sqlite3_file *pJfd, /* The journal file into which to write */
78809 const void *zBuf, /* Take data to be written from here */
78810 int iAmt, /* Number of bytes to write */
78811 sqlite_int64 iOfst /* Begin writing at this offset into the file */
78813 int rc = SQLITE_OK;
78814 JournalFile *p = (JournalFile *)pJfd;
78815 if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
78816 rc = createFile(p);
78818 if( rc==SQLITE_OK ){
78819 if( p->pReal ){
78820 rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
78821 }else{
78822 memcpy(&p->zBuf[iOfst], zBuf, iAmt);
78823 if( p->iSize<(iOfst+iAmt) ){
78824 p->iSize = (iOfst+iAmt);
78828 return rc;
78832 ** Truncate the file.
78834 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
78835 int rc = SQLITE_OK;
78836 JournalFile *p = (JournalFile *)pJfd;
78837 if( p->pReal ){
78838 rc = sqlite3OsTruncate(p->pReal, size);
78839 }else if( size<p->iSize ){
78840 p->iSize = size;
78842 return rc;
78846 ** Sync the file.
78848 static int jrnlSync(sqlite3_file *pJfd, int flags){
78849 int rc;
78850 JournalFile *p = (JournalFile *)pJfd;
78851 if( p->pReal ){
78852 rc = sqlite3OsSync(p->pReal, flags);
78853 }else{
78854 rc = SQLITE_OK;
78856 return rc;
78860 ** Query the size of the file in bytes.
78862 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
78863 int rc = SQLITE_OK;
78864 JournalFile *p = (JournalFile *)pJfd;
78865 if( p->pReal ){
78866 rc = sqlite3OsFileSize(p->pReal, pSize);
78867 }else{
78868 *pSize = (sqlite_int64) p->iSize;
78870 return rc;
78874 ** Table of methods for JournalFile sqlite3_file object.
78876 static struct sqlite3_io_methods JournalFileMethods = {
78877 1, /* iVersion */
78878 jrnlClose, /* xClose */
78879 jrnlRead, /* xRead */
78880 jrnlWrite, /* xWrite */
78881 jrnlTruncate, /* xTruncate */
78882 jrnlSync, /* xSync */
78883 jrnlFileSize, /* xFileSize */
78884 0, /* xLock */
78885 0, /* xUnlock */
78886 0, /* xCheckReservedLock */
78887 0, /* xFileControl */
78888 0, /* xSectorSize */
78889 0, /* xDeviceCharacteristics */
78890 0, /* xShmMap */
78891 0, /* xShmLock */
78892 0, /* xShmBarrier */
78893 0 /* xShmUnmap */
78897 ** Open a journal file.
78899 SQLITE_PRIVATE int sqlite3JournalOpen(
78900 sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
78901 const char *zName, /* Name of the journal file */
78902 sqlite3_file *pJfd, /* Preallocated, blank file handle */
78903 int flags, /* Opening flags */
78904 int nBuf /* Bytes buffered before opening the file */
78906 JournalFile *p = (JournalFile *)pJfd;
78907 memset(p, 0, sqlite3JournalSize(pVfs));
78908 if( nBuf>0 ){
78909 p->zBuf = sqlite3MallocZero(nBuf);
78910 if( !p->zBuf ){
78911 return SQLITE_NOMEM;
78913 }else{
78914 return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
78916 p->pMethod = &JournalFileMethods;
78917 p->nBuf = nBuf;
78918 p->flags = flags;
78919 p->zJournal = zName;
78920 p->pVfs = pVfs;
78921 return SQLITE_OK;
78925 ** If the argument p points to a JournalFile structure, and the underlying
78926 ** file has not yet been created, create it now.
78928 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
78929 if( p->pMethods!=&JournalFileMethods ){
78930 return SQLITE_OK;
78932 return createFile((JournalFile *)p);
78936 ** The file-handle passed as the only argument is guaranteed to be an open
78937 ** file. It may or may not be of class JournalFile. If the file is a
78938 ** JournalFile, and the underlying file on disk has not yet been opened,
78939 ** return 0. Otherwise, return 1.
78941 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
78942 return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
78946 ** Return the number of bytes required to store a JournalFile that uses vfs
78947 ** pVfs to create the underlying on-disk files.
78949 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
78950 return (pVfs->szOsFile+sizeof(JournalFile));
78952 #endif
78954 /************** End of journal.c *********************************************/
78955 /************** Begin file memjournal.c **************************************/
78957 ** 2008 October 7
78959 ** The author disclaims copyright to this source code. In place of
78960 ** a legal notice, here is a blessing:
78962 ** May you do good and not evil.
78963 ** May you find forgiveness for yourself and forgive others.
78964 ** May you share freely, never taking more than you give.
78966 *************************************************************************
78968 ** This file contains code use to implement an in-memory rollback journal.
78969 ** The in-memory rollback journal is used to journal transactions for
78970 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
78973 /* Forward references to internal structures */
78974 typedef struct MemJournal MemJournal;
78975 typedef struct FilePoint FilePoint;
78976 typedef struct FileChunk FileChunk;
78978 /* Space to hold the rollback journal is allocated in increments of
78979 ** this many bytes.
78981 ** The size chosen is a little less than a power of two. That way,
78982 ** the FileChunk object will have a size that almost exactly fills
78983 ** a power-of-two allocation. This minimizes wasted space in power-of-two
78984 ** memory allocators.
78986 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
78989 ** The rollback journal is composed of a linked list of these structures.
78991 struct FileChunk {
78992 FileChunk *pNext; /* Next chunk in the journal */
78993 u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
78997 ** An instance of this object serves as a cursor into the rollback journal.
78998 ** The cursor can be either for reading or writing.
79000 struct FilePoint {
79001 sqlite3_int64 iOffset; /* Offset from the beginning of the file */
79002 FileChunk *pChunk; /* Specific chunk into which cursor points */
79006 ** This subclass is a subclass of sqlite3_file. Each open memory-journal
79007 ** is an instance of this class.
79009 struct MemJournal {
79010 sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
79011 FileChunk *pFirst; /* Head of in-memory chunk-list */
79012 FilePoint endpoint; /* Pointer to the end of the file */
79013 FilePoint readpoint; /* Pointer to the end of the last xRead() */
79017 ** Read data from the in-memory journal file. This is the implementation
79018 ** of the sqlite3_vfs.xRead method.
79020 static int memjrnlRead(
79021 sqlite3_file *pJfd, /* The journal file from which to read */
79022 void *zBuf, /* Put the results here */
79023 int iAmt, /* Number of bytes to read */
79024 sqlite_int64 iOfst /* Begin reading at this offset */
79026 MemJournal *p = (MemJournal *)pJfd;
79027 u8 *zOut = zBuf;
79028 int nRead = iAmt;
79029 int iChunkOffset;
79030 FileChunk *pChunk;
79032 /* SQLite never tries to read past the end of a rollback journal file */
79033 assert( iOfst+iAmt<=p->endpoint.iOffset );
79035 if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
79036 sqlite3_int64 iOff = 0;
79037 for(pChunk=p->pFirst;
79038 ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
79039 pChunk=pChunk->pNext
79041 iOff += JOURNAL_CHUNKSIZE;
79043 }else{
79044 pChunk = p->readpoint.pChunk;
79047 iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
79048 do {
79049 int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
79050 int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
79051 memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
79052 zOut += nCopy;
79053 nRead -= iSpace;
79054 iChunkOffset = 0;
79055 } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
79056 p->readpoint.iOffset = iOfst+iAmt;
79057 p->readpoint.pChunk = pChunk;
79059 return SQLITE_OK;
79063 ** Write data to the file.
79065 static int memjrnlWrite(
79066 sqlite3_file *pJfd, /* The journal file into which to write */
79067 const void *zBuf, /* Take data to be written from here */
79068 int iAmt, /* Number of bytes to write */
79069 sqlite_int64 iOfst /* Begin writing at this offset into the file */
79071 MemJournal *p = (MemJournal *)pJfd;
79072 int nWrite = iAmt;
79073 u8 *zWrite = (u8 *)zBuf;
79075 /* An in-memory journal file should only ever be appended to. Random
79076 ** access writes are not required by sqlite.
79078 assert( iOfst==p->endpoint.iOffset );
79079 UNUSED_PARAMETER(iOfst);
79081 while( nWrite>0 ){
79082 FileChunk *pChunk = p->endpoint.pChunk;
79083 int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
79084 int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
79086 if( iChunkOffset==0 ){
79087 /* New chunk is required to extend the file. */
79088 FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
79089 if( !pNew ){
79090 return SQLITE_IOERR_NOMEM;
79092 pNew->pNext = 0;
79093 if( pChunk ){
79094 assert( p->pFirst );
79095 pChunk->pNext = pNew;
79096 }else{
79097 assert( !p->pFirst );
79098 p->pFirst = pNew;
79100 p->endpoint.pChunk = pNew;
79103 memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
79104 zWrite += iSpace;
79105 nWrite -= iSpace;
79106 p->endpoint.iOffset += iSpace;
79109 return SQLITE_OK;
79113 ** Truncate the file.
79115 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
79116 MemJournal *p = (MemJournal *)pJfd;
79117 FileChunk *pChunk;
79118 assert(size==0);
79119 UNUSED_PARAMETER(size);
79120 pChunk = p->pFirst;
79121 while( pChunk ){
79122 FileChunk *pTmp = pChunk;
79123 pChunk = pChunk->pNext;
79124 sqlite3_free(pTmp);
79126 sqlite3MemJournalOpen(pJfd);
79127 return SQLITE_OK;
79131 ** Close the file.
79133 static int memjrnlClose(sqlite3_file *pJfd){
79134 memjrnlTruncate(pJfd, 0);
79135 return SQLITE_OK;
79140 ** Sync the file.
79142 ** Syncing an in-memory journal is a no-op. And, in fact, this routine
79143 ** is never called in a working implementation. This implementation
79144 ** exists purely as a contingency, in case some malfunction in some other
79145 ** part of SQLite causes Sync to be called by mistake.
79147 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
79148 UNUSED_PARAMETER2(NotUsed, NotUsed2);
79149 return SQLITE_OK;
79153 ** Query the size of the file in bytes.
79155 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
79156 MemJournal *p = (MemJournal *)pJfd;
79157 *pSize = (sqlite_int64) p->endpoint.iOffset;
79158 return SQLITE_OK;
79162 ** Table of methods for MemJournal sqlite3_file object.
79164 static const struct sqlite3_io_methods MemJournalMethods = {
79165 1, /* iVersion */
79166 memjrnlClose, /* xClose */
79167 memjrnlRead, /* xRead */
79168 memjrnlWrite, /* xWrite */
79169 memjrnlTruncate, /* xTruncate */
79170 memjrnlSync, /* xSync */
79171 memjrnlFileSize, /* xFileSize */
79172 0, /* xLock */
79173 0, /* xUnlock */
79174 0, /* xCheckReservedLock */
79175 0, /* xFileControl */
79176 0, /* xSectorSize */
79177 0, /* xDeviceCharacteristics */
79178 0, /* xShmMap */
79179 0, /* xShmLock */
79180 0, /* xShmBarrier */
79181 0, /* xShmUnmap */
79182 0, /* xFetch */
79183 0 /* xUnfetch */
79187 ** Open a journal file.
79189 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
79190 MemJournal *p = (MemJournal *)pJfd;
79191 assert( EIGHT_BYTE_ALIGNMENT(p) );
79192 memset(p, 0, sqlite3MemJournalSize());
79193 p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
79197 ** Return true if the file-handle passed as an argument is
79198 ** an in-memory journal
79200 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
79201 return pJfd->pMethods==&MemJournalMethods;
79205 ** Return the number of bytes required to store a MemJournal file descriptor.
79207 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
79208 return sizeof(MemJournal);
79211 /************** End of memjournal.c ******************************************/
79212 /************** Begin file walker.c ******************************************/
79214 ** 2008 August 16
79216 ** The author disclaims copyright to this source code. In place of
79217 ** a legal notice, here is a blessing:
79219 ** May you do good and not evil.
79220 ** May you find forgiveness for yourself and forgive others.
79221 ** May you share freely, never taking more than you give.
79223 *************************************************************************
79224 ** This file contains routines used for walking the parser tree for
79225 ** an SQL statement.
79227 /* #include <stdlib.h> */
79228 /* #include <string.h> */
79232 ** Walk an expression tree. Invoke the callback once for each node
79233 ** of the expression, while descending. (In other words, the callback
79234 ** is invoked before visiting children.)
79236 ** The return value from the callback should be one of the WRC_*
79237 ** constants to specify how to proceed with the walk.
79239 ** WRC_Continue Continue descending down the tree.
79241 ** WRC_Prune Do not descend into child nodes. But allow
79242 ** the walk to continue with sibling nodes.
79244 ** WRC_Abort Do no more callbacks. Unwind the stack and
79245 ** return the top-level walk call.
79247 ** The return value from this routine is WRC_Abort to abandon the tree walk
79248 ** and WRC_Continue to continue.
79250 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
79251 int rc;
79252 if( pExpr==0 ) return WRC_Continue;
79253 testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
79254 testcase( ExprHasProperty(pExpr, EP_Reduced) );
79255 rc = pWalker->xExprCallback(pWalker, pExpr);
79256 if( rc==WRC_Continue
79257 && !ExprHasProperty(pExpr,EP_TokenOnly) ){
79258 if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
79259 if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
79260 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
79261 if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
79262 }else{
79263 if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
79266 return rc & WRC_Abort;
79270 ** Call sqlite3WalkExpr() for every expression in list p or until
79271 ** an abort request is seen.
79273 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
79274 int i;
79275 struct ExprList_item *pItem;
79276 if( p ){
79277 for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
79278 if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
79281 return WRC_Continue;
79285 ** Walk all expressions associated with SELECT statement p. Do
79286 ** not invoke the SELECT callback on p, but do (of course) invoke
79287 ** any expr callbacks and SELECT callbacks that come from subqueries.
79288 ** Return WRC_Abort or WRC_Continue.
79290 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
79291 if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
79292 if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
79293 if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
79294 if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
79295 if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
79296 if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
79297 if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
79298 return WRC_Continue;
79302 ** Walk the parse trees associated with all subqueries in the
79303 ** FROM clause of SELECT statement p. Do not invoke the select
79304 ** callback on p, but do invoke it on each FROM clause subquery
79305 ** and on any subqueries further down in the tree. Return
79306 ** WRC_Abort or WRC_Continue;
79308 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
79309 SrcList *pSrc;
79310 int i;
79311 struct SrcList_item *pItem;
79313 pSrc = p->pSrc;
79314 if( ALWAYS(pSrc) ){
79315 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
79316 if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
79317 return WRC_Abort;
79321 return WRC_Continue;
79325 ** Call sqlite3WalkExpr() for every expression in Select statement p.
79326 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
79327 ** on the compound select chain, p->pPrior.
79329 ** If it is not NULL, the xSelectCallback() callback is invoked before
79330 ** the walk of the expressions and FROM clause. The xSelectCallback2()
79331 ** method, if it is not NULL, is invoked following the walk of the
79332 ** expressions and FROM clause.
79334 ** Return WRC_Continue under normal conditions. Return WRC_Abort if
79335 ** there is an abort request.
79337 ** If the Walker does not have an xSelectCallback() then this routine
79338 ** is a no-op returning WRC_Continue.
79340 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
79341 int rc;
79342 if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
79343 return WRC_Continue;
79345 rc = WRC_Continue;
79346 pWalker->walkerDepth++;
79347 while( p ){
79348 if( pWalker->xSelectCallback ){
79349 rc = pWalker->xSelectCallback(pWalker, p);
79350 if( rc ) break;
79352 if( sqlite3WalkSelectExpr(pWalker, p)
79353 || sqlite3WalkSelectFrom(pWalker, p)
79355 pWalker->walkerDepth--;
79356 return WRC_Abort;
79358 if( pWalker->xSelectCallback2 ){
79359 pWalker->xSelectCallback2(pWalker, p);
79361 p = p->pPrior;
79363 pWalker->walkerDepth--;
79364 return rc & WRC_Abort;
79367 /************** End of walker.c **********************************************/
79368 /************** Begin file resolve.c *****************************************/
79370 ** 2008 August 18
79372 ** The author disclaims copyright to this source code. In place of
79373 ** a legal notice, here is a blessing:
79375 ** May you do good and not evil.
79376 ** May you find forgiveness for yourself and forgive others.
79377 ** May you share freely, never taking more than you give.
79379 *************************************************************************
79381 ** This file contains routines used for walking the parser tree and
79382 ** resolve all identifiers by associating them with a particular
79383 ** table and column.
79385 /* #include <stdlib.h> */
79386 /* #include <string.h> */
79389 ** Walk the expression tree pExpr and increase the aggregate function
79390 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
79391 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
79392 ** outer query into an inner subquery.
79394 ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
79395 ** is a helper function - a callback for the tree walker.
79397 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
79398 if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
79399 return WRC_Continue;
79401 static void incrAggFunctionDepth(Expr *pExpr, int N){
79402 if( N>0 ){
79403 Walker w;
79404 memset(&w, 0, sizeof(w));
79405 w.xExprCallback = incrAggDepth;
79406 w.u.i = N;
79407 sqlite3WalkExpr(&w, pExpr);
79412 ** Turn the pExpr expression into an alias for the iCol-th column of the
79413 ** result set in pEList.
79415 ** If the result set column is a simple column reference, then this routine
79416 ** makes an exact copy. But for any other kind of expression, this
79417 ** routine make a copy of the result set column as the argument to the
79418 ** TK_AS operator. The TK_AS operator causes the expression to be
79419 ** evaluated just once and then reused for each alias.
79421 ** The reason for suppressing the TK_AS term when the expression is a simple
79422 ** column reference is so that the column reference will be recognized as
79423 ** usable by indices within the WHERE clause processing logic.
79425 ** The TK_AS operator is inhibited if zType[0]=='G'. This means
79426 ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
79428 ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
79430 ** Is equivalent to:
79432 ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
79434 ** The result of random()%5 in the GROUP BY clause is probably different
79435 ** from the result in the result-set. On the other hand Standard SQL does
79436 ** not allow the GROUP BY clause to contain references to result-set columns.
79437 ** So this should never come up in well-formed queries.
79439 ** If the reference is followed by a COLLATE operator, then make sure
79440 ** the COLLATE operator is preserved. For example:
79442 ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
79444 ** Should be transformed into:
79446 ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
79448 ** The nSubquery parameter specifies how many levels of subquery the
79449 ** alias is removed from the original expression. The usually value is
79450 ** zero but it might be more if the alias is contained within a subquery
79451 ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
79452 ** structures must be increased by the nSubquery amount.
79454 static void resolveAlias(
79455 Parse *pParse, /* Parsing context */
79456 ExprList *pEList, /* A result set */
79457 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
79458 Expr *pExpr, /* Transform this into an alias to the result set */
79459 const char *zType, /* "GROUP" or "ORDER" or "" */
79460 int nSubquery /* Number of subqueries that the label is moving */
79462 Expr *pOrig; /* The iCol-th column of the result set */
79463 Expr *pDup; /* Copy of pOrig */
79464 sqlite3 *db; /* The database connection */
79466 assert( iCol>=0 && iCol<pEList->nExpr );
79467 pOrig = pEList->a[iCol].pExpr;
79468 assert( pOrig!=0 );
79469 assert( pOrig->flags & EP_Resolved );
79470 db = pParse->db;
79471 pDup = sqlite3ExprDup(db, pOrig, 0);
79472 if( pDup==0 ) return;
79473 if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
79474 incrAggFunctionDepth(pDup, nSubquery);
79475 pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
79476 if( pDup==0 ) return;
79477 ExprSetProperty(pDup, EP_Skip);
79478 if( pEList->a[iCol].u.x.iAlias==0 ){
79479 pEList->a[iCol].u.x.iAlias = (u16)(++pParse->nAlias);
79481 pDup->iTable = pEList->a[iCol].u.x.iAlias;
79483 if( pExpr->op==TK_COLLATE ){
79484 pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
79487 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
79488 ** prevents ExprDelete() from deleting the Expr structure itself,
79489 ** allowing it to be repopulated by the memcpy() on the following line.
79490 ** The pExpr->u.zToken might point into memory that will be freed by the
79491 ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
79492 ** make a copy of the token before doing the sqlite3DbFree().
79494 ExprSetProperty(pExpr, EP_Static);
79495 sqlite3ExprDelete(db, pExpr);
79496 memcpy(pExpr, pDup, sizeof(*pExpr));
79497 if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
79498 assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
79499 pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
79500 pExpr->flags |= EP_MemToken;
79502 sqlite3DbFree(db, pDup);
79507 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
79509 ** Return FALSE if the USING clause is NULL or if it does not contain
79510 ** zCol.
79512 static int nameInUsingClause(IdList *pUsing, const char *zCol){
79513 if( pUsing ){
79514 int k;
79515 for(k=0; k<pUsing->nId; k++){
79516 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
79519 return 0;
79523 ** Subqueries stores the original database, table and column names for their
79524 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
79525 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
79526 ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
79527 ** match anything.
79529 SQLITE_PRIVATE int sqlite3MatchSpanName(
79530 const char *zSpan,
79531 const char *zCol,
79532 const char *zTab,
79533 const char *zDb
79535 int n;
79536 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
79537 if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
79538 return 0;
79540 zSpan += n+1;
79541 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
79542 if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
79543 return 0;
79545 zSpan += n+1;
79546 if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
79547 return 0;
79549 return 1;
79553 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
79554 ** that name in the set of source tables in pSrcList and make the pExpr
79555 ** expression node refer back to that source column. The following changes
79556 ** are made to pExpr:
79558 ** pExpr->iDb Set the index in db->aDb[] of the database X
79559 ** (even if X is implied).
79560 ** pExpr->iTable Set to the cursor number for the table obtained
79561 ** from pSrcList.
79562 ** pExpr->pTab Points to the Table structure of X.Y (even if
79563 ** X and/or Y are implied.)
79564 ** pExpr->iColumn Set to the column number within the table.
79565 ** pExpr->op Set to TK_COLUMN.
79566 ** pExpr->pLeft Any expression this points to is deleted
79567 ** pExpr->pRight Any expression this points to is deleted.
79569 ** The zDb variable is the name of the database (the "X"). This value may be
79570 ** NULL meaning that name is of the form Y.Z or Z. Any available database
79571 ** can be used. The zTable variable is the name of the table (the "Y"). This
79572 ** value can be NULL if zDb is also NULL. If zTable is NULL it
79573 ** means that the form of the name is Z and that columns from any table
79574 ** can be used.
79576 ** If the name cannot be resolved unambiguously, leave an error message
79577 ** in pParse and return WRC_Abort. Return WRC_Prune on success.
79579 static int lookupName(
79580 Parse *pParse, /* The parsing context */
79581 const char *zDb, /* Name of the database containing table, or NULL */
79582 const char *zTab, /* Name of table containing column, or NULL */
79583 const char *zCol, /* Name of the column. */
79584 NameContext *pNC, /* The name context used to resolve the name */
79585 Expr *pExpr /* Make this EXPR node point to the selected column */
79587 int i, j; /* Loop counters */
79588 int cnt = 0; /* Number of matching column names */
79589 int cntTab = 0; /* Number of matching table names */
79590 int nSubquery = 0; /* How many levels of subquery */
79591 sqlite3 *db = pParse->db; /* The database connection */
79592 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
79593 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
79594 NameContext *pTopNC = pNC; /* First namecontext in the list */
79595 Schema *pSchema = 0; /* Schema of the expression */
79596 int isTrigger = 0; /* True if resolved to a trigger column */
79597 Table *pTab = 0; /* Table hold the row */
79598 Column *pCol; /* A column of pTab */
79600 assert( pNC ); /* the name context cannot be NULL. */
79601 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
79602 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
79604 /* Initialize the node to no-match */
79605 pExpr->iTable = -1;
79606 pExpr->pTab = 0;
79607 ExprSetVVAProperty(pExpr, EP_NoReduce);
79609 /* Translate the schema name in zDb into a pointer to the corresponding
79610 ** schema. If not found, pSchema will remain NULL and nothing will match
79611 ** resulting in an appropriate error message toward the end of this routine
79613 if( zDb ){
79614 testcase( pNC->ncFlags & NC_PartIdx );
79615 testcase( pNC->ncFlags & NC_IsCheck );
79616 if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
79617 /* Silently ignore database qualifiers inside CHECK constraints and partial
79618 ** indices. Do not raise errors because that might break legacy and
79619 ** because it does not hurt anything to just ignore the database name. */
79620 zDb = 0;
79621 }else{
79622 for(i=0; i<db->nDb; i++){
79623 assert( db->aDb[i].zName );
79624 if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
79625 pSchema = db->aDb[i].pSchema;
79626 break;
79632 /* Start at the inner-most context and move outward until a match is found */
79633 while( pNC && cnt==0 ){
79634 ExprList *pEList;
79635 SrcList *pSrcList = pNC->pSrcList;
79637 if( pSrcList ){
79638 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
79639 pTab = pItem->pTab;
79640 assert( pTab!=0 && pTab->zName!=0 );
79641 assert( pTab->nCol>0 );
79642 if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
79643 int hit = 0;
79644 pEList = pItem->pSelect->pEList;
79645 for(j=0; j<pEList->nExpr; j++){
79646 if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
79647 cnt++;
79648 cntTab = 2;
79649 pMatch = pItem;
79650 pExpr->iColumn = j;
79651 hit = 1;
79654 if( hit || zTab==0 ) continue;
79656 if( zDb && pTab->pSchema!=pSchema ){
79657 continue;
79659 if( zTab ){
79660 const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
79661 assert( zTabName!=0 );
79662 if( sqlite3StrICmp(zTabName, zTab)!=0 ){
79663 continue;
79666 if( 0==(cntTab++) ){
79667 pMatch = pItem;
79669 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
79670 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
79671 /* If there has been exactly one prior match and this match
79672 ** is for the right-hand table of a NATURAL JOIN or is in a
79673 ** USING clause, then skip this match.
79675 if( cnt==1 ){
79676 if( pItem->jointype & JT_NATURAL ) continue;
79677 if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
79679 cnt++;
79680 pMatch = pItem;
79681 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
79682 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
79683 break;
79687 if( pMatch ){
79688 pExpr->iTable = pMatch->iCursor;
79689 pExpr->pTab = pMatch->pTab;
79690 assert( (pMatch->jointype & JT_RIGHT)==0 ); /* RIGHT JOIN not (yet) supported */
79691 if( (pMatch->jointype & JT_LEFT)!=0 ){
79692 ExprSetProperty(pExpr, EP_CanBeNull);
79694 pSchema = pExpr->pTab->pSchema;
79696 } /* if( pSrcList ) */
79698 #ifndef SQLITE_OMIT_TRIGGER
79699 /* If we have not already resolved the name, then maybe
79700 ** it is a new.* or old.* trigger argument reference
79702 if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
79703 int op = pParse->eTriggerOp;
79704 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
79705 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
79706 pExpr->iTable = 1;
79707 pTab = pParse->pTriggerTab;
79708 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
79709 pExpr->iTable = 0;
79710 pTab = pParse->pTriggerTab;
79711 }else{
79712 pTab = 0;
79715 if( pTab ){
79716 int iCol;
79717 pSchema = pTab->pSchema;
79718 cntTab++;
79719 for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
79720 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
79721 if( iCol==pTab->iPKey ){
79722 iCol = -1;
79724 break;
79727 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && HasRowid(pTab) ){
79728 /* IMP: R-51414-32910 */
79729 /* IMP: R-44911-55124 */
79730 iCol = -1;
79732 if( iCol<pTab->nCol ){
79733 cnt++;
79734 if( iCol<0 ){
79735 pExpr->affinity = SQLITE_AFF_INTEGER;
79736 }else if( pExpr->iTable==0 ){
79737 testcase( iCol==31 );
79738 testcase( iCol==32 );
79739 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
79740 }else{
79741 testcase( iCol==31 );
79742 testcase( iCol==32 );
79743 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
79745 pExpr->iColumn = (i16)iCol;
79746 pExpr->pTab = pTab;
79747 isTrigger = 1;
79751 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
79754 ** Perhaps the name is a reference to the ROWID
79756 if( cnt==0 && cntTab==1 && pMatch && sqlite3IsRowid(zCol)
79757 && HasRowid(pMatch->pTab) ){
79758 cnt = 1;
79759 pExpr->iColumn = -1; /* IMP: R-44911-55124 */
79760 pExpr->affinity = SQLITE_AFF_INTEGER;
79764 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
79765 ** might refer to an result-set alias. This happens, for example, when
79766 ** we are resolving names in the WHERE clause of the following command:
79768 ** SELECT a+b AS x FROM table WHERE x<10;
79770 ** In cases like this, replace pExpr with a copy of the expression that
79771 ** forms the result set entry ("a+b" in the example) and return immediately.
79772 ** Note that the expression in the result set should have already been
79773 ** resolved by the time the WHERE clause is resolved.
79775 ** The ability to use an output result-set column in the WHERE, GROUP BY,
79776 ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
79777 ** clause is not standard SQL. This is a (goofy) SQLite extension, that
79778 ** is supported for backwards compatibility only. TO DO: Issue a warning
79779 ** on sqlite3_log() whenever the capability is used.
79781 if( (pEList = pNC->pEList)!=0
79782 && zTab==0
79783 && cnt==0
79785 for(j=0; j<pEList->nExpr; j++){
79786 char *zAs = pEList->a[j].zName;
79787 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
79788 Expr *pOrig;
79789 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
79790 assert( pExpr->x.pList==0 );
79791 assert( pExpr->x.pSelect==0 );
79792 pOrig = pEList->a[j].pExpr;
79793 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
79794 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
79795 return WRC_Abort;
79797 resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
79798 cnt = 1;
79799 pMatch = 0;
79800 assert( zTab==0 && zDb==0 );
79801 goto lookupname_end;
79806 /* Advance to the next name context. The loop will exit when either
79807 ** we have a match (cnt>0) or when we run out of name contexts.
79809 if( cnt==0 ){
79810 pNC = pNC->pNext;
79811 nSubquery++;
79816 ** If X and Y are NULL (in other words if only the column name Z is
79817 ** supplied) and the value of Z is enclosed in double-quotes, then
79818 ** Z is a string literal if it doesn't match any column names. In that
79819 ** case, we need to return right away and not make any changes to
79820 ** pExpr.
79822 ** Because no reference was made to outer contexts, the pNC->nRef
79823 ** fields are not changed in any context.
79825 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
79826 pExpr->op = TK_STRING;
79827 pExpr->pTab = 0;
79828 return WRC_Prune;
79832 ** cnt==0 means there was not match. cnt>1 means there were two or
79833 ** more matches. Either way, we have an error.
79835 if( cnt!=1 ){
79836 const char *zErr;
79837 zErr = cnt==0 ? "no such column" : "ambiguous column name";
79838 if( zDb ){
79839 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
79840 }else if( zTab ){
79841 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
79842 }else{
79843 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
79845 pParse->checkSchema = 1;
79846 pTopNC->nErr++;
79849 /* If a column from a table in pSrcList is referenced, then record
79850 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
79851 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
79852 ** column number is greater than the number of bits in the bitmask
79853 ** then set the high-order bit of the bitmask.
79855 if( pExpr->iColumn>=0 && pMatch!=0 ){
79856 int n = pExpr->iColumn;
79857 testcase( n==BMS-1 );
79858 if( n>=BMS ){
79859 n = BMS-1;
79861 assert( pMatch->iCursor==pExpr->iTable );
79862 pMatch->colUsed |= ((Bitmask)1)<<n;
79865 /* Clean up and return
79867 sqlite3ExprDelete(db, pExpr->pLeft);
79868 pExpr->pLeft = 0;
79869 sqlite3ExprDelete(db, pExpr->pRight);
79870 pExpr->pRight = 0;
79871 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
79872 lookupname_end:
79873 if( cnt==1 ){
79874 assert( pNC!=0 );
79875 if( pExpr->op!=TK_AS ){
79876 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
79878 /* Increment the nRef value on all name contexts from TopNC up to
79879 ** the point where the name matched. */
79880 for(;;){
79881 assert( pTopNC!=0 );
79882 pTopNC->nRef++;
79883 if( pTopNC==pNC ) break;
79884 pTopNC = pTopNC->pNext;
79886 return WRC_Prune;
79887 } else {
79888 return WRC_Abort;
79893 ** Allocate and return a pointer to an expression to load the column iCol
79894 ** from datasource iSrc in SrcList pSrc.
79896 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
79897 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
79898 if( p ){
79899 struct SrcList_item *pItem = &pSrc->a[iSrc];
79900 p->pTab = pItem->pTab;
79901 p->iTable = pItem->iCursor;
79902 if( p->pTab->iPKey==iCol ){
79903 p->iColumn = -1;
79904 }else{
79905 p->iColumn = (ynVar)iCol;
79906 testcase( iCol==BMS );
79907 testcase( iCol==BMS-1 );
79908 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
79910 ExprSetProperty(p, EP_Resolved);
79912 return p;
79916 ** Report an error that an expression is not valid for a partial index WHERE
79917 ** clause.
79919 static void notValidPartIdxWhere(
79920 Parse *pParse, /* Leave error message here */
79921 NameContext *pNC, /* The name context */
79922 const char *zMsg /* Type of error */
79924 if( (pNC->ncFlags & NC_PartIdx)!=0 ){
79925 sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
79926 zMsg);
79930 #ifndef SQLITE_OMIT_CHECK
79932 ** Report an error that an expression is not valid for a CHECK constraint.
79934 static void notValidCheckConstraint(
79935 Parse *pParse, /* Leave error message here */
79936 NameContext *pNC, /* The name context */
79937 const char *zMsg /* Type of error */
79939 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
79940 sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
79943 #else
79944 # define notValidCheckConstraint(P,N,M)
79945 #endif
79948 ** Expression p should encode a floating point value between 1.0 and 0.0.
79949 ** Return 1024 times this value. Or return -1 if p is not a floating point
79950 ** value between 1.0 and 0.0.
79952 static int exprProbability(Expr *p){
79953 double r = -1.0;
79954 if( p->op!=TK_FLOAT ) return -1;
79955 sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
79956 assert( r>=0.0 );
79957 if( r>1.0 ) return -1;
79958 return (int)(r*1000.0);
79962 ** This routine is callback for sqlite3WalkExpr().
79964 ** Resolve symbolic names into TK_COLUMN operators for the current
79965 ** node in the expression tree. Return 0 to continue the search down
79966 ** the tree or 2 to abort the tree walk.
79968 ** This routine also does error checking and name resolution for
79969 ** function names. The operator for aggregate functions is changed
79970 ** to TK_AGG_FUNCTION.
79972 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
79973 NameContext *pNC;
79974 Parse *pParse;
79976 pNC = pWalker->u.pNC;
79977 assert( pNC!=0 );
79978 pParse = pNC->pParse;
79979 assert( pParse==pWalker->pParse );
79981 if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
79982 ExprSetProperty(pExpr, EP_Resolved);
79983 #ifndef NDEBUG
79984 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
79985 SrcList *pSrcList = pNC->pSrcList;
79986 int i;
79987 for(i=0; i<pNC->pSrcList->nSrc; i++){
79988 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
79991 #endif
79992 switch( pExpr->op ){
79994 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
79995 /* The special operator TK_ROW means use the rowid for the first
79996 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
79997 ** clause processing on UPDATE and DELETE statements.
79999 case TK_ROW: {
80000 SrcList *pSrcList = pNC->pSrcList;
80001 struct SrcList_item *pItem;
80002 assert( pSrcList && pSrcList->nSrc==1 );
80003 pItem = pSrcList->a;
80004 pExpr->op = TK_COLUMN;
80005 pExpr->pTab = pItem->pTab;
80006 pExpr->iTable = pItem->iCursor;
80007 pExpr->iColumn = -1;
80008 pExpr->affinity = SQLITE_AFF_INTEGER;
80009 break;
80011 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
80013 /* A lone identifier is the name of a column.
80015 case TK_ID: {
80016 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
80019 /* A table name and column name: ID.ID
80020 ** Or a database, table and column: ID.ID.ID
80022 case TK_DOT: {
80023 const char *zColumn;
80024 const char *zTable;
80025 const char *zDb;
80026 Expr *pRight;
80028 /* if( pSrcList==0 ) break; */
80029 pRight = pExpr->pRight;
80030 if( pRight->op==TK_ID ){
80031 zDb = 0;
80032 zTable = pExpr->pLeft->u.zToken;
80033 zColumn = pRight->u.zToken;
80034 }else{
80035 assert( pRight->op==TK_DOT );
80036 zDb = pExpr->pLeft->u.zToken;
80037 zTable = pRight->pLeft->u.zToken;
80038 zColumn = pRight->pRight->u.zToken;
80040 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
80043 /* Resolve function names
80045 case TK_FUNCTION: {
80046 ExprList *pList = pExpr->x.pList; /* The argument list */
80047 int n = pList ? pList->nExpr : 0; /* Number of arguments */
80048 int no_such_func = 0; /* True if no such function exists */
80049 int wrong_num_args = 0; /* True if wrong number of arguments */
80050 int is_agg = 0; /* True if is an aggregate function */
80051 int auth; /* Authorization to use the function */
80052 int nId; /* Number of characters in function name */
80053 const char *zId; /* The function name. */
80054 FuncDef *pDef; /* Information about the function */
80055 u8 enc = ENC(pParse->db); /* The database encoding */
80057 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
80058 notValidPartIdxWhere(pParse, pNC, "functions");
80059 zId = pExpr->u.zToken;
80060 nId = sqlite3Strlen30(zId);
80061 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
80062 if( pDef==0 ){
80063 pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
80064 if( pDef==0 ){
80065 no_such_func = 1;
80066 }else{
80067 wrong_num_args = 1;
80069 }else{
80070 is_agg = pDef->xFunc==0;
80071 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
80072 ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
80073 if( n==2 ){
80074 pExpr->iTable = exprProbability(pList->a[1].pExpr);
80075 if( pExpr->iTable<0 ){
80076 sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a "
80077 "constant between 0.0 and 1.0");
80078 pNC->nErr++;
80080 }else{
80081 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to
80082 ** likelihood(X, 0.0625).
80083 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is short-hand for
80084 ** likelihood(X,0.0625).
80085 ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand for
80086 ** likelihood(X,0.9375).
80087 ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent to
80088 ** likelihood(X,0.9375). */
80089 /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
80090 pExpr->iTable = pDef->zName[0]=='u' ? 62 : 938;
80093 #ifndef SQLITE_OMIT_AUTHORIZATION
80094 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
80095 if( auth!=SQLITE_OK ){
80096 if( auth==SQLITE_DENY ){
80097 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
80098 pDef->zName);
80099 pNC->nErr++;
80101 pExpr->op = TK_NULL;
80102 return WRC_Prune;
80104 #endif
80105 if( pDef->funcFlags & SQLITE_FUNC_CONSTANT ) ExprSetProperty(pExpr,EP_Constant);
80107 if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
80108 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
80109 pNC->nErr++;
80110 is_agg = 0;
80111 }else if( no_such_func && pParse->db->init.busy==0 ){
80112 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
80113 pNC->nErr++;
80114 }else if( wrong_num_args ){
80115 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
80116 nId, zId);
80117 pNC->nErr++;
80119 if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
80120 sqlite3WalkExprList(pWalker, pList);
80121 if( is_agg ){
80122 NameContext *pNC2 = pNC;
80123 pExpr->op = TK_AGG_FUNCTION;
80124 pExpr->op2 = 0;
80125 while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
80126 pExpr->op2++;
80127 pNC2 = pNC2->pNext;
80129 assert( pDef!=0 );
80130 if( pNC2 ){
80131 assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
80132 testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
80133 pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
80136 pNC->ncFlags |= NC_AllowAgg;
80138 /* FIX ME: Compute pExpr->affinity based on the expected return
80139 ** type of the function
80141 return WRC_Prune;
80143 #ifndef SQLITE_OMIT_SUBQUERY
80144 case TK_SELECT:
80145 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
80146 #endif
80147 case TK_IN: {
80148 testcase( pExpr->op==TK_IN );
80149 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
80150 int nRef = pNC->nRef;
80151 notValidCheckConstraint(pParse, pNC, "subqueries");
80152 notValidPartIdxWhere(pParse, pNC, "subqueries");
80153 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
80154 assert( pNC->nRef>=nRef );
80155 if( nRef!=pNC->nRef ){
80156 ExprSetProperty(pExpr, EP_VarSelect);
80159 break;
80161 case TK_VARIABLE: {
80162 notValidCheckConstraint(pParse, pNC, "parameters");
80163 notValidPartIdxWhere(pParse, pNC, "parameters");
80164 break;
80167 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
80171 ** pEList is a list of expressions which are really the result set of the
80172 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
80173 ** This routine checks to see if pE is a simple identifier which corresponds
80174 ** to the AS-name of one of the terms of the expression list. If it is,
80175 ** this routine return an integer between 1 and N where N is the number of
80176 ** elements in pEList, corresponding to the matching entry. If there is
80177 ** no match, or if pE is not a simple identifier, then this routine
80178 ** return 0.
80180 ** pEList has been resolved. pE has not.
80182 static int resolveAsName(
80183 Parse *pParse, /* Parsing context for error messages */
80184 ExprList *pEList, /* List of expressions to scan */
80185 Expr *pE /* Expression we are trying to match */
80187 int i; /* Loop counter */
80189 UNUSED_PARAMETER(pParse);
80191 if( pE->op==TK_ID ){
80192 char *zCol = pE->u.zToken;
80193 for(i=0; i<pEList->nExpr; i++){
80194 char *zAs = pEList->a[i].zName;
80195 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
80196 return i+1;
80200 return 0;
80204 ** pE is a pointer to an expression which is a single term in the
80205 ** ORDER BY of a compound SELECT. The expression has not been
80206 ** name resolved.
80208 ** At the point this routine is called, we already know that the
80209 ** ORDER BY term is not an integer index into the result set. That
80210 ** case is handled by the calling routine.
80212 ** Attempt to match pE against result set columns in the left-most
80213 ** SELECT statement. Return the index i of the matching column,
80214 ** as an indication to the caller that it should sort by the i-th column.
80215 ** The left-most column is 1. In other words, the value returned is the
80216 ** same integer value that would be used in the SQL statement to indicate
80217 ** the column.
80219 ** If there is no match, return 0. Return -1 if an error occurs.
80221 static int resolveOrderByTermToExprList(
80222 Parse *pParse, /* Parsing context for error messages */
80223 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
80224 Expr *pE /* The specific ORDER BY term */
80226 int i; /* Loop counter */
80227 ExprList *pEList; /* The columns of the result set */
80228 NameContext nc; /* Name context for resolving pE */
80229 sqlite3 *db; /* Database connection */
80230 int rc; /* Return code from subprocedures */
80231 u8 savedSuppErr; /* Saved value of db->suppressErr */
80233 assert( sqlite3ExprIsInteger(pE, &i)==0 );
80234 pEList = pSelect->pEList;
80236 /* Resolve all names in the ORDER BY term expression
80238 memset(&nc, 0, sizeof(nc));
80239 nc.pParse = pParse;
80240 nc.pSrcList = pSelect->pSrc;
80241 nc.pEList = pEList;
80242 nc.ncFlags = NC_AllowAgg;
80243 nc.nErr = 0;
80244 db = pParse->db;
80245 savedSuppErr = db->suppressErr;
80246 db->suppressErr = 1;
80247 rc = sqlite3ResolveExprNames(&nc, pE);
80248 db->suppressErr = savedSuppErr;
80249 if( rc ) return 0;
80251 /* Try to match the ORDER BY expression against an expression
80252 ** in the result set. Return an 1-based index of the matching
80253 ** result-set entry.
80255 for(i=0; i<pEList->nExpr; i++){
80256 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
80257 return i+1;
80261 /* If no match, return 0. */
80262 return 0;
80266 ** Generate an ORDER BY or GROUP BY term out-of-range error.
80268 static void resolveOutOfRangeError(
80269 Parse *pParse, /* The error context into which to write the error */
80270 const char *zType, /* "ORDER" or "GROUP" */
80271 int i, /* The index (1-based) of the term out of range */
80272 int mx /* Largest permissible value of i */
80274 sqlite3ErrorMsg(pParse,
80275 "%r %s BY term out of range - should be "
80276 "between 1 and %d", i, zType, mx);
80280 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
80281 ** each term of the ORDER BY clause is a constant integer between 1
80282 ** and N where N is the number of columns in the compound SELECT.
80284 ** ORDER BY terms that are already an integer between 1 and N are
80285 ** unmodified. ORDER BY terms that are integers outside the range of
80286 ** 1 through N generate an error. ORDER BY terms that are expressions
80287 ** are matched against result set expressions of compound SELECT
80288 ** beginning with the left-most SELECT and working toward the right.
80289 ** At the first match, the ORDER BY expression is transformed into
80290 ** the integer column number.
80292 ** Return the number of errors seen.
80294 static int resolveCompoundOrderBy(
80295 Parse *pParse, /* Parsing context. Leave error messages here */
80296 Select *pSelect /* The SELECT statement containing the ORDER BY */
80298 int i;
80299 ExprList *pOrderBy;
80300 ExprList *pEList;
80301 sqlite3 *db;
80302 int moreToDo = 1;
80304 pOrderBy = pSelect->pOrderBy;
80305 if( pOrderBy==0 ) return 0;
80306 db = pParse->db;
80307 #if SQLITE_MAX_COLUMN
80308 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
80309 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
80310 return 1;
80312 #endif
80313 for(i=0; i<pOrderBy->nExpr; i++){
80314 pOrderBy->a[i].done = 0;
80316 pSelect->pNext = 0;
80317 while( pSelect->pPrior ){
80318 pSelect->pPrior->pNext = pSelect;
80319 pSelect = pSelect->pPrior;
80321 while( pSelect && moreToDo ){
80322 struct ExprList_item *pItem;
80323 moreToDo = 0;
80324 pEList = pSelect->pEList;
80325 assert( pEList!=0 );
80326 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
80327 int iCol = -1;
80328 Expr *pE, *pDup;
80329 if( pItem->done ) continue;
80330 pE = sqlite3ExprSkipCollate(pItem->pExpr);
80331 if( sqlite3ExprIsInteger(pE, &iCol) ){
80332 if( iCol<=0 || iCol>pEList->nExpr ){
80333 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
80334 return 1;
80336 }else{
80337 iCol = resolveAsName(pParse, pEList, pE);
80338 if( iCol==0 ){
80339 pDup = sqlite3ExprDup(db, pE, 0);
80340 if( !db->mallocFailed ){
80341 assert(pDup);
80342 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
80344 sqlite3ExprDelete(db, pDup);
80347 if( iCol>0 ){
80348 /* Convert the ORDER BY term into an integer column number iCol,
80349 ** taking care to preserve the COLLATE clause if it exists */
80350 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
80351 if( pNew==0 ) return 1;
80352 pNew->flags |= EP_IntValue;
80353 pNew->u.iValue = iCol;
80354 if( pItem->pExpr==pE ){
80355 pItem->pExpr = pNew;
80356 }else{
80357 assert( pItem->pExpr->op==TK_COLLATE );
80358 assert( pItem->pExpr->pLeft==pE );
80359 pItem->pExpr->pLeft = pNew;
80361 sqlite3ExprDelete(db, pE);
80362 pItem->u.x.iOrderByCol = (u16)iCol;
80363 pItem->done = 1;
80364 }else{
80365 moreToDo = 1;
80368 pSelect = pSelect->pNext;
80370 for(i=0; i<pOrderBy->nExpr; i++){
80371 if( pOrderBy->a[i].done==0 ){
80372 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
80373 "column in the result set", i+1);
80374 return 1;
80377 return 0;
80381 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
80382 ** the SELECT statement pSelect. If any term is reference to a
80383 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
80384 ** field) then convert that term into a copy of the corresponding result set
80385 ** column.
80387 ** If any errors are detected, add an error message to pParse and
80388 ** return non-zero. Return zero if no errors are seen.
80390 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
80391 Parse *pParse, /* Parsing context. Leave error messages here */
80392 Select *pSelect, /* The SELECT statement containing the clause */
80393 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
80394 const char *zType /* "ORDER" or "GROUP" */
80396 int i;
80397 sqlite3 *db = pParse->db;
80398 ExprList *pEList;
80399 struct ExprList_item *pItem;
80401 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
80402 #if SQLITE_MAX_COLUMN
80403 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
80404 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
80405 return 1;
80407 #endif
80408 pEList = pSelect->pEList;
80409 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
80410 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
80411 if( pItem->u.x.iOrderByCol ){
80412 if( pItem->u.x.iOrderByCol>pEList->nExpr ){
80413 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
80414 return 1;
80416 resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr, zType,0);
80419 return 0;
80423 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
80424 ** The Name context of the SELECT statement is pNC. zType is either
80425 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
80427 ** This routine resolves each term of the clause into an expression.
80428 ** If the order-by term is an integer I between 1 and N (where N is the
80429 ** number of columns in the result set of the SELECT) then the expression
80430 ** in the resolution is a copy of the I-th result-set expression. If
80431 ** the order-by term is an identifier that corresponds to the AS-name of
80432 ** a result-set expression, then the term resolves to a copy of the
80433 ** result-set expression. Otherwise, the expression is resolved in
80434 ** the usual way - using sqlite3ResolveExprNames().
80436 ** This routine returns the number of errors. If errors occur, then
80437 ** an appropriate error message might be left in pParse. (OOM errors
80438 ** excepted.)
80440 static int resolveOrderGroupBy(
80441 NameContext *pNC, /* The name context of the SELECT statement */
80442 Select *pSelect, /* The SELECT statement holding pOrderBy */
80443 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
80444 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
80446 int i, j; /* Loop counters */
80447 int iCol; /* Column number */
80448 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
80449 Parse *pParse; /* Parsing context */
80450 int nResult; /* Number of terms in the result set */
80452 if( pOrderBy==0 ) return 0;
80453 nResult = pSelect->pEList->nExpr;
80454 pParse = pNC->pParse;
80455 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
80456 Expr *pE = pItem->pExpr;
80457 Expr *pE2 = sqlite3ExprSkipCollate(pE);
80458 if( zType[0]!='G' ){
80459 iCol = resolveAsName(pParse, pSelect->pEList, pE2);
80460 if( iCol>0 ){
80461 /* If an AS-name match is found, mark this ORDER BY column as being
80462 ** a copy of the iCol-th result-set column. The subsequent call to
80463 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
80464 ** copy of the iCol-th result-set expression. */
80465 pItem->u.x.iOrderByCol = (u16)iCol;
80466 continue;
80469 if( sqlite3ExprIsInteger(pE2, &iCol) ){
80470 /* The ORDER BY term is an integer constant. Again, set the column
80471 ** number so that sqlite3ResolveOrderGroupBy() will convert the
80472 ** order-by term to a copy of the result-set expression */
80473 if( iCol<1 || iCol>0xffff ){
80474 resolveOutOfRangeError(pParse, zType, i+1, nResult);
80475 return 1;
80477 pItem->u.x.iOrderByCol = (u16)iCol;
80478 continue;
80481 /* Otherwise, treat the ORDER BY term as an ordinary expression */
80482 pItem->u.x.iOrderByCol = 0;
80483 if( sqlite3ResolveExprNames(pNC, pE) ){
80484 return 1;
80486 for(j=0; j<pSelect->pEList->nExpr; j++){
80487 if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
80488 pItem->u.x.iOrderByCol = j+1;
80492 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
80496 ** Resolve names in the SELECT statement p and all of its descendants.
80498 static int resolveSelectStep(Walker *pWalker, Select *p){
80499 NameContext *pOuterNC; /* Context that contains this SELECT */
80500 NameContext sNC; /* Name context of this SELECT */
80501 int isCompound; /* True if p is a compound select */
80502 int nCompound; /* Number of compound terms processed so far */
80503 Parse *pParse; /* Parsing context */
80504 ExprList *pEList; /* Result set expression list */
80505 int i; /* Loop counter */
80506 ExprList *pGroupBy; /* The GROUP BY clause */
80507 Select *pLeftmost; /* Left-most of SELECT of a compound */
80508 sqlite3 *db; /* Database connection */
80511 assert( p!=0 );
80512 if( p->selFlags & SF_Resolved ){
80513 return WRC_Prune;
80515 pOuterNC = pWalker->u.pNC;
80516 pParse = pWalker->pParse;
80517 db = pParse->db;
80519 /* Normally sqlite3SelectExpand() will be called first and will have
80520 ** already expanded this SELECT. However, if this is a subquery within
80521 ** an expression, sqlite3ResolveExprNames() will be called without a
80522 ** prior call to sqlite3SelectExpand(). When that happens, let
80523 ** sqlite3SelectPrep() do all of the processing for this SELECT.
80524 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
80525 ** this routine in the correct order.
80527 if( (p->selFlags & SF_Expanded)==0 ){
80528 sqlite3SelectPrep(pParse, p, pOuterNC);
80529 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
80532 isCompound = p->pPrior!=0;
80533 nCompound = 0;
80534 pLeftmost = p;
80535 while( p ){
80536 assert( (p->selFlags & SF_Expanded)!=0 );
80537 assert( (p->selFlags & SF_Resolved)==0 );
80538 p->selFlags |= SF_Resolved;
80540 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
80541 ** are not allowed to refer to any names, so pass an empty NameContext.
80543 memset(&sNC, 0, sizeof(sNC));
80544 sNC.pParse = pParse;
80545 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
80546 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
80547 return WRC_Abort;
80550 /* Recursively resolve names in all subqueries
80552 for(i=0; i<p->pSrc->nSrc; i++){
80553 struct SrcList_item *pItem = &p->pSrc->a[i];
80554 if( pItem->pSelect ){
80555 NameContext *pNC; /* Used to iterate name contexts */
80556 int nRef = 0; /* Refcount for pOuterNC and outer contexts */
80557 const char *zSavedContext = pParse->zAuthContext;
80559 /* Count the total number of references to pOuterNC and all of its
80560 ** parent contexts. After resolving references to expressions in
80561 ** pItem->pSelect, check if this value has changed. If so, then
80562 ** SELECT statement pItem->pSelect must be correlated. Set the
80563 ** pItem->isCorrelated flag if this is the case. */
80564 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
80566 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
80567 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
80568 pParse->zAuthContext = zSavedContext;
80569 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
80571 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
80572 assert( pItem->isCorrelated==0 && nRef<=0 );
80573 pItem->isCorrelated = (nRef!=0);
80577 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
80578 ** resolve the result-set expression list.
80580 sNC.ncFlags = NC_AllowAgg;
80581 sNC.pSrcList = p->pSrc;
80582 sNC.pNext = pOuterNC;
80584 /* Resolve names in the result set. */
80585 pEList = p->pEList;
80586 assert( pEList!=0 );
80587 for(i=0; i<pEList->nExpr; i++){
80588 Expr *pX = pEList->a[i].pExpr;
80589 if( sqlite3ResolveExprNames(&sNC, pX) ){
80590 return WRC_Abort;
80594 /* If there are no aggregate functions in the result-set, and no GROUP BY
80595 ** expression, do not allow aggregates in any of the other expressions.
80597 assert( (p->selFlags & SF_Aggregate)==0 );
80598 pGroupBy = p->pGroupBy;
80599 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
80600 assert( NC_MinMaxAgg==SF_MinMaxAgg );
80601 p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
80602 }else{
80603 sNC.ncFlags &= ~NC_AllowAgg;
80606 /* If a HAVING clause is present, then there must be a GROUP BY clause.
80608 if( p->pHaving && !pGroupBy ){
80609 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
80610 return WRC_Abort;
80613 /* Add the output column list to the name-context before parsing the
80614 ** other expressions in the SELECT statement. This is so that
80615 ** expressions in the WHERE clause (etc.) can refer to expressions by
80616 ** aliases in the result set.
80618 ** Minor point: If this is the case, then the expression will be
80619 ** re-evaluated for each reference to it.
80621 sNC.pEList = p->pEList;
80622 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
80623 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
80625 /* The ORDER BY and GROUP BY clauses may not refer to terms in
80626 ** outer queries
80628 sNC.pNext = 0;
80629 sNC.ncFlags |= NC_AllowAgg;
80631 /* Process the ORDER BY clause for singleton SELECT statements.
80632 ** The ORDER BY clause for compounds SELECT statements is handled
80633 ** below, after all of the result-sets for all of the elements of
80634 ** the compound have been resolved.
80636 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
80637 return WRC_Abort;
80639 if( db->mallocFailed ){
80640 return WRC_Abort;
80643 /* Resolve the GROUP BY clause. At the same time, make sure
80644 ** the GROUP BY clause does not contain aggregate functions.
80646 if( pGroupBy ){
80647 struct ExprList_item *pItem;
80649 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
80650 return WRC_Abort;
80652 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
80653 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
80654 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
80655 "the GROUP BY clause");
80656 return WRC_Abort;
80661 /* Advance to the next term of the compound
80663 p = p->pPrior;
80664 nCompound++;
80667 /* Resolve the ORDER BY on a compound SELECT after all terms of
80668 ** the compound have been resolved.
80670 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
80671 return WRC_Abort;
80674 return WRC_Prune;
80678 ** This routine walks an expression tree and resolves references to
80679 ** table columns and result-set columns. At the same time, do error
80680 ** checking on function usage and set a flag if any aggregate functions
80681 ** are seen.
80683 ** To resolve table columns references we look for nodes (or subtrees) of the
80684 ** form X.Y.Z or Y.Z or just Z where
80686 ** X: The name of a database. Ex: "main" or "temp" or
80687 ** the symbolic name assigned to an ATTACH-ed database.
80689 ** Y: The name of a table in a FROM clause. Or in a trigger
80690 ** one of the special names "old" or "new".
80692 ** Z: The name of a column in table Y.
80694 ** The node at the root of the subtree is modified as follows:
80696 ** Expr.op Changed to TK_COLUMN
80697 ** Expr.pTab Points to the Table object for X.Y
80698 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
80699 ** Expr.iTable The VDBE cursor number for X.Y
80702 ** To resolve result-set references, look for expression nodes of the
80703 ** form Z (with no X and Y prefix) where the Z matches the right-hand
80704 ** size of an AS clause in the result-set of a SELECT. The Z expression
80705 ** is replaced by a copy of the left-hand side of the result-set expression.
80706 ** Table-name and function resolution occurs on the substituted expression
80707 ** tree. For example, in:
80709 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
80711 ** The "x" term of the order by is replaced by "a+b" to render:
80713 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
80715 ** Function calls are checked to make sure that the function is
80716 ** defined and that the correct number of arguments are specified.
80717 ** If the function is an aggregate function, then the NC_HasAgg flag is
80718 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
80719 ** If an expression contains aggregate functions then the EP_Agg
80720 ** property on the expression is set.
80722 ** An error message is left in pParse if anything is amiss. The number
80723 ** if errors is returned.
80725 SQLITE_PRIVATE int sqlite3ResolveExprNames(
80726 NameContext *pNC, /* Namespace to resolve expressions in. */
80727 Expr *pExpr /* The expression to be analyzed. */
80729 u16 savedHasAgg;
80730 Walker w;
80732 if( pExpr==0 ) return 0;
80733 #if SQLITE_MAX_EXPR_DEPTH>0
80735 Parse *pParse = pNC->pParse;
80736 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
80737 return 1;
80739 pParse->nHeight += pExpr->nHeight;
80741 #endif
80742 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
80743 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
80744 memset(&w, 0, sizeof(w));
80745 w.xExprCallback = resolveExprStep;
80746 w.xSelectCallback = resolveSelectStep;
80747 w.pParse = pNC->pParse;
80748 w.u.pNC = pNC;
80749 sqlite3WalkExpr(&w, pExpr);
80750 #if SQLITE_MAX_EXPR_DEPTH>0
80751 pNC->pParse->nHeight -= pExpr->nHeight;
80752 #endif
80753 if( pNC->nErr>0 || w.pParse->nErr>0 ){
80754 ExprSetProperty(pExpr, EP_Error);
80756 if( pNC->ncFlags & NC_HasAgg ){
80757 ExprSetProperty(pExpr, EP_Agg);
80759 pNC->ncFlags |= savedHasAgg;
80760 return ExprHasProperty(pExpr, EP_Error);
80765 ** Resolve all names in all expressions of a SELECT and in all
80766 ** decendents of the SELECT, including compounds off of p->pPrior,
80767 ** subqueries in expressions, and subqueries used as FROM clause
80768 ** terms.
80770 ** See sqlite3ResolveExprNames() for a description of the kinds of
80771 ** transformations that occur.
80773 ** All SELECT statements should have been expanded using
80774 ** sqlite3SelectExpand() prior to invoking this routine.
80776 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
80777 Parse *pParse, /* The parser context */
80778 Select *p, /* The SELECT statement being coded. */
80779 NameContext *pOuterNC /* Name context for parent SELECT statement */
80781 Walker w;
80783 assert( p!=0 );
80784 memset(&w, 0, sizeof(w));
80785 w.xExprCallback = resolveExprStep;
80786 w.xSelectCallback = resolveSelectStep;
80787 w.pParse = pParse;
80788 w.u.pNC = pOuterNC;
80789 sqlite3WalkSelect(&w, p);
80793 ** Resolve names in expressions that can only reference a single table:
80795 ** * CHECK constraints
80796 ** * WHERE clauses on partial indices
80798 ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
80799 ** is set to -1 and the Expr.iColumn value is set to the column number.
80801 ** Any errors cause an error message to be set in pParse.
80803 SQLITE_PRIVATE void sqlite3ResolveSelfReference(
80804 Parse *pParse, /* Parsing context */
80805 Table *pTab, /* The table being referenced */
80806 int type, /* NC_IsCheck or NC_PartIdx */
80807 Expr *pExpr, /* Expression to resolve. May be NULL. */
80808 ExprList *pList /* Expression list to resolve. May be NUL. */
80810 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
80811 NameContext sNC; /* Name context for pParse->pNewTable */
80812 int i; /* Loop counter */
80814 assert( type==NC_IsCheck || type==NC_PartIdx );
80815 memset(&sNC, 0, sizeof(sNC));
80816 memset(&sSrc, 0, sizeof(sSrc));
80817 sSrc.nSrc = 1;
80818 sSrc.a[0].zName = pTab->zName;
80819 sSrc.a[0].pTab = pTab;
80820 sSrc.a[0].iCursor = -1;
80821 sNC.pParse = pParse;
80822 sNC.pSrcList = &sSrc;
80823 sNC.ncFlags = type;
80824 if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
80825 if( pList ){
80826 for(i=0; i<pList->nExpr; i++){
80827 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
80828 return;
80834 /************** End of resolve.c *********************************************/
80835 /************** Begin file expr.c ********************************************/
80837 ** 2001 September 15
80839 ** The author disclaims copyright to this source code. In place of
80840 ** a legal notice, here is a blessing:
80842 ** May you do good and not evil.
80843 ** May you find forgiveness for yourself and forgive others.
80844 ** May you share freely, never taking more than you give.
80846 *************************************************************************
80847 ** This file contains routines used for analyzing expressions and
80848 ** for generating VDBE code that evaluates expressions in SQLite.
80852 ** Return the 'affinity' of the expression pExpr if any.
80854 ** If pExpr is a column, a reference to a column via an 'AS' alias,
80855 ** or a sub-select with a column as the return value, then the
80856 ** affinity of that column is returned. Otherwise, 0x00 is returned,
80857 ** indicating no affinity for the expression.
80859 ** i.e. the WHERE clause expressions in the following statements all
80860 ** have an affinity:
80862 ** CREATE TABLE t1(a);
80863 ** SELECT * FROM t1 WHERE a;
80864 ** SELECT a AS b FROM t1 WHERE b;
80865 ** SELECT * FROM t1 WHERE (select a from t1);
80867 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
80868 int op;
80869 pExpr = sqlite3ExprSkipCollate(pExpr);
80870 if( pExpr->flags & EP_Generic ) return 0;
80871 op = pExpr->op;
80872 if( op==TK_SELECT ){
80873 assert( pExpr->flags&EP_xIsSelect );
80874 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
80876 #ifndef SQLITE_OMIT_CAST
80877 if( op==TK_CAST ){
80878 assert( !ExprHasProperty(pExpr, EP_IntValue) );
80879 return sqlite3AffinityType(pExpr->u.zToken, 0);
80881 #endif
80882 if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
80883 && pExpr->pTab!=0
80885 /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
80886 ** a TK_COLUMN but was previously evaluated and cached in a register */
80887 int j = pExpr->iColumn;
80888 if( j<0 ) return SQLITE_AFF_INTEGER;
80889 assert( pExpr->pTab && j<pExpr->pTab->nCol );
80890 return pExpr->pTab->aCol[j].affinity;
80892 return pExpr->affinity;
80896 ** Set the collating sequence for expression pExpr to be the collating
80897 ** sequence named by pToken. Return a pointer to a new Expr node that
80898 ** implements the COLLATE operator.
80900 ** If a memory allocation error occurs, that fact is recorded in pParse->db
80901 ** and the pExpr parameter is returned unchanged.
80903 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
80904 Parse *pParse, /* Parsing context */
80905 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
80906 const Token *pCollName, /* Name of collating sequence */
80907 int dequote /* True to dequote pCollName */
80909 if( pCollName->n>0 ){
80910 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
80911 if( pNew ){
80912 pNew->pLeft = pExpr;
80913 pNew->flags |= EP_Collate|EP_Skip;
80914 pExpr = pNew;
80917 return pExpr;
80919 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
80920 Token s;
80921 assert( zC!=0 );
80922 s.z = zC;
80923 s.n = sqlite3Strlen30(s.z);
80924 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
80928 ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
80929 ** or likelihood() function at the root of an expression.
80931 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
80932 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
80933 if( ExprHasProperty(pExpr, EP_Unlikely) ){
80934 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
80935 assert( pExpr->x.pList->nExpr>0 );
80936 assert( pExpr->op==TK_FUNCTION );
80937 pExpr = pExpr->x.pList->a[0].pExpr;
80938 }else{
80939 assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
80940 pExpr = pExpr->pLeft;
80943 return pExpr;
80947 ** Return the collation sequence for the expression pExpr. If
80948 ** there is no defined collating sequence, return NULL.
80950 ** The collating sequence might be determined by a COLLATE operator
80951 ** or by the presence of a column with a defined collating sequence.
80952 ** COLLATE operators take first precedence. Left operands take
80953 ** precedence over right operands.
80955 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
80956 sqlite3 *db = pParse->db;
80957 CollSeq *pColl = 0;
80958 Expr *p = pExpr;
80959 while( p ){
80960 int op = p->op;
80961 if( p->flags & EP_Generic ) break;
80962 if( op==TK_CAST || op==TK_UPLUS ){
80963 p = p->pLeft;
80964 continue;
80966 if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
80967 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
80968 break;
80970 if( p->pTab!=0
80971 && (op==TK_AGG_COLUMN || op==TK_COLUMN
80972 || op==TK_REGISTER || op==TK_TRIGGER)
80974 /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
80975 ** a TK_COLUMN but was previously evaluated and cached in a register */
80976 int j = p->iColumn;
80977 if( j>=0 ){
80978 const char *zColl = p->pTab->aCol[j].zColl;
80979 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
80981 break;
80983 if( p->flags & EP_Collate ){
80984 if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
80985 p = p->pLeft;
80986 }else{
80987 p = p->pRight;
80989 }else{
80990 break;
80993 if( sqlite3CheckCollSeq(pParse, pColl) ){
80994 pColl = 0;
80996 return pColl;
81000 ** pExpr is an operand of a comparison operator. aff2 is the
81001 ** type affinity of the other operand. This routine returns the
81002 ** type affinity that should be used for the comparison operator.
81004 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
81005 char aff1 = sqlite3ExprAffinity(pExpr);
81006 if( aff1 && aff2 ){
81007 /* Both sides of the comparison are columns. If one has numeric
81008 ** affinity, use that. Otherwise use no affinity.
81010 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
81011 return SQLITE_AFF_NUMERIC;
81012 }else{
81013 return SQLITE_AFF_NONE;
81015 }else if( !aff1 && !aff2 ){
81016 /* Neither side of the comparison is a column. Compare the
81017 ** results directly.
81019 return SQLITE_AFF_NONE;
81020 }else{
81021 /* One side is a column, the other is not. Use the columns affinity. */
81022 assert( aff1==0 || aff2==0 );
81023 return (aff1 + aff2);
81028 ** pExpr is a comparison operator. Return the type affinity that should
81029 ** be applied to both operands prior to doing the comparison.
81031 static char comparisonAffinity(Expr *pExpr){
81032 char aff;
81033 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
81034 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
81035 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
81036 assert( pExpr->pLeft );
81037 aff = sqlite3ExprAffinity(pExpr->pLeft);
81038 if( pExpr->pRight ){
81039 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
81040 }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
81041 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
81042 }else if( !aff ){
81043 aff = SQLITE_AFF_NONE;
81045 return aff;
81049 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
81050 ** idx_affinity is the affinity of an indexed column. Return true
81051 ** if the index with affinity idx_affinity may be used to implement
81052 ** the comparison in pExpr.
81054 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
81055 char aff = comparisonAffinity(pExpr);
81056 switch( aff ){
81057 case SQLITE_AFF_NONE:
81058 return 1;
81059 case SQLITE_AFF_TEXT:
81060 return idx_affinity==SQLITE_AFF_TEXT;
81061 default:
81062 return sqlite3IsNumericAffinity(idx_affinity);
81067 ** Return the P5 value that should be used for a binary comparison
81068 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
81070 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
81071 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
81072 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
81073 return aff;
81077 ** Return a pointer to the collation sequence that should be used by
81078 ** a binary comparison operator comparing pLeft and pRight.
81080 ** If the left hand expression has a collating sequence type, then it is
81081 ** used. Otherwise the collation sequence for the right hand expression
81082 ** is used, or the default (BINARY) if neither expression has a collating
81083 ** type.
81085 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
81086 ** it is not considered.
81088 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
81089 Parse *pParse,
81090 Expr *pLeft,
81091 Expr *pRight
81093 CollSeq *pColl;
81094 assert( pLeft );
81095 if( pLeft->flags & EP_Collate ){
81096 pColl = sqlite3ExprCollSeq(pParse, pLeft);
81097 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
81098 pColl = sqlite3ExprCollSeq(pParse, pRight);
81099 }else{
81100 pColl = sqlite3ExprCollSeq(pParse, pLeft);
81101 if( !pColl ){
81102 pColl = sqlite3ExprCollSeq(pParse, pRight);
81105 return pColl;
81109 ** Generate code for a comparison operator.
81111 static int codeCompare(
81112 Parse *pParse, /* The parsing (and code generating) context */
81113 Expr *pLeft, /* The left operand */
81114 Expr *pRight, /* The right operand */
81115 int opcode, /* The comparison opcode */
81116 int in1, int in2, /* Register holding operands */
81117 int dest, /* Jump here if true. */
81118 int jumpIfNull /* If true, jump if either operand is NULL */
81120 int p5;
81121 int addr;
81122 CollSeq *p4;
81124 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
81125 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
81126 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
81127 (void*)p4, P4_COLLSEQ);
81128 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
81129 return addr;
81132 #if SQLITE_MAX_EXPR_DEPTH>0
81134 ** Check that argument nHeight is less than or equal to the maximum
81135 ** expression depth allowed. If it is not, leave an error message in
81136 ** pParse.
81138 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
81139 int rc = SQLITE_OK;
81140 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
81141 if( nHeight>mxHeight ){
81142 sqlite3ErrorMsg(pParse,
81143 "Expression tree is too large (maximum depth %d)", mxHeight
81145 rc = SQLITE_ERROR;
81147 return rc;
81150 /* The following three functions, heightOfExpr(), heightOfExprList()
81151 ** and heightOfSelect(), are used to determine the maximum height
81152 ** of any expression tree referenced by the structure passed as the
81153 ** first argument.
81155 ** If this maximum height is greater than the current value pointed
81156 ** to by pnHeight, the second parameter, then set *pnHeight to that
81157 ** value.
81159 static void heightOfExpr(Expr *p, int *pnHeight){
81160 if( p ){
81161 if( p->nHeight>*pnHeight ){
81162 *pnHeight = p->nHeight;
81166 static void heightOfExprList(ExprList *p, int *pnHeight){
81167 if( p ){
81168 int i;
81169 for(i=0; i<p->nExpr; i++){
81170 heightOfExpr(p->a[i].pExpr, pnHeight);
81174 static void heightOfSelect(Select *p, int *pnHeight){
81175 if( p ){
81176 heightOfExpr(p->pWhere, pnHeight);
81177 heightOfExpr(p->pHaving, pnHeight);
81178 heightOfExpr(p->pLimit, pnHeight);
81179 heightOfExpr(p->pOffset, pnHeight);
81180 heightOfExprList(p->pEList, pnHeight);
81181 heightOfExprList(p->pGroupBy, pnHeight);
81182 heightOfExprList(p->pOrderBy, pnHeight);
81183 heightOfSelect(p->pPrior, pnHeight);
81188 ** Set the Expr.nHeight variable in the structure passed as an
81189 ** argument. An expression with no children, Expr.pList or
81190 ** Expr.pSelect member has a height of 1. Any other expression
81191 ** has a height equal to the maximum height of any other
81192 ** referenced Expr plus one.
81194 static void exprSetHeight(Expr *p){
81195 int nHeight = 0;
81196 heightOfExpr(p->pLeft, &nHeight);
81197 heightOfExpr(p->pRight, &nHeight);
81198 if( ExprHasProperty(p, EP_xIsSelect) ){
81199 heightOfSelect(p->x.pSelect, &nHeight);
81200 }else{
81201 heightOfExprList(p->x.pList, &nHeight);
81203 p->nHeight = nHeight + 1;
81207 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
81208 ** the height is greater than the maximum allowed expression depth,
81209 ** leave an error in pParse.
81211 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
81212 exprSetHeight(p);
81213 sqlite3ExprCheckHeight(pParse, p->nHeight);
81217 ** Return the maximum height of any expression tree referenced
81218 ** by the select statement passed as an argument.
81220 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
81221 int nHeight = 0;
81222 heightOfSelect(p, &nHeight);
81223 return nHeight;
81225 #else
81226 #define exprSetHeight(y)
81227 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
81230 ** This routine is the core allocator for Expr nodes.
81232 ** Construct a new expression node and return a pointer to it. Memory
81233 ** for this node and for the pToken argument is a single allocation
81234 ** obtained from sqlite3DbMalloc(). The calling function
81235 ** is responsible for making sure the node eventually gets freed.
81237 ** If dequote is true, then the token (if it exists) is dequoted.
81238 ** If dequote is false, no dequoting is performance. The deQuote
81239 ** parameter is ignored if pToken is NULL or if the token does not
81240 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
81241 ** then the EP_DblQuoted flag is set on the expression node.
81243 ** Special case: If op==TK_INTEGER and pToken points to a string that
81244 ** can be translated into a 32-bit integer, then the token is not
81245 ** stored in u.zToken. Instead, the integer values is written
81246 ** into u.iValue and the EP_IntValue flag is set. No extra storage
81247 ** is allocated to hold the integer text and the dequote flag is ignored.
81249 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
81250 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
81251 int op, /* Expression opcode */
81252 const Token *pToken, /* Token argument. Might be NULL */
81253 int dequote /* True to dequote */
81255 Expr *pNew;
81256 int nExtra = 0;
81257 int iValue = 0;
81259 if( pToken ){
81260 if( op!=TK_INTEGER || pToken->z==0
81261 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
81262 nExtra = pToken->n+1;
81263 assert( iValue>=0 );
81266 pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
81267 if( pNew ){
81268 pNew->op = (u8)op;
81269 pNew->iAgg = -1;
81270 if( pToken ){
81271 if( nExtra==0 ){
81272 pNew->flags |= EP_IntValue;
81273 pNew->u.iValue = iValue;
81274 }else{
81275 int c;
81276 pNew->u.zToken = (char*)&pNew[1];
81277 assert( pToken->z!=0 || pToken->n==0 );
81278 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
81279 pNew->u.zToken[pToken->n] = 0;
81280 if( dequote && nExtra>=3
81281 && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
81282 sqlite3Dequote(pNew->u.zToken);
81283 if( c=='"' ) pNew->flags |= EP_DblQuoted;
81287 #if SQLITE_MAX_EXPR_DEPTH>0
81288 pNew->nHeight = 1;
81289 #endif
81291 return pNew;
81295 ** Allocate a new expression node from a zero-terminated token that has
81296 ** already been dequoted.
81298 SQLITE_PRIVATE Expr *sqlite3Expr(
81299 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
81300 int op, /* Expression opcode */
81301 const char *zToken /* Token argument. Might be NULL */
81303 Token x;
81304 x.z = zToken;
81305 x.n = zToken ? sqlite3Strlen30(zToken) : 0;
81306 return sqlite3ExprAlloc(db, op, &x, 0);
81310 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
81312 ** If pRoot==NULL that means that a memory allocation error has occurred.
81313 ** In that case, delete the subtrees pLeft and pRight.
81315 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
81316 sqlite3 *db,
81317 Expr *pRoot,
81318 Expr *pLeft,
81319 Expr *pRight
81321 if( pRoot==0 ){
81322 assert( db->mallocFailed );
81323 sqlite3ExprDelete(db, pLeft);
81324 sqlite3ExprDelete(db, pRight);
81325 }else{
81326 if( pRight ){
81327 pRoot->pRight = pRight;
81328 pRoot->flags |= EP_Collate & pRight->flags;
81330 if( pLeft ){
81331 pRoot->pLeft = pLeft;
81332 pRoot->flags |= EP_Collate & pLeft->flags;
81334 exprSetHeight(pRoot);
81339 ** Allocate an Expr node which joins as many as two subtrees.
81341 ** One or both of the subtrees can be NULL. Return a pointer to the new
81342 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
81343 ** free the subtrees and return NULL.
81345 SQLITE_PRIVATE Expr *sqlite3PExpr(
81346 Parse *pParse, /* Parsing context */
81347 int op, /* Expression opcode */
81348 Expr *pLeft, /* Left operand */
81349 Expr *pRight, /* Right operand */
81350 const Token *pToken /* Argument token */
81352 Expr *p;
81353 if( op==TK_AND && pLeft && pRight ){
81354 /* Take advantage of short-circuit false optimization for AND */
81355 p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
81356 }else{
81357 p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
81358 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
81360 if( p ) {
81361 sqlite3ExprCheckHeight(pParse, p->nHeight);
81363 return p;
81367 ** If the expression is always either TRUE or FALSE (respectively),
81368 ** then return 1. If one cannot determine the truth value of the
81369 ** expression at compile-time return 0.
81371 ** This is an optimization. If is OK to return 0 here even if
81372 ** the expression really is always false or false (a false negative).
81373 ** But it is a bug to return 1 if the expression might have different
81374 ** boolean values in different circumstances (a false positive.)
81376 ** Note that if the expression is part of conditional for a
81377 ** LEFT JOIN, then we cannot determine at compile-time whether or not
81378 ** is it true or false, so always return 0.
81380 static int exprAlwaysTrue(Expr *p){
81381 int v = 0;
81382 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
81383 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
81384 return v!=0;
81386 static int exprAlwaysFalse(Expr *p){
81387 int v = 0;
81388 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
81389 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
81390 return v==0;
81394 ** Join two expressions using an AND operator. If either expression is
81395 ** NULL, then just return the other expression.
81397 ** If one side or the other of the AND is known to be false, then instead
81398 ** of returning an AND expression, just return a constant expression with
81399 ** a value of false.
81401 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
81402 if( pLeft==0 ){
81403 return pRight;
81404 }else if( pRight==0 ){
81405 return pLeft;
81406 }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
81407 sqlite3ExprDelete(db, pLeft);
81408 sqlite3ExprDelete(db, pRight);
81409 return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
81410 }else{
81411 Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
81412 sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
81413 return pNew;
81418 ** Construct a new expression node for a function with multiple
81419 ** arguments.
81421 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
81422 Expr *pNew;
81423 sqlite3 *db = pParse->db;
81424 assert( pToken );
81425 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
81426 if( pNew==0 ){
81427 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
81428 return 0;
81430 pNew->x.pList = pList;
81431 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
81432 sqlite3ExprSetHeight(pParse, pNew);
81433 return pNew;
81437 ** Assign a variable number to an expression that encodes a wildcard
81438 ** in the original SQL statement.
81440 ** Wildcards consisting of a single "?" are assigned the next sequential
81441 ** variable number.
81443 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
81444 ** sure "nnn" is not too be to avoid a denial of service attack when
81445 ** the SQL statement comes from an external source.
81447 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
81448 ** as the previous instance of the same wildcard. Or if this is the first
81449 ** instance of the wildcard, the next sequential variable number is
81450 ** assigned.
81452 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
81453 sqlite3 *db = pParse->db;
81454 const char *z;
81456 if( pExpr==0 ) return;
81457 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
81458 z = pExpr->u.zToken;
81459 assert( z!=0 );
81460 assert( z[0]!=0 );
81461 if( z[1]==0 ){
81462 /* Wildcard of the form "?". Assign the next variable number */
81463 assert( z[0]=='?' );
81464 pExpr->iColumn = (ynVar)(++pParse->nVar);
81465 }else{
81466 ynVar x = 0;
81467 u32 n = sqlite3Strlen30(z);
81468 if( z[0]=='?' ){
81469 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
81470 ** use it as the variable number */
81471 i64 i;
81472 int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
81473 pExpr->iColumn = x = (ynVar)i;
81474 testcase( i==0 );
81475 testcase( i==1 );
81476 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
81477 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
81478 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
81479 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
81480 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
81481 x = 0;
81483 if( i>pParse->nVar ){
81484 pParse->nVar = (int)i;
81486 }else{
81487 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
81488 ** number as the prior appearance of the same name, or if the name
81489 ** has never appeared before, reuse the same variable number
81491 ynVar i;
81492 for(i=0; i<pParse->nzVar; i++){
81493 if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
81494 pExpr->iColumn = x = (ynVar)i+1;
81495 break;
81498 if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
81500 if( x>0 ){
81501 if( x>pParse->nzVar ){
81502 char **a;
81503 a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
81504 if( a==0 ) return; /* Error reported through db->mallocFailed */
81505 pParse->azVar = a;
81506 memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
81507 pParse->nzVar = x;
81509 if( z[0]!='?' || pParse->azVar[x-1]==0 ){
81510 sqlite3DbFree(db, pParse->azVar[x-1]);
81511 pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
81515 if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
81516 sqlite3ErrorMsg(pParse, "too many SQL variables");
81521 ** Recursively delete an expression tree.
81523 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
81524 if( p==0 ) return;
81525 /* Sanity check: Assert that the IntValue is non-negative if it exists */
81526 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
81527 if( !ExprHasProperty(p, EP_TokenOnly) ){
81528 /* The Expr.x union is never used at the same time as Expr.pRight */
81529 assert( p->x.pList==0 || p->pRight==0 );
81530 sqlite3ExprDelete(db, p->pLeft);
81531 sqlite3ExprDelete(db, p->pRight);
81532 if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
81533 if( ExprHasProperty(p, EP_xIsSelect) ){
81534 sqlite3SelectDelete(db, p->x.pSelect);
81535 }else{
81536 sqlite3ExprListDelete(db, p->x.pList);
81539 if( !ExprHasProperty(p, EP_Static) ){
81540 sqlite3DbFree(db, p);
81545 ** Return the number of bytes allocated for the expression structure
81546 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
81547 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
81549 static int exprStructSize(Expr *p){
81550 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
81551 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
81552 return EXPR_FULLSIZE;
81556 ** The dupedExpr*Size() routines each return the number of bytes required
81557 ** to store a copy of an expression or expression tree. They differ in
81558 ** how much of the tree is measured.
81560 ** dupedExprStructSize() Size of only the Expr structure
81561 ** dupedExprNodeSize() Size of Expr + space for token
81562 ** dupedExprSize() Expr + token + subtree components
81564 ***************************************************************************
81566 ** The dupedExprStructSize() function returns two values OR-ed together:
81567 ** (1) the space required for a copy of the Expr structure only and
81568 ** (2) the EP_xxx flags that indicate what the structure size should be.
81569 ** The return values is always one of:
81571 ** EXPR_FULLSIZE
81572 ** EXPR_REDUCEDSIZE | EP_Reduced
81573 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
81575 ** The size of the structure can be found by masking the return value
81576 ** of this routine with 0xfff. The flags can be found by masking the
81577 ** return value with EP_Reduced|EP_TokenOnly.
81579 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
81580 ** (unreduced) Expr objects as they or originally constructed by the parser.
81581 ** During expression analysis, extra information is computed and moved into
81582 ** later parts of teh Expr object and that extra information might get chopped
81583 ** off if the expression is reduced. Note also that it does not work to
81584 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
81585 ** to reduce a pristine expression tree from the parser. The implementation
81586 ** of dupedExprStructSize() contain multiple assert() statements that attempt
81587 ** to enforce this constraint.
81589 static int dupedExprStructSize(Expr *p, int flags){
81590 int nSize;
81591 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
81592 assert( EXPR_FULLSIZE<=0xfff );
81593 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
81594 if( 0==(flags&EXPRDUP_REDUCE) ){
81595 nSize = EXPR_FULLSIZE;
81596 }else{
81597 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
81598 assert( !ExprHasProperty(p, EP_FromJoin) );
81599 assert( !ExprHasProperty(p, EP_MemToken) );
81600 assert( !ExprHasProperty(p, EP_NoReduce) );
81601 if( p->pLeft || p->x.pList ){
81602 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
81603 }else{
81604 assert( p->pRight==0 );
81605 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
81608 return nSize;
81612 ** This function returns the space in bytes required to store the copy
81613 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
81614 ** string is defined.)
81616 static int dupedExprNodeSize(Expr *p, int flags){
81617 int nByte = dupedExprStructSize(p, flags) & 0xfff;
81618 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
81619 nByte += sqlite3Strlen30(p->u.zToken)+1;
81621 return ROUND8(nByte);
81625 ** Return the number of bytes required to create a duplicate of the
81626 ** expression passed as the first argument. The second argument is a
81627 ** mask containing EXPRDUP_XXX flags.
81629 ** The value returned includes space to create a copy of the Expr struct
81630 ** itself and the buffer referred to by Expr.u.zToken, if any.
81632 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
81633 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
81634 ** and Expr.pRight variables (but not for any structures pointed to or
81635 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
81637 static int dupedExprSize(Expr *p, int flags){
81638 int nByte = 0;
81639 if( p ){
81640 nByte = dupedExprNodeSize(p, flags);
81641 if( flags&EXPRDUP_REDUCE ){
81642 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
81645 return nByte;
81649 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
81650 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
81651 ** to store the copy of expression p, the copies of p->u.zToken
81652 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
81653 ** if any. Before returning, *pzBuffer is set to the first byte past the
81654 ** portion of the buffer copied into by this function.
81656 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
81657 Expr *pNew = 0; /* Value to return */
81658 if( p ){
81659 const int isReduced = (flags&EXPRDUP_REDUCE);
81660 u8 *zAlloc;
81661 u32 staticFlag = 0;
81663 assert( pzBuffer==0 || isReduced );
81665 /* Figure out where to write the new Expr structure. */
81666 if( pzBuffer ){
81667 zAlloc = *pzBuffer;
81668 staticFlag = EP_Static;
81669 }else{
81670 zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
81672 pNew = (Expr *)zAlloc;
81674 if( pNew ){
81675 /* Set nNewSize to the size allocated for the structure pointed to
81676 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
81677 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
81678 ** by the copy of the p->u.zToken string (if any).
81680 const unsigned nStructSize = dupedExprStructSize(p, flags);
81681 const int nNewSize = nStructSize & 0xfff;
81682 int nToken;
81683 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
81684 nToken = sqlite3Strlen30(p->u.zToken) + 1;
81685 }else{
81686 nToken = 0;
81688 if( isReduced ){
81689 assert( ExprHasProperty(p, EP_Reduced)==0 );
81690 memcpy(zAlloc, p, nNewSize);
81691 }else{
81692 int nSize = exprStructSize(p);
81693 memcpy(zAlloc, p, nSize);
81694 if( EXPR_FULLSIZE>nSize ){
81695 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
81699 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
81700 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
81701 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
81702 pNew->flags |= staticFlag;
81704 /* Copy the p->u.zToken string, if any. */
81705 if( nToken ){
81706 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
81707 memcpy(zToken, p->u.zToken, nToken);
81710 if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
81711 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
81712 if( ExprHasProperty(p, EP_xIsSelect) ){
81713 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
81714 }else{
81715 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
81719 /* Fill in pNew->pLeft and pNew->pRight. */
81720 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
81721 zAlloc += dupedExprNodeSize(p, flags);
81722 if( ExprHasProperty(pNew, EP_Reduced) ){
81723 pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
81724 pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
81726 if( pzBuffer ){
81727 *pzBuffer = zAlloc;
81729 }else{
81730 if( !ExprHasProperty(p, EP_TokenOnly) ){
81731 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
81732 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
81738 return pNew;
81742 ** Create and return a deep copy of the object passed as the second
81743 ** argument. If an OOM condition is encountered, NULL is returned
81744 ** and the db->mallocFailed flag set.
81746 #ifndef SQLITE_OMIT_CTE
81747 static With *withDup(sqlite3 *db, With *p){
81748 With *pRet = 0;
81749 if( p ){
81750 int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
81751 pRet = sqlite3DbMallocZero(db, nByte);
81752 if( pRet ){
81753 int i;
81754 pRet->nCte = p->nCte;
81755 for(i=0; i<p->nCte; i++){
81756 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
81757 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
81758 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
81762 return pRet;
81764 #else
81765 # define withDup(x,y) 0
81766 #endif
81769 ** The following group of routines make deep copies of expressions,
81770 ** expression lists, ID lists, and select statements. The copies can
81771 ** be deleted (by being passed to their respective ...Delete() routines)
81772 ** without effecting the originals.
81774 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
81775 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
81776 ** by subsequent calls to sqlite*ListAppend() routines.
81778 ** Any tables that the SrcList might point to are not duplicated.
81780 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
81781 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
81782 ** truncated version of the usual Expr structure that will be stored as
81783 ** part of the in-memory representation of the database schema.
81785 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
81786 return exprDup(db, p, flags, 0);
81788 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
81789 ExprList *pNew;
81790 struct ExprList_item *pItem, *pOldItem;
81791 int i;
81792 if( p==0 ) return 0;
81793 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
81794 if( pNew==0 ) return 0;
81795 pNew->nExpr = i = p->nExpr;
81796 if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
81797 pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) );
81798 if( pItem==0 ){
81799 sqlite3DbFree(db, pNew);
81800 return 0;
81802 pOldItem = p->a;
81803 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
81804 Expr *pOldExpr = pOldItem->pExpr;
81805 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
81806 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
81807 pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
81808 pItem->sortOrder = pOldItem->sortOrder;
81809 pItem->done = 0;
81810 pItem->bSpanIsTab = pOldItem->bSpanIsTab;
81811 pItem->u = pOldItem->u;
81813 return pNew;
81817 ** If cursors, triggers, views and subqueries are all omitted from
81818 ** the build, then none of the following routines, except for
81819 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
81820 ** called with a NULL argument.
81822 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
81823 || !defined(SQLITE_OMIT_SUBQUERY)
81824 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
81825 SrcList *pNew;
81826 int i;
81827 int nByte;
81828 if( p==0 ) return 0;
81829 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
81830 pNew = sqlite3DbMallocRaw(db, nByte );
81831 if( pNew==0 ) return 0;
81832 pNew->nSrc = pNew->nAlloc = p->nSrc;
81833 for(i=0; i<p->nSrc; i++){
81834 struct SrcList_item *pNewItem = &pNew->a[i];
81835 struct SrcList_item *pOldItem = &p->a[i];
81836 Table *pTab;
81837 pNewItem->pSchema = pOldItem->pSchema;
81838 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
81839 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
81840 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
81841 pNewItem->jointype = pOldItem->jointype;
81842 pNewItem->iCursor = pOldItem->iCursor;
81843 pNewItem->addrFillSub = pOldItem->addrFillSub;
81844 pNewItem->regReturn = pOldItem->regReturn;
81845 pNewItem->isCorrelated = pOldItem->isCorrelated;
81846 pNewItem->viaCoroutine = pOldItem->viaCoroutine;
81847 pNewItem->isRecursive = pOldItem->isRecursive;
81848 pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
81849 pNewItem->notIndexed = pOldItem->notIndexed;
81850 pNewItem->pIndex = pOldItem->pIndex;
81851 pTab = pNewItem->pTab = pOldItem->pTab;
81852 if( pTab ){
81853 pTab->nRef++;
81855 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
81856 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
81857 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
81858 pNewItem->colUsed = pOldItem->colUsed;
81860 return pNew;
81862 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
81863 IdList *pNew;
81864 int i;
81865 if( p==0 ) return 0;
81866 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
81867 if( pNew==0 ) return 0;
81868 pNew->nId = p->nId;
81869 pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
81870 if( pNew->a==0 ){
81871 sqlite3DbFree(db, pNew);
81872 return 0;
81874 /* Note that because the size of the allocation for p->a[] is not
81875 ** necessarily a power of two, sqlite3IdListAppend() may not be called
81876 ** on the duplicate created by this function. */
81877 for(i=0; i<p->nId; i++){
81878 struct IdList_item *pNewItem = &pNew->a[i];
81879 struct IdList_item *pOldItem = &p->a[i];
81880 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
81881 pNewItem->idx = pOldItem->idx;
81883 return pNew;
81885 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
81886 Select *pNew, *pPrior;
81887 if( p==0 ) return 0;
81888 pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
81889 if( pNew==0 ) return 0;
81890 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
81891 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
81892 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
81893 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
81894 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
81895 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
81896 pNew->op = p->op;
81897 pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
81898 if( pPrior ) pPrior->pNext = pNew;
81899 pNew->pNext = 0;
81900 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
81901 pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
81902 pNew->iLimit = 0;
81903 pNew->iOffset = 0;
81904 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
81905 pNew->addrOpenEphm[0] = -1;
81906 pNew->addrOpenEphm[1] = -1;
81907 pNew->nSelectRow = p->nSelectRow;
81908 pNew->pWith = withDup(db, p->pWith);
81909 sqlite3SelectSetName(pNew, p->zSelName);
81910 return pNew;
81912 #else
81913 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
81914 assert( p==0 );
81915 return 0;
81917 #endif
81921 ** Add a new element to the end of an expression list. If pList is
81922 ** initially NULL, then create a new expression list.
81924 ** If a memory allocation error occurs, the entire list is freed and
81925 ** NULL is returned. If non-NULL is returned, then it is guaranteed
81926 ** that the new entry was successfully appended.
81928 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
81929 Parse *pParse, /* Parsing context */
81930 ExprList *pList, /* List to which to append. Might be NULL */
81931 Expr *pExpr /* Expression to be appended. Might be NULL */
81933 sqlite3 *db = pParse->db;
81934 if( pList==0 ){
81935 pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
81936 if( pList==0 ){
81937 goto no_mem;
81939 pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
81940 if( pList->a==0 ) goto no_mem;
81941 }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
81942 struct ExprList_item *a;
81943 assert( pList->nExpr>0 );
81944 a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
81945 if( a==0 ){
81946 goto no_mem;
81948 pList->a = a;
81950 assert( pList->a!=0 );
81951 if( 1 ){
81952 struct ExprList_item *pItem = &pList->a[pList->nExpr++];
81953 memset(pItem, 0, sizeof(*pItem));
81954 pItem->pExpr = pExpr;
81956 return pList;
81958 no_mem:
81959 /* Avoid leaking memory if malloc has failed. */
81960 sqlite3ExprDelete(db, pExpr);
81961 sqlite3ExprListDelete(db, pList);
81962 return 0;
81966 ** Set the ExprList.a[].zName element of the most recently added item
81967 ** on the expression list.
81969 ** pList might be NULL following an OOM error. But pName should never be
81970 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
81971 ** is set.
81973 SQLITE_PRIVATE void sqlite3ExprListSetName(
81974 Parse *pParse, /* Parsing context */
81975 ExprList *pList, /* List to which to add the span. */
81976 Token *pName, /* Name to be added */
81977 int dequote /* True to cause the name to be dequoted */
81979 assert( pList!=0 || pParse->db->mallocFailed!=0 );
81980 if( pList ){
81981 struct ExprList_item *pItem;
81982 assert( pList->nExpr>0 );
81983 pItem = &pList->a[pList->nExpr-1];
81984 assert( pItem->zName==0 );
81985 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
81986 if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
81991 ** Set the ExprList.a[].zSpan element of the most recently added item
81992 ** on the expression list.
81994 ** pList might be NULL following an OOM error. But pSpan should never be
81995 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
81996 ** is set.
81998 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
81999 Parse *pParse, /* Parsing context */
82000 ExprList *pList, /* List to which to add the span. */
82001 ExprSpan *pSpan /* The span to be added */
82003 sqlite3 *db = pParse->db;
82004 assert( pList!=0 || db->mallocFailed!=0 );
82005 if( pList ){
82006 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
82007 assert( pList->nExpr>0 );
82008 assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
82009 sqlite3DbFree(db, pItem->zSpan);
82010 pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
82011 (int)(pSpan->zEnd - pSpan->zStart));
82016 ** If the expression list pEList contains more than iLimit elements,
82017 ** leave an error message in pParse.
82019 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
82020 Parse *pParse,
82021 ExprList *pEList,
82022 const char *zObject
82024 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
82025 testcase( pEList && pEList->nExpr==mx );
82026 testcase( pEList && pEList->nExpr==mx+1 );
82027 if( pEList && pEList->nExpr>mx ){
82028 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
82033 ** Delete an entire expression list.
82035 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
82036 int i;
82037 struct ExprList_item *pItem;
82038 if( pList==0 ) return;
82039 assert( pList->a!=0 || pList->nExpr==0 );
82040 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
82041 sqlite3ExprDelete(db, pItem->pExpr);
82042 sqlite3DbFree(db, pItem->zName);
82043 sqlite3DbFree(db, pItem->zSpan);
82045 sqlite3DbFree(db, pList->a);
82046 sqlite3DbFree(db, pList);
82050 ** These routines are Walker callbacks. Walker.u.pi is a pointer
82051 ** to an integer. These routines are checking an expression to see
82052 ** if it is a constant. Set *Walker.u.i to 0 if the expression is
82053 ** not constant.
82055 ** These callback routines are used to implement the following:
82057 ** sqlite3ExprIsConstant() pWalker->u.i==1
82058 ** sqlite3ExprIsConstantNotJoin() pWalker->u.i==2
82059 ** sqlite3ExprIsConstantOrFunction() pWalker->u.i==3 or 4
82061 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
82062 ** in a CREATE TABLE statement. The Walker.u.i value is 4 when parsing
82063 ** an existing schema and 3 when processing a new statement. A bound
82064 ** parameter raises an error for new statements, but is silently converted
82065 ** to NULL for existing schemas. This allows sqlite_master tables that
82066 ** contain a bound parameter because they were generated by older versions
82067 ** of SQLite to be parsed by newer versions of SQLite without raising a
82068 ** malformed schema error.
82070 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
82072 /* If pWalker->u.i is 2 then any term of the expression that comes from
82073 ** the ON or USING clauses of a join disqualifies the expression
82074 ** from being considered constant. */
82075 if( pWalker->u.i==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
82076 pWalker->u.i = 0;
82077 return WRC_Abort;
82080 switch( pExpr->op ){
82081 /* Consider functions to be constant if all their arguments are constant
82082 ** and either pWalker->u.i==3 or 4 or the function as the SQLITE_FUNC_CONST
82083 ** flag. */
82084 case TK_FUNCTION:
82085 if( pWalker->u.i>=3 || ExprHasProperty(pExpr,EP_Constant) ){
82086 return WRC_Continue;
82088 /* Fall through */
82089 case TK_ID:
82090 case TK_COLUMN:
82091 case TK_AGG_FUNCTION:
82092 case TK_AGG_COLUMN:
82093 testcase( pExpr->op==TK_ID );
82094 testcase( pExpr->op==TK_COLUMN );
82095 testcase( pExpr->op==TK_AGG_FUNCTION );
82096 testcase( pExpr->op==TK_AGG_COLUMN );
82097 pWalker->u.i = 0;
82098 return WRC_Abort;
82099 case TK_VARIABLE:
82100 if( pWalker->u.i==4 ){
82101 /* Silently convert bound parameters that appear inside of CREATE
82102 ** statements into a NULL when parsing the CREATE statement text out
82103 ** of the sqlite_master table */
82104 pExpr->op = TK_NULL;
82105 }else if( pWalker->u.i==3 ){
82106 /* A bound parameter in a CREATE statement that originates from
82107 ** sqlite3_prepare() causes an error */
82108 pWalker->u.i = 0;
82109 return WRC_Abort;
82111 /* Fall through */
82112 default:
82113 testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
82114 testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
82115 return WRC_Continue;
82118 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
82119 UNUSED_PARAMETER(NotUsed);
82120 pWalker->u.i = 0;
82121 return WRC_Abort;
82123 static int exprIsConst(Expr *p, int initFlag){
82124 Walker w;
82125 memset(&w, 0, sizeof(w));
82126 w.u.i = initFlag;
82127 w.xExprCallback = exprNodeIsConstant;
82128 w.xSelectCallback = selectNodeIsConstant;
82129 sqlite3WalkExpr(&w, p);
82130 return w.u.i;
82134 ** Walk an expression tree. Return 1 if the expression is constant
82135 ** and 0 if it involves variables or function calls.
82137 ** For the purposes of this function, a double-quoted string (ex: "abc")
82138 ** is considered a variable but a single-quoted string (ex: 'abc') is
82139 ** a constant.
82141 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
82142 return exprIsConst(p, 1);
82146 ** Walk an expression tree. Return 1 if the expression is constant
82147 ** that does no originate from the ON or USING clauses of a join.
82148 ** Return 0 if it involves variables or function calls or terms from
82149 ** an ON or USING clause.
82151 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
82152 return exprIsConst(p, 2);
82156 ** Walk an expression tree. Return 1 if the expression is constant
82157 ** or a function call with constant arguments. Return and 0 if there
82158 ** are any variables.
82160 ** For the purposes of this function, a double-quoted string (ex: "abc")
82161 ** is considered a variable but a single-quoted string (ex: 'abc') is
82162 ** a constant.
82164 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
82165 assert( isInit==0 || isInit==1 );
82166 return exprIsConst(p, 3+isInit);
82170 ** If the expression p codes a constant integer that is small enough
82171 ** to fit in a 32-bit integer, return 1 and put the value of the integer
82172 ** in *pValue. If the expression is not an integer or if it is too big
82173 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
82175 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
82176 int rc = 0;
82178 /* If an expression is an integer literal that fits in a signed 32-bit
82179 ** integer, then the EP_IntValue flag will have already been set */
82180 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
82181 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
82183 if( p->flags & EP_IntValue ){
82184 *pValue = p->u.iValue;
82185 return 1;
82187 switch( p->op ){
82188 case TK_UPLUS: {
82189 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
82190 break;
82192 case TK_UMINUS: {
82193 int v;
82194 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
82195 assert( v!=(-2147483647-1) );
82196 *pValue = -v;
82197 rc = 1;
82199 break;
82201 default: break;
82203 return rc;
82207 ** Return FALSE if there is no chance that the expression can be NULL.
82209 ** If the expression might be NULL or if the expression is too complex
82210 ** to tell return TRUE.
82212 ** This routine is used as an optimization, to skip OP_IsNull opcodes
82213 ** when we know that a value cannot be NULL. Hence, a false positive
82214 ** (returning TRUE when in fact the expression can never be NULL) might
82215 ** be a small performance hit but is otherwise harmless. On the other
82216 ** hand, a false negative (returning FALSE when the result could be NULL)
82217 ** will likely result in an incorrect answer. So when in doubt, return
82218 ** TRUE.
82220 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
82221 u8 op;
82222 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
82223 op = p->op;
82224 if( op==TK_REGISTER ) op = p->op2;
82225 switch( op ){
82226 case TK_INTEGER:
82227 case TK_STRING:
82228 case TK_FLOAT:
82229 case TK_BLOB:
82230 return 0;
82231 case TK_COLUMN:
82232 assert( p->pTab!=0 );
82233 return ExprHasProperty(p, EP_CanBeNull) ||
82234 (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
82235 default:
82236 return 1;
82241 ** Return TRUE if the given expression is a constant which would be
82242 ** unchanged by OP_Affinity with the affinity given in the second
82243 ** argument.
82245 ** This routine is used to determine if the OP_Affinity operation
82246 ** can be omitted. When in doubt return FALSE. A false negative
82247 ** is harmless. A false positive, however, can result in the wrong
82248 ** answer.
82250 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
82251 u8 op;
82252 if( aff==SQLITE_AFF_NONE ) return 1;
82253 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
82254 op = p->op;
82255 if( op==TK_REGISTER ) op = p->op2;
82256 switch( op ){
82257 case TK_INTEGER: {
82258 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
82260 case TK_FLOAT: {
82261 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
82263 case TK_STRING: {
82264 return aff==SQLITE_AFF_TEXT;
82266 case TK_BLOB: {
82267 return 1;
82269 case TK_COLUMN: {
82270 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
82271 return p->iColumn<0
82272 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
82274 default: {
82275 return 0;
82281 ** Return TRUE if the given string is a row-id column name.
82283 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
82284 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
82285 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
82286 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
82287 return 0;
82291 ** Return true if we are able to the IN operator optimization on a
82292 ** query of the form
82294 ** x IN (SELECT ...)
82296 ** Where the SELECT... clause is as specified by the parameter to this
82297 ** routine.
82299 ** The Select object passed in has already been preprocessed and no
82300 ** errors have been found.
82302 #ifndef SQLITE_OMIT_SUBQUERY
82303 static int isCandidateForInOpt(Select *p){
82304 SrcList *pSrc;
82305 ExprList *pEList;
82306 Table *pTab;
82307 if( p==0 ) return 0; /* right-hand side of IN is SELECT */
82308 if( p->pPrior ) return 0; /* Not a compound SELECT */
82309 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
82310 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
82311 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
82312 return 0; /* No DISTINCT keyword and no aggregate functions */
82314 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
82315 if( p->pLimit ) return 0; /* Has no LIMIT clause */
82316 assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
82317 if( p->pWhere ) return 0; /* Has no WHERE clause */
82318 pSrc = p->pSrc;
82319 assert( pSrc!=0 );
82320 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
82321 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
82322 pTab = pSrc->a[0].pTab;
82323 if( NEVER(pTab==0) ) return 0;
82324 assert( pTab->pSelect==0 ); /* FROM clause is not a view */
82325 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
82326 pEList = p->pEList;
82327 if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
82328 if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
82329 return 1;
82331 #endif /* SQLITE_OMIT_SUBQUERY */
82334 ** Code an OP_Once instruction and allocate space for its flag. Return the
82335 ** address of the new instruction.
82337 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
82338 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
82339 return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
82343 ** Generate code that checks the left-most column of index table iCur to see if
82344 ** it contains any NULL entries. Cause the register at regHasNull to be set
82345 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
82346 ** to be set to NULL if iCur contains one or more NULL values.
82348 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
82349 int j1;
82350 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
82351 j1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
82352 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
82353 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
82354 VdbeComment((v, "first_entry_in(%d)", iCur));
82355 sqlite3VdbeJumpHere(v, j1);
82359 #ifndef SQLITE_OMIT_SUBQUERY
82361 ** The argument is an IN operator with a list (not a subquery) on the
82362 ** right-hand side. Return TRUE if that list is constant.
82364 static int sqlite3InRhsIsConstant(Expr *pIn){
82365 Expr *pLHS;
82366 int res;
82367 assert( !ExprHasProperty(pIn, EP_xIsSelect) );
82368 pLHS = pIn->pLeft;
82369 pIn->pLeft = 0;
82370 res = sqlite3ExprIsConstant(pIn);
82371 pIn->pLeft = pLHS;
82372 return res;
82374 #endif
82377 ** This function is used by the implementation of the IN (...) operator.
82378 ** The pX parameter is the expression on the RHS of the IN operator, which
82379 ** might be either a list of expressions or a subquery.
82381 ** The job of this routine is to find or create a b-tree object that can
82382 ** be used either to test for membership in the RHS set or to iterate through
82383 ** all members of the RHS set, skipping duplicates.
82385 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
82386 ** and pX->iTable is set to the index of that cursor.
82388 ** The returned value of this function indicates the b-tree type, as follows:
82390 ** IN_INDEX_ROWID - The cursor was opened on a database table.
82391 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
82392 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
82393 ** IN_INDEX_EPH - The cursor was opened on a specially created and
82394 ** populated epheremal table.
82395 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
82396 ** implemented as a sequence of comparisons.
82398 ** An existing b-tree might be used if the RHS expression pX is a simple
82399 ** subquery such as:
82401 ** SELECT <column> FROM <table>
82403 ** If the RHS of the IN operator is a list or a more complex subquery, then
82404 ** an ephemeral table might need to be generated from the RHS and then
82405 ** pX->iTable made to point to the ephemeral table instead of an
82406 ** existing table.
82408 ** The inFlags parameter must contain exactly one of the bits
82409 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
82410 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
82411 ** fast membership test. When the IN_INDEX_LOOP bit is set, the
82412 ** IN index will be used to loop over all values of the RHS of the
82413 ** IN operator.
82415 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
82416 ** through the set members) then the b-tree must not contain duplicates.
82417 ** An epheremal table must be used unless the selected <column> is guaranteed
82418 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
82419 ** has a UNIQUE constraint or UNIQUE index.
82421 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
82422 ** for fast set membership tests) then an epheremal table must
82423 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
82424 ** be found with <column> as its left-most column.
82426 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
82427 ** if the RHS of the IN operator is a list (not a subquery) then this
82428 ** routine might decide that creating an ephemeral b-tree for membership
82429 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
82430 ** calling routine should implement the IN operator using a sequence
82431 ** of Eq or Ne comparison operations.
82433 ** When the b-tree is being used for membership tests, the calling function
82434 ** might need to know whether or not the RHS side of the IN operator
82435 ** contains a NULL. If prRhsHasNull is not a NULL pointer and
82436 ** if there is any chance that the (...) might contain a NULL value at
82437 ** runtime, then a register is allocated and the register number written
82438 ** to *prRhsHasNull. If there is no chance that the (...) contains a
82439 ** NULL value, then *prRhsHasNull is left unchanged.
82441 ** If a register is allocated and its location stored in *prRhsHasNull, then
82442 ** the value in that register will be NULL if the b-tree contains one or more
82443 ** NULL values, and it will be some non-NULL value if the b-tree contains no
82444 ** NULL values.
82446 #ifndef SQLITE_OMIT_SUBQUERY
82447 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
82448 Select *p; /* SELECT to the right of IN operator */
82449 int eType = 0; /* Type of RHS table. IN_INDEX_* */
82450 int iTab = pParse->nTab++; /* Cursor of the RHS table */
82451 int mustBeUnique; /* True if RHS must be unique */
82452 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
82454 assert( pX->op==TK_IN );
82455 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
82457 /* Check to see if an existing table or index can be used to
82458 ** satisfy the query. This is preferable to generating a new
82459 ** ephemeral table.
82461 p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
82462 if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
82463 sqlite3 *db = pParse->db; /* Database connection */
82464 Table *pTab; /* Table <table>. */
82465 Expr *pExpr; /* Expression <column> */
82466 i16 iCol; /* Index of column <column> */
82467 i16 iDb; /* Database idx for pTab */
82469 assert( p ); /* Because of isCandidateForInOpt(p) */
82470 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
82471 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
82472 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
82473 pTab = p->pSrc->a[0].pTab;
82474 pExpr = p->pEList->a[0].pExpr;
82475 iCol = (i16)pExpr->iColumn;
82477 /* Code an OP_Transaction and OP_TableLock for <table>. */
82478 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
82479 sqlite3CodeVerifySchema(pParse, iDb);
82480 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
82482 /* This function is only called from two places. In both cases the vdbe
82483 ** has already been allocated. So assume sqlite3GetVdbe() is always
82484 ** successful here.
82486 assert(v);
82487 if( iCol<0 ){
82488 int iAddr = sqlite3CodeOnce(pParse);
82489 VdbeCoverage(v);
82491 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
82492 eType = IN_INDEX_ROWID;
82494 sqlite3VdbeJumpHere(v, iAddr);
82495 }else{
82496 Index *pIdx; /* Iterator variable */
82498 /* The collation sequence used by the comparison. If an index is to
82499 ** be used in place of a temp-table, it must be ordered according
82500 ** to this collation sequence. */
82501 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
82503 /* Check that the affinity that will be used to perform the
82504 ** comparison is the same as the affinity of the column. If
82505 ** it is not, it is not possible to use any index.
82507 int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
82509 for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
82510 if( (pIdx->aiColumn[0]==iCol)
82511 && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
82512 && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
82514 int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
82515 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
82516 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
82517 VdbeComment((v, "%s", pIdx->zName));
82518 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
82519 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
82521 if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
82522 *prRhsHasNull = ++pParse->nMem;
82523 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
82525 sqlite3VdbeJumpHere(v, iAddr);
82531 /* If no preexisting index is available for the IN clause
82532 ** and IN_INDEX_NOOP is an allowed reply
82533 ** and the RHS of the IN operator is a list, not a subquery
82534 ** and the RHS is not contant or has two or fewer terms,
82535 ** then it is not worth creating an ephemeral table to evaluate
82536 ** the IN operator so return IN_INDEX_NOOP.
82538 if( eType==0
82539 && (inFlags & IN_INDEX_NOOP_OK)
82540 && !ExprHasProperty(pX, EP_xIsSelect)
82541 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
82543 eType = IN_INDEX_NOOP;
82547 if( eType==0 ){
82548 /* Could not find an existing table or index to use as the RHS b-tree.
82549 ** We will have to generate an ephemeral table to do the job.
82551 u32 savedNQueryLoop = pParse->nQueryLoop;
82552 int rMayHaveNull = 0;
82553 eType = IN_INDEX_EPH;
82554 if( inFlags & IN_INDEX_LOOP ){
82555 pParse->nQueryLoop = 0;
82556 if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
82557 eType = IN_INDEX_ROWID;
82559 }else if( prRhsHasNull ){
82560 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
82562 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
82563 pParse->nQueryLoop = savedNQueryLoop;
82564 }else{
82565 pX->iTable = iTab;
82567 return eType;
82569 #endif
82572 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
82573 ** or IN operators. Examples:
82575 ** (SELECT a FROM b) -- subquery
82576 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
82577 ** x IN (4,5,11) -- IN operator with list on right-hand side
82578 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
82580 ** The pExpr parameter describes the expression that contains the IN
82581 ** operator or subquery.
82583 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
82584 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
82585 ** to some integer key column of a table B-Tree. In this case, use an
82586 ** intkey B-Tree to store the set of IN(...) values instead of the usual
82587 ** (slower) variable length keys B-Tree.
82589 ** If rMayHaveNull is non-zero, that means that the operation is an IN
82590 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
82591 ** All this routine does is initialize the register given by rMayHaveNull
82592 ** to NULL. Calling routines will take care of changing this register
82593 ** value to non-NULL if the RHS is NULL-free.
82595 ** For a SELECT or EXISTS operator, return the register that holds the
82596 ** result. For IN operators or if an error occurs, the return value is 0.
82598 #ifndef SQLITE_OMIT_SUBQUERY
82599 SQLITE_PRIVATE int sqlite3CodeSubselect(
82600 Parse *pParse, /* Parsing context */
82601 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
82602 int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
82603 int isRowid /* If true, LHS of IN operator is a rowid */
82605 int jmpIfDynamic = -1; /* One-time test address */
82606 int rReg = 0; /* Register storing resulting */
82607 Vdbe *v = sqlite3GetVdbe(pParse);
82608 if( NEVER(v==0) ) return 0;
82609 sqlite3ExprCachePush(pParse);
82611 /* This code must be run in its entirety every time it is encountered
82612 ** if any of the following is true:
82614 ** * The right-hand side is a correlated subquery
82615 ** * The right-hand side is an expression list containing variables
82616 ** * We are inside a trigger
82618 ** If all of the above are false, then we can run this code just once
82619 ** save the results, and reuse the same result on subsequent invocations.
82621 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
82622 jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
82625 #ifndef SQLITE_OMIT_EXPLAIN
82626 if( pParse->explain==2 ){
82627 char *zMsg = sqlite3MPrintf(
82628 pParse->db, "EXECUTE %s%s SUBQUERY %d", jmpIfDynamic>=0?"":"CORRELATED ",
82629 pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
82631 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
82633 #endif
82635 switch( pExpr->op ){
82636 case TK_IN: {
82637 char affinity; /* Affinity of the LHS of the IN */
82638 int addr; /* Address of OP_OpenEphemeral instruction */
82639 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
82640 KeyInfo *pKeyInfo = 0; /* Key information */
82642 affinity = sqlite3ExprAffinity(pLeft);
82644 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
82645 ** expression it is handled the same way. An ephemeral table is
82646 ** filled with single-field index keys representing the results
82647 ** from the SELECT or the <exprlist>.
82649 ** If the 'x' expression is a column value, or the SELECT...
82650 ** statement returns a column value, then the affinity of that
82651 ** column is used to build the index keys. If both 'x' and the
82652 ** SELECT... statement are columns, then numeric affinity is used
82653 ** if either column has NUMERIC or INTEGER affinity. If neither
82654 ** 'x' nor the SELECT... statement are columns, then numeric affinity
82655 ** is used.
82657 pExpr->iTable = pParse->nTab++;
82658 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
82659 pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
82661 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
82662 /* Case 1: expr IN (SELECT ...)
82664 ** Generate code to write the results of the select into the temporary
82665 ** table allocated and opened above.
82667 Select *pSelect = pExpr->x.pSelect;
82668 SelectDest dest;
82669 ExprList *pEList;
82671 assert( !isRowid );
82672 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
82673 dest.affSdst = (u8)affinity;
82674 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
82675 pSelect->iLimit = 0;
82676 testcase( pSelect->selFlags & SF_Distinct );
82677 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
82678 if( sqlite3Select(pParse, pSelect, &dest) ){
82679 sqlite3KeyInfoUnref(pKeyInfo);
82680 return 0;
82682 pEList = pSelect->pEList;
82683 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
82684 assert( pEList!=0 );
82685 assert( pEList->nExpr>0 );
82686 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
82687 pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
82688 pEList->a[0].pExpr);
82689 }else if( ALWAYS(pExpr->x.pList!=0) ){
82690 /* Case 2: expr IN (exprlist)
82692 ** For each expression, build an index key from the evaluation and
82693 ** store it in the temporary table. If <expr> is a column, then use
82694 ** that columns affinity when building index keys. If <expr> is not
82695 ** a column, use numeric affinity.
82697 int i;
82698 ExprList *pList = pExpr->x.pList;
82699 struct ExprList_item *pItem;
82700 int r1, r2, r3;
82702 if( !affinity ){
82703 affinity = SQLITE_AFF_NONE;
82705 if( pKeyInfo ){
82706 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
82707 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
82710 /* Loop through each expression in <exprlist>. */
82711 r1 = sqlite3GetTempReg(pParse);
82712 r2 = sqlite3GetTempReg(pParse);
82713 if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
82714 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
82715 Expr *pE2 = pItem->pExpr;
82716 int iValToIns;
82718 /* If the expression is not constant then we will need to
82719 ** disable the test that was generated above that makes sure
82720 ** this code only executes once. Because for a non-constant
82721 ** expression we need to rerun this code each time.
82723 if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
82724 sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
82725 jmpIfDynamic = -1;
82728 /* Evaluate the expression and insert it into the temp table */
82729 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
82730 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
82731 }else{
82732 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
82733 if( isRowid ){
82734 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
82735 sqlite3VdbeCurrentAddr(v)+2);
82736 VdbeCoverage(v);
82737 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
82738 }else{
82739 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
82740 sqlite3ExprCacheAffinityChange(pParse, r3, 1);
82741 sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
82745 sqlite3ReleaseTempReg(pParse, r1);
82746 sqlite3ReleaseTempReg(pParse, r2);
82748 if( pKeyInfo ){
82749 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
82751 break;
82754 case TK_EXISTS:
82755 case TK_SELECT:
82756 default: {
82757 /* If this has to be a scalar SELECT. Generate code to put the
82758 ** value of this select in a memory cell and record the number
82759 ** of the memory cell in iColumn. If this is an EXISTS, write
82760 ** an integer 0 (not exists) or 1 (exists) into a memory cell
82761 ** and record that memory cell in iColumn.
82763 Select *pSel; /* SELECT statement to encode */
82764 SelectDest dest; /* How to deal with SELECt result */
82766 testcase( pExpr->op==TK_EXISTS );
82767 testcase( pExpr->op==TK_SELECT );
82768 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
82770 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
82771 pSel = pExpr->x.pSelect;
82772 sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
82773 if( pExpr->op==TK_SELECT ){
82774 dest.eDest = SRT_Mem;
82775 dest.iSdst = dest.iSDParm;
82776 sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
82777 VdbeComment((v, "Init subquery result"));
82778 }else{
82779 dest.eDest = SRT_Exists;
82780 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
82781 VdbeComment((v, "Init EXISTS result"));
82783 sqlite3ExprDelete(pParse->db, pSel->pLimit);
82784 pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
82785 &sqlite3IntTokens[1]);
82786 pSel->iLimit = 0;
82787 if( sqlite3Select(pParse, pSel, &dest) ){
82788 return 0;
82790 rReg = dest.iSDParm;
82791 ExprSetVVAProperty(pExpr, EP_NoReduce);
82792 break;
82796 if( rHasNullFlag ){
82797 sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
82800 if( jmpIfDynamic>=0 ){
82801 sqlite3VdbeJumpHere(v, jmpIfDynamic);
82803 sqlite3ExprCachePop(pParse);
82805 return rReg;
82807 #endif /* SQLITE_OMIT_SUBQUERY */
82809 #ifndef SQLITE_OMIT_SUBQUERY
82811 ** Generate code for an IN expression.
82813 ** x IN (SELECT ...)
82814 ** x IN (value, value, ...)
82816 ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
82817 ** is an array of zero or more values. The expression is true if the LHS is
82818 ** contained within the RHS. The value of the expression is unknown (NULL)
82819 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
82820 ** RHS contains one or more NULL values.
82822 ** This routine generates code that jumps to destIfFalse if the LHS is not
82823 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
82824 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
82825 ** within the RHS then fall through.
82827 static void sqlite3ExprCodeIN(
82828 Parse *pParse, /* Parsing and code generating context */
82829 Expr *pExpr, /* The IN expression */
82830 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
82831 int destIfNull /* Jump here if the results are unknown due to NULLs */
82833 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
82834 char affinity; /* Comparison affinity to use */
82835 int eType; /* Type of the RHS */
82836 int r1; /* Temporary use register */
82837 Vdbe *v; /* Statement under construction */
82839 /* Compute the RHS. After this step, the table with cursor
82840 ** pExpr->iTable will contains the values that make up the RHS.
82842 v = pParse->pVdbe;
82843 assert( v!=0 ); /* OOM detected prior to this routine */
82844 VdbeNoopComment((v, "begin IN expr"));
82845 eType = sqlite3FindInIndex(pParse, pExpr,
82846 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
82847 destIfFalse==destIfNull ? 0 : &rRhsHasNull);
82849 /* Figure out the affinity to use to create a key from the results
82850 ** of the expression. affinityStr stores a static string suitable for
82851 ** P4 of OP_MakeRecord.
82853 affinity = comparisonAffinity(pExpr);
82855 /* Code the LHS, the <expr> from "<expr> IN (...)".
82857 sqlite3ExprCachePush(pParse);
82858 r1 = sqlite3GetTempReg(pParse);
82859 sqlite3ExprCode(pParse, pExpr->pLeft, r1);
82861 /* If sqlite3FindInIndex() did not find or create an index that is
82862 ** suitable for evaluating the IN operator, then evaluate using a
82863 ** sequence of comparisons.
82865 if( eType==IN_INDEX_NOOP ){
82866 ExprList *pList = pExpr->x.pList;
82867 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
82868 int labelOk = sqlite3VdbeMakeLabel(v);
82869 int r2, regToFree;
82870 int regCkNull = 0;
82871 int ii;
82872 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
82873 if( destIfNull!=destIfFalse ){
82874 regCkNull = sqlite3GetTempReg(pParse);
82875 sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
82877 for(ii=0; ii<pList->nExpr; ii++){
82878 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
82879 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
82880 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
82882 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
82883 sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
82884 (void*)pColl, P4_COLLSEQ);
82885 VdbeCoverageIf(v, ii<pList->nExpr-1);
82886 VdbeCoverageIf(v, ii==pList->nExpr-1);
82887 sqlite3VdbeChangeP5(v, affinity);
82888 }else{
82889 assert( destIfNull==destIfFalse );
82890 sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
82891 (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
82892 sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
82894 sqlite3ReleaseTempReg(pParse, regToFree);
82896 if( regCkNull ){
82897 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
82898 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
82900 sqlite3VdbeResolveLabel(v, labelOk);
82901 sqlite3ReleaseTempReg(pParse, regCkNull);
82902 }else{
82904 /* If the LHS is NULL, then the result is either false or NULL depending
82905 ** on whether the RHS is empty or not, respectively.
82907 if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
82908 if( destIfNull==destIfFalse ){
82909 /* Shortcut for the common case where the false and NULL outcomes are
82910 ** the same. */
82911 sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
82912 }else{
82913 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
82914 sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
82915 VdbeCoverage(v);
82916 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
82917 sqlite3VdbeJumpHere(v, addr1);
82921 if( eType==IN_INDEX_ROWID ){
82922 /* In this case, the RHS is the ROWID of table b-tree
82924 sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
82925 sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
82926 VdbeCoverage(v);
82927 }else{
82928 /* In this case, the RHS is an index b-tree.
82930 sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
82932 /* If the set membership test fails, then the result of the
82933 ** "x IN (...)" expression must be either 0 or NULL. If the set
82934 ** contains no NULL values, then the result is 0. If the set
82935 ** contains one or more NULL values, then the result of the
82936 ** expression is also NULL.
82938 assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
82939 if( rRhsHasNull==0 ){
82940 /* This branch runs if it is known at compile time that the RHS
82941 ** cannot contain NULL values. This happens as the result
82942 ** of a "NOT NULL" constraint in the database schema.
82944 ** Also run this branch if NULL is equivalent to FALSE
82945 ** for this particular IN operator.
82947 sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
82948 VdbeCoverage(v);
82949 }else{
82950 /* In this branch, the RHS of the IN might contain a NULL and
82951 ** the presence of a NULL on the RHS makes a difference in the
82952 ** outcome.
82954 int j1;
82956 /* First check to see if the LHS is contained in the RHS. If so,
82957 ** then the answer is TRUE the presence of NULLs in the RHS does
82958 ** not matter. If the LHS is not contained in the RHS, then the
82959 ** answer is NULL if the RHS contains NULLs and the answer is
82960 ** FALSE if the RHS is NULL-free.
82962 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
82963 VdbeCoverage(v);
82964 sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
82965 VdbeCoverage(v);
82966 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
82967 sqlite3VdbeJumpHere(v, j1);
82971 sqlite3ReleaseTempReg(pParse, r1);
82972 sqlite3ExprCachePop(pParse);
82973 VdbeComment((v, "end IN expr"));
82975 #endif /* SQLITE_OMIT_SUBQUERY */
82978 ** Duplicate an 8-byte value
82980 static char *dup8bytes(Vdbe *v, const char *in){
82981 char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
82982 if( out ){
82983 memcpy(out, in, 8);
82985 return out;
82988 #ifndef SQLITE_OMIT_FLOATING_POINT
82990 ** Generate an instruction that will put the floating point
82991 ** value described by z[0..n-1] into register iMem.
82993 ** The z[] string will probably not be zero-terminated. But the
82994 ** z[n] character is guaranteed to be something that does not look
82995 ** like the continuation of the number.
82997 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
82998 if( ALWAYS(z!=0) ){
82999 double value;
83000 char *zV;
83001 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
83002 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
83003 if( negateFlag ) value = -value;
83004 zV = dup8bytes(v, (char*)&value);
83005 sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
83008 #endif
83012 ** Generate an instruction that will put the integer describe by
83013 ** text z[0..n-1] into register iMem.
83015 ** Expr.u.zToken is always UTF8 and zero-terminated.
83017 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
83018 Vdbe *v = pParse->pVdbe;
83019 if( pExpr->flags & EP_IntValue ){
83020 int i = pExpr->u.iValue;
83021 assert( i>=0 );
83022 if( negFlag ) i = -i;
83023 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
83024 }else{
83025 int c;
83026 i64 value;
83027 const char *z = pExpr->u.zToken;
83028 assert( z!=0 );
83029 c = sqlite3DecOrHexToI64(z, &value);
83030 if( c==0 || (c==2 && negFlag) ){
83031 char *zV;
83032 if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
83033 zV = dup8bytes(v, (char*)&value);
83034 sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
83035 }else{
83036 #ifdef SQLITE_OMIT_FLOATING_POINT
83037 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
83038 #else
83039 #ifndef SQLITE_OMIT_HEX_INTEGER
83040 if( sqlite3_strnicmp(z,"0x",2)==0 ){
83041 sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
83042 }else
83043 #endif
83045 codeReal(v, z, negFlag, iMem);
83047 #endif
83053 ** Clear a cache entry.
83055 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
83056 if( p->tempReg ){
83057 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
83058 pParse->aTempReg[pParse->nTempReg++] = p->iReg;
83060 p->tempReg = 0;
83066 ** Record in the column cache that a particular column from a
83067 ** particular table is stored in a particular register.
83069 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
83070 int i;
83071 int minLru;
83072 int idxLru;
83073 struct yColCache *p;
83075 assert( iReg>0 ); /* Register numbers are always positive */
83076 assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
83078 /* The SQLITE_ColumnCache flag disables the column cache. This is used
83079 ** for testing only - to verify that SQLite always gets the same answer
83080 ** with and without the column cache.
83082 if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
83084 /* First replace any existing entry.
83086 ** Actually, the way the column cache is currently used, we are guaranteed
83087 ** that the object will never already be in cache. Verify this guarantee.
83089 #ifndef NDEBUG
83090 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83091 assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
83093 #endif
83095 /* Find an empty slot and replace it */
83096 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83097 if( p->iReg==0 ){
83098 p->iLevel = pParse->iCacheLevel;
83099 p->iTable = iTab;
83100 p->iColumn = iCol;
83101 p->iReg = iReg;
83102 p->tempReg = 0;
83103 p->lru = pParse->iCacheCnt++;
83104 return;
83108 /* Replace the last recently used */
83109 minLru = 0x7fffffff;
83110 idxLru = -1;
83111 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83112 if( p->lru<minLru ){
83113 idxLru = i;
83114 minLru = p->lru;
83117 if( ALWAYS(idxLru>=0) ){
83118 p = &pParse->aColCache[idxLru];
83119 p->iLevel = pParse->iCacheLevel;
83120 p->iTable = iTab;
83121 p->iColumn = iCol;
83122 p->iReg = iReg;
83123 p->tempReg = 0;
83124 p->lru = pParse->iCacheCnt++;
83125 return;
83130 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
83131 ** Purge the range of registers from the column cache.
83133 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
83134 int i;
83135 int iLast = iReg + nReg - 1;
83136 struct yColCache *p;
83137 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83138 int r = p->iReg;
83139 if( r>=iReg && r<=iLast ){
83140 cacheEntryClear(pParse, p);
83141 p->iReg = 0;
83147 ** Remember the current column cache context. Any new entries added
83148 ** added to the column cache after this call are removed when the
83149 ** corresponding pop occurs.
83151 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
83152 pParse->iCacheLevel++;
83153 #ifdef SQLITE_DEBUG
83154 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
83155 printf("PUSH to %d\n", pParse->iCacheLevel);
83157 #endif
83161 ** Remove from the column cache any entries that were added since the
83162 ** the previous sqlite3ExprCachePush operation. In other words, restore
83163 ** the cache to the state it was in prior the most recent Push.
83165 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
83166 int i;
83167 struct yColCache *p;
83168 assert( pParse->iCacheLevel>=1 );
83169 pParse->iCacheLevel--;
83170 #ifdef SQLITE_DEBUG
83171 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
83172 printf("POP to %d\n", pParse->iCacheLevel);
83174 #endif
83175 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83176 if( p->iReg && p->iLevel>pParse->iCacheLevel ){
83177 cacheEntryClear(pParse, p);
83178 p->iReg = 0;
83184 ** When a cached column is reused, make sure that its register is
83185 ** no longer available as a temp register. ticket #3879: that same
83186 ** register might be in the cache in multiple places, so be sure to
83187 ** get them all.
83189 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
83190 int i;
83191 struct yColCache *p;
83192 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83193 if( p->iReg==iReg ){
83194 p->tempReg = 0;
83200 ** Generate code to extract the value of the iCol-th column of a table.
83202 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
83203 Vdbe *v, /* The VDBE under construction */
83204 Table *pTab, /* The table containing the value */
83205 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
83206 int iCol, /* Index of the column to extract */
83207 int regOut /* Extract the value into this register */
83209 if( iCol<0 || iCol==pTab->iPKey ){
83210 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
83211 }else{
83212 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
83213 int x = iCol;
83214 if( !HasRowid(pTab) ){
83215 x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
83217 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
83219 if( iCol>=0 ){
83220 sqlite3ColumnDefault(v, pTab, iCol, regOut);
83225 ** Generate code that will extract the iColumn-th column from
83226 ** table pTab and store the column value in a register. An effort
83227 ** is made to store the column value in register iReg, but this is
83228 ** not guaranteed. The location of the column value is returned.
83230 ** There must be an open cursor to pTab in iTable when this routine
83231 ** is called. If iColumn<0 then code is generated that extracts the rowid.
83233 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
83234 Parse *pParse, /* Parsing and code generating context */
83235 Table *pTab, /* Description of the table we are reading from */
83236 int iColumn, /* Index of the table column */
83237 int iTable, /* The cursor pointing to the table */
83238 int iReg, /* Store results here */
83239 u8 p5 /* P5 value for OP_Column */
83241 Vdbe *v = pParse->pVdbe;
83242 int i;
83243 struct yColCache *p;
83245 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83246 if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
83247 p->lru = pParse->iCacheCnt++;
83248 sqlite3ExprCachePinRegister(pParse, p->iReg);
83249 return p->iReg;
83252 assert( v!=0 );
83253 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
83254 if( p5 ){
83255 sqlite3VdbeChangeP5(v, p5);
83256 }else{
83257 sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
83259 return iReg;
83263 ** Clear all column cache entries.
83265 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
83266 int i;
83267 struct yColCache *p;
83269 #if SQLITE_DEBUG
83270 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
83271 printf("CLEAR\n");
83273 #endif
83274 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83275 if( p->iReg ){
83276 cacheEntryClear(pParse, p);
83277 p->iReg = 0;
83283 ** Record the fact that an affinity change has occurred on iCount
83284 ** registers starting with iStart.
83286 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
83287 sqlite3ExprCacheRemove(pParse, iStart, iCount);
83291 ** Generate code to move content from registers iFrom...iFrom+nReg-1
83292 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
83294 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
83295 assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
83296 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
83297 sqlite3ExprCacheRemove(pParse, iFrom, nReg);
83300 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
83302 ** Return true if any register in the range iFrom..iTo (inclusive)
83303 ** is used as part of the column cache.
83305 ** This routine is used within assert() and testcase() macros only
83306 ** and does not appear in a normal build.
83308 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
83309 int i;
83310 struct yColCache *p;
83311 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83312 int r = p->iReg;
83313 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
83315 return 0;
83317 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
83320 ** Convert an expression node to a TK_REGISTER
83322 static void exprToRegister(Expr *p, int iReg){
83323 p->op2 = p->op;
83324 p->op = TK_REGISTER;
83325 p->iTable = iReg;
83326 ExprClearProperty(p, EP_Skip);
83330 ** Generate code into the current Vdbe to evaluate the given
83331 ** expression. Attempt to store the results in register "target".
83332 ** Return the register where results are stored.
83334 ** With this routine, there is no guarantee that results will
83335 ** be stored in target. The result might be stored in some other
83336 ** register if it is convenient to do so. The calling function
83337 ** must check the return code and move the results to the desired
83338 ** register.
83340 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
83341 Vdbe *v = pParse->pVdbe; /* The VM under construction */
83342 int op; /* The opcode being coded */
83343 int inReg = target; /* Results stored in register inReg */
83344 int regFree1 = 0; /* If non-zero free this temporary register */
83345 int regFree2 = 0; /* If non-zero free this temporary register */
83346 int r1, r2, r3, r4; /* Various register numbers */
83347 sqlite3 *db = pParse->db; /* The database connection */
83348 Expr tempX; /* Temporary expression node */
83350 assert( target>0 && target<=pParse->nMem );
83351 if( v==0 ){
83352 assert( pParse->db->mallocFailed );
83353 return 0;
83356 if( pExpr==0 ){
83357 op = TK_NULL;
83358 }else{
83359 op = pExpr->op;
83361 switch( op ){
83362 case TK_AGG_COLUMN: {
83363 AggInfo *pAggInfo = pExpr->pAggInfo;
83364 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
83365 if( !pAggInfo->directMode ){
83366 assert( pCol->iMem>0 );
83367 inReg = pCol->iMem;
83368 break;
83369 }else if( pAggInfo->useSortingIdx ){
83370 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
83371 pCol->iSorterColumn, target);
83372 break;
83374 /* Otherwise, fall thru into the TK_COLUMN case */
83376 case TK_COLUMN: {
83377 int iTab = pExpr->iTable;
83378 if( iTab<0 ){
83379 if( pParse->ckBase>0 ){
83380 /* Generating CHECK constraints or inserting into partial index */
83381 inReg = pExpr->iColumn + pParse->ckBase;
83382 break;
83383 }else{
83384 /* Deleting from a partial index */
83385 iTab = pParse->iPartIdxTab;
83388 inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
83389 pExpr->iColumn, iTab, target,
83390 pExpr->op2);
83391 break;
83393 case TK_INTEGER: {
83394 codeInteger(pParse, pExpr, 0, target);
83395 break;
83397 #ifndef SQLITE_OMIT_FLOATING_POINT
83398 case TK_FLOAT: {
83399 assert( !ExprHasProperty(pExpr, EP_IntValue) );
83400 codeReal(v, pExpr->u.zToken, 0, target);
83401 break;
83403 #endif
83404 case TK_STRING: {
83405 assert( !ExprHasProperty(pExpr, EP_IntValue) );
83406 sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
83407 break;
83409 case TK_NULL: {
83410 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
83411 break;
83413 #ifndef SQLITE_OMIT_BLOB_LITERAL
83414 case TK_BLOB: {
83415 int n;
83416 const char *z;
83417 char *zBlob;
83418 assert( !ExprHasProperty(pExpr, EP_IntValue) );
83419 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
83420 assert( pExpr->u.zToken[1]=='\'' );
83421 z = &pExpr->u.zToken[2];
83422 n = sqlite3Strlen30(z) - 1;
83423 assert( z[n]=='\'' );
83424 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
83425 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
83426 break;
83428 #endif
83429 case TK_VARIABLE: {
83430 assert( !ExprHasProperty(pExpr, EP_IntValue) );
83431 assert( pExpr->u.zToken!=0 );
83432 assert( pExpr->u.zToken[0]!=0 );
83433 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
83434 if( pExpr->u.zToken[1]!=0 ){
83435 assert( pExpr->u.zToken[0]=='?'
83436 || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
83437 sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
83439 break;
83441 case TK_REGISTER: {
83442 inReg = pExpr->iTable;
83443 break;
83445 case TK_AS: {
83446 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
83447 break;
83449 #ifndef SQLITE_OMIT_CAST
83450 case TK_CAST: {
83451 /* Expressions of the form: CAST(pLeft AS token) */
83452 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
83453 if( inReg!=target ){
83454 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
83455 inReg = target;
83457 sqlite3VdbeAddOp2(v, OP_Cast, target,
83458 sqlite3AffinityType(pExpr->u.zToken, 0));
83459 testcase( usedAsColumnCache(pParse, inReg, inReg) );
83460 sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
83461 break;
83463 #endif /* SQLITE_OMIT_CAST */
83464 case TK_LT:
83465 case TK_LE:
83466 case TK_GT:
83467 case TK_GE:
83468 case TK_NE:
83469 case TK_EQ: {
83470 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
83471 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
83472 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
83473 r1, r2, inReg, SQLITE_STOREP2);
83474 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
83475 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
83476 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
83477 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
83478 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
83479 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
83480 testcase( regFree1==0 );
83481 testcase( regFree2==0 );
83482 break;
83484 case TK_IS:
83485 case TK_ISNOT: {
83486 testcase( op==TK_IS );
83487 testcase( op==TK_ISNOT );
83488 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
83489 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
83490 op = (op==TK_IS) ? TK_EQ : TK_NE;
83491 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
83492 r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
83493 VdbeCoverageIf(v, op==TK_EQ);
83494 VdbeCoverageIf(v, op==TK_NE);
83495 testcase( regFree1==0 );
83496 testcase( regFree2==0 );
83497 break;
83499 case TK_AND:
83500 case TK_OR:
83501 case TK_PLUS:
83502 case TK_STAR:
83503 case TK_MINUS:
83504 case TK_REM:
83505 case TK_BITAND:
83506 case TK_BITOR:
83507 case TK_SLASH:
83508 case TK_LSHIFT:
83509 case TK_RSHIFT:
83510 case TK_CONCAT: {
83511 assert( TK_AND==OP_And ); testcase( op==TK_AND );
83512 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
83513 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
83514 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
83515 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
83516 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
83517 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
83518 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
83519 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
83520 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
83521 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
83522 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
83523 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
83524 sqlite3VdbeAddOp3(v, op, r2, r1, target);
83525 testcase( regFree1==0 );
83526 testcase( regFree2==0 );
83527 break;
83529 case TK_UMINUS: {
83530 Expr *pLeft = pExpr->pLeft;
83531 assert( pLeft );
83532 if( pLeft->op==TK_INTEGER ){
83533 codeInteger(pParse, pLeft, 1, target);
83534 #ifndef SQLITE_OMIT_FLOATING_POINT
83535 }else if( pLeft->op==TK_FLOAT ){
83536 assert( !ExprHasProperty(pExpr, EP_IntValue) );
83537 codeReal(v, pLeft->u.zToken, 1, target);
83538 #endif
83539 }else{
83540 tempX.op = TK_INTEGER;
83541 tempX.flags = EP_IntValue|EP_TokenOnly;
83542 tempX.u.iValue = 0;
83543 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
83544 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
83545 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
83546 testcase( regFree2==0 );
83548 inReg = target;
83549 break;
83551 case TK_BITNOT:
83552 case TK_NOT: {
83553 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
83554 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
83555 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
83556 testcase( regFree1==0 );
83557 inReg = target;
83558 sqlite3VdbeAddOp2(v, op, r1, inReg);
83559 break;
83561 case TK_ISNULL:
83562 case TK_NOTNULL: {
83563 int addr;
83564 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
83565 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
83566 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
83567 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
83568 testcase( regFree1==0 );
83569 addr = sqlite3VdbeAddOp1(v, op, r1);
83570 VdbeCoverageIf(v, op==TK_ISNULL);
83571 VdbeCoverageIf(v, op==TK_NOTNULL);
83572 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
83573 sqlite3VdbeJumpHere(v, addr);
83574 break;
83576 case TK_AGG_FUNCTION: {
83577 AggInfo *pInfo = pExpr->pAggInfo;
83578 if( pInfo==0 ){
83579 assert( !ExprHasProperty(pExpr, EP_IntValue) );
83580 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
83581 }else{
83582 inReg = pInfo->aFunc[pExpr->iAgg].iMem;
83584 break;
83586 case TK_FUNCTION: {
83587 ExprList *pFarg; /* List of function arguments */
83588 int nFarg; /* Number of function arguments */
83589 FuncDef *pDef; /* The function definition object */
83590 int nId; /* Length of the function name in bytes */
83591 const char *zId; /* The function name */
83592 u32 constMask = 0; /* Mask of function arguments that are constant */
83593 int i; /* Loop counter */
83594 u8 enc = ENC(db); /* The text encoding used by this database */
83595 CollSeq *pColl = 0; /* A collating sequence */
83597 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
83598 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
83599 pFarg = 0;
83600 }else{
83601 pFarg = pExpr->x.pList;
83603 nFarg = pFarg ? pFarg->nExpr : 0;
83604 assert( !ExprHasProperty(pExpr, EP_IntValue) );
83605 zId = pExpr->u.zToken;
83606 nId = sqlite3Strlen30(zId);
83607 pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
83608 if( pDef==0 || pDef->xFunc==0 ){
83609 sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
83610 break;
83613 /* Attempt a direct implementation of the built-in COALESCE() and
83614 ** IFNULL() functions. This avoids unnecessary evaluation of
83615 ** arguments past the first non-NULL argument.
83617 if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
83618 int endCoalesce = sqlite3VdbeMakeLabel(v);
83619 assert( nFarg>=2 );
83620 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
83621 for(i=1; i<nFarg; i++){
83622 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
83623 VdbeCoverage(v);
83624 sqlite3ExprCacheRemove(pParse, target, 1);
83625 sqlite3ExprCachePush(pParse);
83626 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
83627 sqlite3ExprCachePop(pParse);
83629 sqlite3VdbeResolveLabel(v, endCoalesce);
83630 break;
83633 /* The UNLIKELY() function is a no-op. The result is the value
83634 ** of the first argument.
83636 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
83637 assert( nFarg>=1 );
83638 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
83639 break;
83642 for(i=0; i<nFarg; i++){
83643 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
83644 testcase( i==31 );
83645 constMask |= MASKBIT32(i);
83647 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
83648 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
83651 if( pFarg ){
83652 if( constMask ){
83653 r1 = pParse->nMem+1;
83654 pParse->nMem += nFarg;
83655 }else{
83656 r1 = sqlite3GetTempRange(pParse, nFarg);
83659 /* For length() and typeof() functions with a column argument,
83660 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
83661 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
83662 ** loading.
83664 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
83665 u8 exprOp;
83666 assert( nFarg==1 );
83667 assert( pFarg->a[0].pExpr!=0 );
83668 exprOp = pFarg->a[0].pExpr->op;
83669 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
83670 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
83671 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
83672 testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
83673 pFarg->a[0].pExpr->op2 =
83674 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
83678 sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
83679 sqlite3ExprCodeExprList(pParse, pFarg, r1,
83680 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
83681 sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
83682 }else{
83683 r1 = 0;
83685 #ifndef SQLITE_OMIT_VIRTUALTABLE
83686 /* Possibly overload the function if the first argument is
83687 ** a virtual table column.
83689 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
83690 ** second argument, not the first, as the argument to test to
83691 ** see if it is a column in a virtual table. This is done because
83692 ** the left operand of infix functions (the operand we want to
83693 ** control overloading) ends up as the second argument to the
83694 ** function. The expression "A glob B" is equivalent to
83695 ** "glob(B,A). We want to use the A in "A glob B" to test
83696 ** for function overloading. But we use the B term in "glob(B,A)".
83698 if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
83699 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
83700 }else if( nFarg>0 ){
83701 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
83703 #endif
83704 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
83705 if( !pColl ) pColl = db->pDfltColl;
83706 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
83708 sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
83709 (char*)pDef, P4_FUNCDEF);
83710 sqlite3VdbeChangeP5(v, (u8)nFarg);
83711 if( nFarg && constMask==0 ){
83712 sqlite3ReleaseTempRange(pParse, r1, nFarg);
83714 break;
83716 #ifndef SQLITE_OMIT_SUBQUERY
83717 case TK_EXISTS:
83718 case TK_SELECT: {
83719 testcase( op==TK_EXISTS );
83720 testcase( op==TK_SELECT );
83721 inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
83722 break;
83724 case TK_IN: {
83725 int destIfFalse = sqlite3VdbeMakeLabel(v);
83726 int destIfNull = sqlite3VdbeMakeLabel(v);
83727 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
83728 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
83729 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
83730 sqlite3VdbeResolveLabel(v, destIfFalse);
83731 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
83732 sqlite3VdbeResolveLabel(v, destIfNull);
83733 break;
83735 #endif /* SQLITE_OMIT_SUBQUERY */
83739 ** x BETWEEN y AND z
83741 ** This is equivalent to
83743 ** x>=y AND x<=z
83745 ** X is stored in pExpr->pLeft.
83746 ** Y is stored in pExpr->pList->a[0].pExpr.
83747 ** Z is stored in pExpr->pList->a[1].pExpr.
83749 case TK_BETWEEN: {
83750 Expr *pLeft = pExpr->pLeft;
83751 struct ExprList_item *pLItem = pExpr->x.pList->a;
83752 Expr *pRight = pLItem->pExpr;
83754 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
83755 r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
83756 testcase( regFree1==0 );
83757 testcase( regFree2==0 );
83758 r3 = sqlite3GetTempReg(pParse);
83759 r4 = sqlite3GetTempReg(pParse);
83760 codeCompare(pParse, pLeft, pRight, OP_Ge,
83761 r1, r2, r3, SQLITE_STOREP2); VdbeCoverage(v);
83762 pLItem++;
83763 pRight = pLItem->pExpr;
83764 sqlite3ReleaseTempReg(pParse, regFree2);
83765 r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
83766 testcase( regFree2==0 );
83767 codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
83768 VdbeCoverage(v);
83769 sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
83770 sqlite3ReleaseTempReg(pParse, r3);
83771 sqlite3ReleaseTempReg(pParse, r4);
83772 break;
83774 case TK_COLLATE:
83775 case TK_UPLUS: {
83776 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
83777 break;
83780 case TK_TRIGGER: {
83781 /* If the opcode is TK_TRIGGER, then the expression is a reference
83782 ** to a column in the new.* or old.* pseudo-tables available to
83783 ** trigger programs. In this case Expr.iTable is set to 1 for the
83784 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
83785 ** is set to the column of the pseudo-table to read, or to -1 to
83786 ** read the rowid field.
83788 ** The expression is implemented using an OP_Param opcode. The p1
83789 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
83790 ** to reference another column of the old.* pseudo-table, where
83791 ** i is the index of the column. For a new.rowid reference, p1 is
83792 ** set to (n+1), where n is the number of columns in each pseudo-table.
83793 ** For a reference to any other column in the new.* pseudo-table, p1
83794 ** is set to (n+2+i), where n and i are as defined previously. For
83795 ** example, if the table on which triggers are being fired is
83796 ** declared as:
83798 ** CREATE TABLE t1(a, b);
83800 ** Then p1 is interpreted as follows:
83802 ** p1==0 -> old.rowid p1==3 -> new.rowid
83803 ** p1==1 -> old.a p1==4 -> new.a
83804 ** p1==2 -> old.b p1==5 -> new.b
83806 Table *pTab = pExpr->pTab;
83807 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
83809 assert( pExpr->iTable==0 || pExpr->iTable==1 );
83810 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
83811 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
83812 assert( p1>=0 && p1<(pTab->nCol*2+2) );
83814 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
83815 VdbeComment((v, "%s.%s -> $%d",
83816 (pExpr->iTable ? "new" : "old"),
83817 (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
83818 target
83821 #ifndef SQLITE_OMIT_FLOATING_POINT
83822 /* If the column has REAL affinity, it may currently be stored as an
83823 ** integer. Use OP_RealAffinity to make sure it is really real. */
83824 if( pExpr->iColumn>=0
83825 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
83827 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
83829 #endif
83830 break;
83835 ** Form A:
83836 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
83838 ** Form B:
83839 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
83841 ** Form A is can be transformed into the equivalent form B as follows:
83842 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
83843 ** WHEN x=eN THEN rN ELSE y END
83845 ** X (if it exists) is in pExpr->pLeft.
83846 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
83847 ** odd. The Y is also optional. If the number of elements in x.pList
83848 ** is even, then Y is omitted and the "otherwise" result is NULL.
83849 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
83851 ** The result of the expression is the Ri for the first matching Ei,
83852 ** or if there is no matching Ei, the ELSE term Y, or if there is
83853 ** no ELSE term, NULL.
83855 default: assert( op==TK_CASE ); {
83856 int endLabel; /* GOTO label for end of CASE stmt */
83857 int nextCase; /* GOTO label for next WHEN clause */
83858 int nExpr; /* 2x number of WHEN terms */
83859 int i; /* Loop counter */
83860 ExprList *pEList; /* List of WHEN terms */
83861 struct ExprList_item *aListelem; /* Array of WHEN terms */
83862 Expr opCompare; /* The X==Ei expression */
83863 Expr *pX; /* The X expression */
83864 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
83865 VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
83867 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
83868 assert(pExpr->x.pList->nExpr > 0);
83869 pEList = pExpr->x.pList;
83870 aListelem = pEList->a;
83871 nExpr = pEList->nExpr;
83872 endLabel = sqlite3VdbeMakeLabel(v);
83873 if( (pX = pExpr->pLeft)!=0 ){
83874 tempX = *pX;
83875 testcase( pX->op==TK_COLUMN );
83876 exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
83877 testcase( regFree1==0 );
83878 opCompare.op = TK_EQ;
83879 opCompare.pLeft = &tempX;
83880 pTest = &opCompare;
83881 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
83882 ** The value in regFree1 might get SCopy-ed into the file result.
83883 ** So make sure that the regFree1 register is not reused for other
83884 ** purposes and possibly overwritten. */
83885 regFree1 = 0;
83887 for(i=0; i<nExpr-1; i=i+2){
83888 sqlite3ExprCachePush(pParse);
83889 if( pX ){
83890 assert( pTest!=0 );
83891 opCompare.pRight = aListelem[i].pExpr;
83892 }else{
83893 pTest = aListelem[i].pExpr;
83895 nextCase = sqlite3VdbeMakeLabel(v);
83896 testcase( pTest->op==TK_COLUMN );
83897 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
83898 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
83899 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
83900 sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
83901 sqlite3ExprCachePop(pParse);
83902 sqlite3VdbeResolveLabel(v, nextCase);
83904 if( (nExpr&1)!=0 ){
83905 sqlite3ExprCachePush(pParse);
83906 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
83907 sqlite3ExprCachePop(pParse);
83908 }else{
83909 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
83911 assert( db->mallocFailed || pParse->nErr>0
83912 || pParse->iCacheLevel==iCacheLevel );
83913 sqlite3VdbeResolveLabel(v, endLabel);
83914 break;
83916 #ifndef SQLITE_OMIT_TRIGGER
83917 case TK_RAISE: {
83918 assert( pExpr->affinity==OE_Rollback
83919 || pExpr->affinity==OE_Abort
83920 || pExpr->affinity==OE_Fail
83921 || pExpr->affinity==OE_Ignore
83923 if( !pParse->pTriggerTab ){
83924 sqlite3ErrorMsg(pParse,
83925 "RAISE() may only be used within a trigger-program");
83926 return 0;
83928 if( pExpr->affinity==OE_Abort ){
83929 sqlite3MayAbort(pParse);
83931 assert( !ExprHasProperty(pExpr, EP_IntValue) );
83932 if( pExpr->affinity==OE_Ignore ){
83933 sqlite3VdbeAddOp4(
83934 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
83935 VdbeCoverage(v);
83936 }else{
83937 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
83938 pExpr->affinity, pExpr->u.zToken, 0, 0);
83941 break;
83943 #endif
83945 sqlite3ReleaseTempReg(pParse, regFree1);
83946 sqlite3ReleaseTempReg(pParse, regFree2);
83947 return inReg;
83951 ** Factor out the code of the given expression to initialization time.
83953 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
83954 Parse *pParse, /* Parsing context */
83955 Expr *pExpr, /* The expression to code when the VDBE initializes */
83956 int regDest, /* Store the value in this register */
83957 u8 reusable /* True if this expression is reusable */
83959 ExprList *p;
83960 assert( ConstFactorOk(pParse) );
83961 p = pParse->pConstExpr;
83962 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
83963 p = sqlite3ExprListAppend(pParse, p, pExpr);
83964 if( p ){
83965 struct ExprList_item *pItem = &p->a[p->nExpr-1];
83966 pItem->u.iConstExprReg = regDest;
83967 pItem->reusable = reusable;
83969 pParse->pConstExpr = p;
83973 ** Generate code to evaluate an expression and store the results
83974 ** into a register. Return the register number where the results
83975 ** are stored.
83977 ** If the register is a temporary register that can be deallocated,
83978 ** then write its number into *pReg. If the result register is not
83979 ** a temporary, then set *pReg to zero.
83981 ** If pExpr is a constant, then this routine might generate this
83982 ** code to fill the register in the initialization section of the
83983 ** VDBE program, in order to factor it out of the evaluation loop.
83985 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
83986 int r2;
83987 pExpr = sqlite3ExprSkipCollate(pExpr);
83988 if( ConstFactorOk(pParse)
83989 && pExpr->op!=TK_REGISTER
83990 && sqlite3ExprIsConstantNotJoin(pExpr)
83992 ExprList *p = pParse->pConstExpr;
83993 int i;
83994 *pReg = 0;
83995 if( p ){
83996 struct ExprList_item *pItem;
83997 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
83998 if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
83999 return pItem->u.iConstExprReg;
84003 r2 = ++pParse->nMem;
84004 sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
84005 }else{
84006 int r1 = sqlite3GetTempReg(pParse);
84007 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
84008 if( r2==r1 ){
84009 *pReg = r1;
84010 }else{
84011 sqlite3ReleaseTempReg(pParse, r1);
84012 *pReg = 0;
84015 return r2;
84019 ** Generate code that will evaluate expression pExpr and store the
84020 ** results in register target. The results are guaranteed to appear
84021 ** in register target.
84023 SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
84024 int inReg;
84026 assert( target>0 && target<=pParse->nMem );
84027 if( pExpr && pExpr->op==TK_REGISTER ){
84028 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
84029 }else{
84030 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
84031 assert( pParse->pVdbe || pParse->db->mallocFailed );
84032 if( inReg!=target && pParse->pVdbe ){
84033 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
84039 ** Generate code that will evaluate expression pExpr and store the
84040 ** results in register target. The results are guaranteed to appear
84041 ** in register target. If the expression is constant, then this routine
84042 ** might choose to code the expression at initialization time.
84044 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
84045 if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
84046 sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
84047 }else{
84048 sqlite3ExprCode(pParse, pExpr, target);
84053 ** Generate code that evaluates the given expression and puts the result
84054 ** in register target.
84056 ** Also make a copy of the expression results into another "cache" register
84057 ** and modify the expression so that the next time it is evaluated,
84058 ** the result is a copy of the cache register.
84060 ** This routine is used for expressions that are used multiple
84061 ** times. They are evaluated once and the results of the expression
84062 ** are reused.
84064 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
84065 Vdbe *v = pParse->pVdbe;
84066 int iMem;
84068 assert( target>0 );
84069 assert( pExpr->op!=TK_REGISTER );
84070 sqlite3ExprCode(pParse, pExpr, target);
84071 iMem = ++pParse->nMem;
84072 sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
84073 exprToRegister(pExpr, iMem);
84076 #ifdef SQLITE_DEBUG
84078 ** Generate a human-readable explanation of an expression tree.
84080 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
84081 const char *zBinOp = 0; /* Binary operator */
84082 const char *zUniOp = 0; /* Unary operator */
84083 pView = sqlite3TreeViewPush(pView, moreToFollow);
84084 if( pExpr==0 ){
84085 sqlite3TreeViewLine(pView, "nil");
84086 sqlite3TreeViewPop(pView);
84087 return;
84089 switch( pExpr->op ){
84090 case TK_AGG_COLUMN: {
84091 sqlite3TreeViewLine(pView, "AGG{%d:%d}",
84092 pExpr->iTable, pExpr->iColumn);
84093 break;
84095 case TK_COLUMN: {
84096 if( pExpr->iTable<0 ){
84097 /* This only happens when coding check constraints */
84098 sqlite3TreeViewLine(pView, "COLUMN(%d)", pExpr->iColumn);
84099 }else{
84100 sqlite3TreeViewLine(pView, "{%d:%d}",
84101 pExpr->iTable, pExpr->iColumn);
84103 break;
84105 case TK_INTEGER: {
84106 if( pExpr->flags & EP_IntValue ){
84107 sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
84108 }else{
84109 sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
84111 break;
84113 #ifndef SQLITE_OMIT_FLOATING_POINT
84114 case TK_FLOAT: {
84115 sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
84116 break;
84118 #endif
84119 case TK_STRING: {
84120 sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
84121 break;
84123 case TK_NULL: {
84124 sqlite3TreeViewLine(pView,"NULL");
84125 break;
84127 #ifndef SQLITE_OMIT_BLOB_LITERAL
84128 case TK_BLOB: {
84129 sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
84130 break;
84132 #endif
84133 case TK_VARIABLE: {
84134 sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
84135 pExpr->u.zToken, pExpr->iColumn);
84136 break;
84138 case TK_REGISTER: {
84139 sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
84140 break;
84142 case TK_AS: {
84143 sqlite3TreeViewLine(pView,"AS %Q", pExpr->u.zToken);
84144 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
84145 break;
84147 case TK_ID: {
84148 sqlite3TreeViewLine(pView,"ID %Q", pExpr->u.zToken);
84149 break;
84151 #ifndef SQLITE_OMIT_CAST
84152 case TK_CAST: {
84153 /* Expressions of the form: CAST(pLeft AS token) */
84154 sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
84155 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
84156 break;
84158 #endif /* SQLITE_OMIT_CAST */
84159 case TK_LT: zBinOp = "LT"; break;
84160 case TK_LE: zBinOp = "LE"; break;
84161 case TK_GT: zBinOp = "GT"; break;
84162 case TK_GE: zBinOp = "GE"; break;
84163 case TK_NE: zBinOp = "NE"; break;
84164 case TK_EQ: zBinOp = "EQ"; break;
84165 case TK_IS: zBinOp = "IS"; break;
84166 case TK_ISNOT: zBinOp = "ISNOT"; break;
84167 case TK_AND: zBinOp = "AND"; break;
84168 case TK_OR: zBinOp = "OR"; break;
84169 case TK_PLUS: zBinOp = "ADD"; break;
84170 case TK_STAR: zBinOp = "MUL"; break;
84171 case TK_MINUS: zBinOp = "SUB"; break;
84172 case TK_REM: zBinOp = "REM"; break;
84173 case TK_BITAND: zBinOp = "BITAND"; break;
84174 case TK_BITOR: zBinOp = "BITOR"; break;
84175 case TK_SLASH: zBinOp = "DIV"; break;
84176 case TK_LSHIFT: zBinOp = "LSHIFT"; break;
84177 case TK_RSHIFT: zBinOp = "RSHIFT"; break;
84178 case TK_CONCAT: zBinOp = "CONCAT"; break;
84179 case TK_DOT: zBinOp = "DOT"; break;
84181 case TK_UMINUS: zUniOp = "UMINUS"; break;
84182 case TK_UPLUS: zUniOp = "UPLUS"; break;
84183 case TK_BITNOT: zUniOp = "BITNOT"; break;
84184 case TK_NOT: zUniOp = "NOT"; break;
84185 case TK_ISNULL: zUniOp = "ISNULL"; break;
84186 case TK_NOTNULL: zUniOp = "NOTNULL"; break;
84188 case TK_COLLATE: {
84189 sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
84190 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
84191 break;
84194 case TK_AGG_FUNCTION:
84195 case TK_FUNCTION: {
84196 ExprList *pFarg; /* List of function arguments */
84197 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
84198 pFarg = 0;
84199 }else{
84200 pFarg = pExpr->x.pList;
84202 if( pExpr->op==TK_AGG_FUNCTION ){
84203 sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
84204 pExpr->op2, pExpr->u.zToken);
84205 }else{
84206 sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
84208 if( pFarg ){
84209 sqlite3TreeViewExprList(pView, pFarg, 0, 0);
84211 break;
84213 #ifndef SQLITE_OMIT_SUBQUERY
84214 case TK_EXISTS: {
84215 sqlite3TreeViewLine(pView, "EXISTS-expr");
84216 sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
84217 break;
84219 case TK_SELECT: {
84220 sqlite3TreeViewLine(pView, "SELECT-expr");
84221 sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
84222 break;
84224 case TK_IN: {
84225 sqlite3TreeViewLine(pView, "IN");
84226 sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
84227 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
84228 sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
84229 }else{
84230 sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
84232 break;
84234 #endif /* SQLITE_OMIT_SUBQUERY */
84237 ** x BETWEEN y AND z
84239 ** This is equivalent to
84241 ** x>=y AND x<=z
84243 ** X is stored in pExpr->pLeft.
84244 ** Y is stored in pExpr->pList->a[0].pExpr.
84245 ** Z is stored in pExpr->pList->a[1].pExpr.
84247 case TK_BETWEEN: {
84248 Expr *pX = pExpr->pLeft;
84249 Expr *pY = pExpr->x.pList->a[0].pExpr;
84250 Expr *pZ = pExpr->x.pList->a[1].pExpr;
84251 sqlite3TreeViewLine(pView, "BETWEEN");
84252 sqlite3TreeViewExpr(pView, pX, 1);
84253 sqlite3TreeViewExpr(pView, pY, 1);
84254 sqlite3TreeViewExpr(pView, pZ, 0);
84255 break;
84257 case TK_TRIGGER: {
84258 /* If the opcode is TK_TRIGGER, then the expression is a reference
84259 ** to a column in the new.* or old.* pseudo-tables available to
84260 ** trigger programs. In this case Expr.iTable is set to 1 for the
84261 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
84262 ** is set to the column of the pseudo-table to read, or to -1 to
84263 ** read the rowid field.
84265 sqlite3TreeViewLine(pView, "%s(%d)",
84266 pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
84267 break;
84269 case TK_CASE: {
84270 sqlite3TreeViewLine(pView, "CASE");
84271 sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
84272 sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
84273 break;
84275 #ifndef SQLITE_OMIT_TRIGGER
84276 case TK_RAISE: {
84277 const char *zType = "unk";
84278 switch( pExpr->affinity ){
84279 case OE_Rollback: zType = "rollback"; break;
84280 case OE_Abort: zType = "abort"; break;
84281 case OE_Fail: zType = "fail"; break;
84282 case OE_Ignore: zType = "ignore"; break;
84284 sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
84285 break;
84287 #endif
84288 default: {
84289 sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
84290 break;
84293 if( zBinOp ){
84294 sqlite3TreeViewLine(pView, "%s", zBinOp);
84295 sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
84296 sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
84297 }else if( zUniOp ){
84298 sqlite3TreeViewLine(pView, "%s", zUniOp);
84299 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
84301 sqlite3TreeViewPop(pView);
84303 #endif /* SQLITE_DEBUG */
84305 #ifdef SQLITE_DEBUG
84307 ** Generate a human-readable explanation of an expression list.
84309 SQLITE_PRIVATE void sqlite3TreeViewExprList(
84310 TreeView *pView,
84311 const ExprList *pList,
84312 u8 moreToFollow,
84313 const char *zLabel
84315 int i;
84316 pView = sqlite3TreeViewPush(pView, moreToFollow);
84317 if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
84318 if( pList==0 ){
84319 sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
84320 }else{
84321 sqlite3TreeViewLine(pView, "%s", zLabel);
84322 for(i=0; i<pList->nExpr; i++){
84323 sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
84324 #if 0
84325 if( pList->a[i].zName ){
84326 sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
84328 if( pList->a[i].bSpanIsTab ){
84329 sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
84331 #endif
84334 sqlite3TreeViewPop(pView);
84336 #endif /* SQLITE_DEBUG */
84339 ** Generate code that pushes the value of every element of the given
84340 ** expression list into a sequence of registers beginning at target.
84342 ** Return the number of elements evaluated.
84344 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
84345 ** filled using OP_SCopy. OP_Copy must be used instead.
84347 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
84348 ** factored out into initialization code.
84350 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
84351 Parse *pParse, /* Parsing context */
84352 ExprList *pList, /* The expression list to be coded */
84353 int target, /* Where to write results */
84354 u8 flags /* SQLITE_ECEL_* flags */
84356 struct ExprList_item *pItem;
84357 int i, n;
84358 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
84359 assert( pList!=0 );
84360 assert( target>0 );
84361 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
84362 n = pList->nExpr;
84363 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
84364 for(pItem=pList->a, i=0; i<n; i++, pItem++){
84365 Expr *pExpr = pItem->pExpr;
84366 if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
84367 sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
84368 }else{
84369 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
84370 if( inReg!=target+i ){
84371 VdbeOp *pOp;
84372 Vdbe *v = pParse->pVdbe;
84373 if( copyOp==OP_Copy
84374 && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
84375 && pOp->p1+pOp->p3+1==inReg
84376 && pOp->p2+pOp->p3+1==target+i
84378 pOp->p3++;
84379 }else{
84380 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
84385 return n;
84389 ** Generate code for a BETWEEN operator.
84391 ** x BETWEEN y AND z
84393 ** The above is equivalent to
84395 ** x>=y AND x<=z
84397 ** Code it as such, taking care to do the common subexpression
84398 ** elimination of x.
84400 static void exprCodeBetween(
84401 Parse *pParse, /* Parsing and code generating context */
84402 Expr *pExpr, /* The BETWEEN expression */
84403 int dest, /* Jump here if the jump is taken */
84404 int jumpIfTrue, /* Take the jump if the BETWEEN is true */
84405 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
84407 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
84408 Expr compLeft; /* The x>=y term */
84409 Expr compRight; /* The x<=z term */
84410 Expr exprX; /* The x subexpression */
84411 int regFree1 = 0; /* Temporary use register */
84413 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
84414 exprX = *pExpr->pLeft;
84415 exprAnd.op = TK_AND;
84416 exprAnd.pLeft = &compLeft;
84417 exprAnd.pRight = &compRight;
84418 compLeft.op = TK_GE;
84419 compLeft.pLeft = &exprX;
84420 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
84421 compRight.op = TK_LE;
84422 compRight.pLeft = &exprX;
84423 compRight.pRight = pExpr->x.pList->a[1].pExpr;
84424 exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
84425 if( jumpIfTrue ){
84426 sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
84427 }else{
84428 sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
84430 sqlite3ReleaseTempReg(pParse, regFree1);
84432 /* Ensure adequate test coverage */
84433 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
84434 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
84435 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
84436 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
84437 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
84438 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
84439 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
84440 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
84444 ** Generate code for a boolean expression such that a jump is made
84445 ** to the label "dest" if the expression is true but execution
84446 ** continues straight thru if the expression is false.
84448 ** If the expression evaluates to NULL (neither true nor false), then
84449 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
84451 ** This code depends on the fact that certain token values (ex: TK_EQ)
84452 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
84453 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
84454 ** the make process cause these values to align. Assert()s in the code
84455 ** below verify that the numbers are aligned correctly.
84457 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
84458 Vdbe *v = pParse->pVdbe;
84459 int op = 0;
84460 int regFree1 = 0;
84461 int regFree2 = 0;
84462 int r1, r2;
84464 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
84465 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
84466 if( NEVER(pExpr==0) ) return; /* No way this can happen */
84467 op = pExpr->op;
84468 switch( op ){
84469 case TK_AND: {
84470 int d2 = sqlite3VdbeMakeLabel(v);
84471 testcase( jumpIfNull==0 );
84472 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
84473 sqlite3ExprCachePush(pParse);
84474 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
84475 sqlite3VdbeResolveLabel(v, d2);
84476 sqlite3ExprCachePop(pParse);
84477 break;
84479 case TK_OR: {
84480 testcase( jumpIfNull==0 );
84481 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
84482 sqlite3ExprCachePush(pParse);
84483 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
84484 sqlite3ExprCachePop(pParse);
84485 break;
84487 case TK_NOT: {
84488 testcase( jumpIfNull==0 );
84489 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
84490 break;
84492 case TK_LT:
84493 case TK_LE:
84494 case TK_GT:
84495 case TK_GE:
84496 case TK_NE:
84497 case TK_EQ: {
84498 testcase( jumpIfNull==0 );
84499 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
84500 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
84501 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
84502 r1, r2, dest, jumpIfNull);
84503 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
84504 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
84505 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
84506 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
84507 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
84508 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
84509 testcase( regFree1==0 );
84510 testcase( regFree2==0 );
84511 break;
84513 case TK_IS:
84514 case TK_ISNOT: {
84515 testcase( op==TK_IS );
84516 testcase( op==TK_ISNOT );
84517 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
84518 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
84519 op = (op==TK_IS) ? TK_EQ : TK_NE;
84520 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
84521 r1, r2, dest, SQLITE_NULLEQ);
84522 VdbeCoverageIf(v, op==TK_EQ);
84523 VdbeCoverageIf(v, op==TK_NE);
84524 testcase( regFree1==0 );
84525 testcase( regFree2==0 );
84526 break;
84528 case TK_ISNULL:
84529 case TK_NOTNULL: {
84530 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
84531 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
84532 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
84533 sqlite3VdbeAddOp2(v, op, r1, dest);
84534 VdbeCoverageIf(v, op==TK_ISNULL);
84535 VdbeCoverageIf(v, op==TK_NOTNULL);
84536 testcase( regFree1==0 );
84537 break;
84539 case TK_BETWEEN: {
84540 testcase( jumpIfNull==0 );
84541 exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
84542 break;
84544 #ifndef SQLITE_OMIT_SUBQUERY
84545 case TK_IN: {
84546 int destIfFalse = sqlite3VdbeMakeLabel(v);
84547 int destIfNull = jumpIfNull ? dest : destIfFalse;
84548 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
84549 sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
84550 sqlite3VdbeResolveLabel(v, destIfFalse);
84551 break;
84553 #endif
84554 default: {
84555 if( exprAlwaysTrue(pExpr) ){
84556 sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
84557 }else if( exprAlwaysFalse(pExpr) ){
84558 /* No-op */
84559 }else{
84560 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
84561 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
84562 VdbeCoverage(v);
84563 testcase( regFree1==0 );
84564 testcase( jumpIfNull==0 );
84566 break;
84569 sqlite3ReleaseTempReg(pParse, regFree1);
84570 sqlite3ReleaseTempReg(pParse, regFree2);
84574 ** Generate code for a boolean expression such that a jump is made
84575 ** to the label "dest" if the expression is false but execution
84576 ** continues straight thru if the expression is true.
84578 ** If the expression evaluates to NULL (neither true nor false) then
84579 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
84580 ** is 0.
84582 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
84583 Vdbe *v = pParse->pVdbe;
84584 int op = 0;
84585 int regFree1 = 0;
84586 int regFree2 = 0;
84587 int r1, r2;
84589 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
84590 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
84591 if( pExpr==0 ) return;
84593 /* The value of pExpr->op and op are related as follows:
84595 ** pExpr->op op
84596 ** --------- ----------
84597 ** TK_ISNULL OP_NotNull
84598 ** TK_NOTNULL OP_IsNull
84599 ** TK_NE OP_Eq
84600 ** TK_EQ OP_Ne
84601 ** TK_GT OP_Le
84602 ** TK_LE OP_Gt
84603 ** TK_GE OP_Lt
84604 ** TK_LT OP_Ge
84606 ** For other values of pExpr->op, op is undefined and unused.
84607 ** The value of TK_ and OP_ constants are arranged such that we
84608 ** can compute the mapping above using the following expression.
84609 ** Assert()s verify that the computation is correct.
84611 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
84613 /* Verify correct alignment of TK_ and OP_ constants
84615 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
84616 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
84617 assert( pExpr->op!=TK_NE || op==OP_Eq );
84618 assert( pExpr->op!=TK_EQ || op==OP_Ne );
84619 assert( pExpr->op!=TK_LT || op==OP_Ge );
84620 assert( pExpr->op!=TK_LE || op==OP_Gt );
84621 assert( pExpr->op!=TK_GT || op==OP_Le );
84622 assert( pExpr->op!=TK_GE || op==OP_Lt );
84624 switch( pExpr->op ){
84625 case TK_AND: {
84626 testcase( jumpIfNull==0 );
84627 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
84628 sqlite3ExprCachePush(pParse);
84629 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
84630 sqlite3ExprCachePop(pParse);
84631 break;
84633 case TK_OR: {
84634 int d2 = sqlite3VdbeMakeLabel(v);
84635 testcase( jumpIfNull==0 );
84636 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
84637 sqlite3ExprCachePush(pParse);
84638 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
84639 sqlite3VdbeResolveLabel(v, d2);
84640 sqlite3ExprCachePop(pParse);
84641 break;
84643 case TK_NOT: {
84644 testcase( jumpIfNull==0 );
84645 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
84646 break;
84648 case TK_LT:
84649 case TK_LE:
84650 case TK_GT:
84651 case TK_GE:
84652 case TK_NE:
84653 case TK_EQ: {
84654 testcase( jumpIfNull==0 );
84655 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
84656 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
84657 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
84658 r1, r2, dest, jumpIfNull);
84659 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
84660 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
84661 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
84662 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
84663 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
84664 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
84665 testcase( regFree1==0 );
84666 testcase( regFree2==0 );
84667 break;
84669 case TK_IS:
84670 case TK_ISNOT: {
84671 testcase( pExpr->op==TK_IS );
84672 testcase( pExpr->op==TK_ISNOT );
84673 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
84674 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
84675 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
84676 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
84677 r1, r2, dest, SQLITE_NULLEQ);
84678 VdbeCoverageIf(v, op==TK_EQ);
84679 VdbeCoverageIf(v, op==TK_NE);
84680 testcase( regFree1==0 );
84681 testcase( regFree2==0 );
84682 break;
84684 case TK_ISNULL:
84685 case TK_NOTNULL: {
84686 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
84687 sqlite3VdbeAddOp2(v, op, r1, dest);
84688 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
84689 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
84690 testcase( regFree1==0 );
84691 break;
84693 case TK_BETWEEN: {
84694 testcase( jumpIfNull==0 );
84695 exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
84696 break;
84698 #ifndef SQLITE_OMIT_SUBQUERY
84699 case TK_IN: {
84700 if( jumpIfNull ){
84701 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
84702 }else{
84703 int destIfNull = sqlite3VdbeMakeLabel(v);
84704 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
84705 sqlite3VdbeResolveLabel(v, destIfNull);
84707 break;
84709 #endif
84710 default: {
84711 if( exprAlwaysFalse(pExpr) ){
84712 sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
84713 }else if( exprAlwaysTrue(pExpr) ){
84714 /* no-op */
84715 }else{
84716 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
84717 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
84718 VdbeCoverage(v);
84719 testcase( regFree1==0 );
84720 testcase( jumpIfNull==0 );
84722 break;
84725 sqlite3ReleaseTempReg(pParse, regFree1);
84726 sqlite3ReleaseTempReg(pParse, regFree2);
84730 ** Do a deep comparison of two expression trees. Return 0 if the two
84731 ** expressions are completely identical. Return 1 if they differ only
84732 ** by a COLLATE operator at the top level. Return 2 if there are differences
84733 ** other than the top-level COLLATE operator.
84735 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
84736 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
84738 ** The pA side might be using TK_REGISTER. If that is the case and pB is
84739 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
84741 ** Sometimes this routine will return 2 even if the two expressions
84742 ** really are equivalent. If we cannot prove that the expressions are
84743 ** identical, we return 2 just to be safe. So if this routine
84744 ** returns 2, then you do not really know for certain if the two
84745 ** expressions are the same. But if you get a 0 or 1 return, then you
84746 ** can be sure the expressions are the same. In the places where
84747 ** this routine is used, it does not hurt to get an extra 2 - that
84748 ** just might result in some slightly slower code. But returning
84749 ** an incorrect 0 or 1 could lead to a malfunction.
84751 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
84752 u32 combinedFlags;
84753 if( pA==0 || pB==0 ){
84754 return pB==pA ? 0 : 2;
84756 combinedFlags = pA->flags | pB->flags;
84757 if( combinedFlags & EP_IntValue ){
84758 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
84759 return 0;
84761 return 2;
84763 if( pA->op!=pB->op ){
84764 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
84765 return 1;
84767 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
84768 return 1;
84770 return 2;
84772 if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken ){
84773 if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
84774 return pA->op==TK_COLLATE ? 1 : 2;
84777 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
84778 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
84779 if( combinedFlags & EP_xIsSelect ) return 2;
84780 if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
84781 if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
84782 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
84783 if( ALWAYS((combinedFlags & EP_Reduced)==0) ){
84784 if( pA->iColumn!=pB->iColumn ) return 2;
84785 if( pA->iTable!=pB->iTable
84786 && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
84789 return 0;
84793 ** Compare two ExprList objects. Return 0 if they are identical and
84794 ** non-zero if they differ in any way.
84796 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
84797 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
84799 ** This routine might return non-zero for equivalent ExprLists. The
84800 ** only consequence will be disabled optimizations. But this routine
84801 ** must never return 0 if the two ExprList objects are different, or
84802 ** a malfunction will result.
84804 ** Two NULL pointers are considered to be the same. But a NULL pointer
84805 ** always differs from a non-NULL pointer.
84807 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
84808 int i;
84809 if( pA==0 && pB==0 ) return 0;
84810 if( pA==0 || pB==0 ) return 1;
84811 if( pA->nExpr!=pB->nExpr ) return 1;
84812 for(i=0; i<pA->nExpr; i++){
84813 Expr *pExprA = pA->a[i].pExpr;
84814 Expr *pExprB = pB->a[i].pExpr;
84815 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
84816 if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
84818 return 0;
84822 ** Return true if we can prove the pE2 will always be true if pE1 is
84823 ** true. Return false if we cannot complete the proof or if pE2 might
84824 ** be false. Examples:
84826 ** pE1: x==5 pE2: x==5 Result: true
84827 ** pE1: x>0 pE2: x==5 Result: false
84828 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
84829 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
84830 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
84831 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
84832 ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
84834 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
84835 ** Expr.iTable<0 then assume a table number given by iTab.
84837 ** When in doubt, return false. Returning true might give a performance
84838 ** improvement. Returning false might cause a performance reduction, but
84839 ** it will always give the correct answer and is hence always safe.
84841 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
84842 if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
84843 return 1;
84845 if( pE2->op==TK_OR
84846 && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
84847 || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
84849 return 1;
84851 if( pE2->op==TK_NOTNULL
84852 && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
84853 && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
84855 return 1;
84857 return 0;
84861 ** An instance of the following structure is used by the tree walker
84862 ** to count references to table columns in the arguments of an
84863 ** aggregate function, in order to implement the
84864 ** sqlite3FunctionThisSrc() routine.
84866 struct SrcCount {
84867 SrcList *pSrc; /* One particular FROM clause in a nested query */
84868 int nThis; /* Number of references to columns in pSrcList */
84869 int nOther; /* Number of references to columns in other FROM clauses */
84873 ** Count the number of references to columns.
84875 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
84876 /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
84877 ** is always called before sqlite3ExprAnalyzeAggregates() and so the
84878 ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
84879 ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
84880 ** NEVER() will need to be removed. */
84881 if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
84882 int i;
84883 struct SrcCount *p = pWalker->u.pSrcCount;
84884 SrcList *pSrc = p->pSrc;
84885 for(i=0; i<pSrc->nSrc; i++){
84886 if( pExpr->iTable==pSrc->a[i].iCursor ) break;
84888 if( i<pSrc->nSrc ){
84889 p->nThis++;
84890 }else{
84891 p->nOther++;
84894 return WRC_Continue;
84898 ** Determine if any of the arguments to the pExpr Function reference
84899 ** pSrcList. Return true if they do. Also return true if the function
84900 ** has no arguments or has only constant arguments. Return false if pExpr
84901 ** references columns but not columns of tables found in pSrcList.
84903 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
84904 Walker w;
84905 struct SrcCount cnt;
84906 assert( pExpr->op==TK_AGG_FUNCTION );
84907 memset(&w, 0, sizeof(w));
84908 w.xExprCallback = exprSrcCount;
84909 w.u.pSrcCount = &cnt;
84910 cnt.pSrc = pSrcList;
84911 cnt.nThis = 0;
84912 cnt.nOther = 0;
84913 sqlite3WalkExprList(&w, pExpr->x.pList);
84914 return cnt.nThis>0 || cnt.nOther==0;
84918 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
84919 ** the new element. Return a negative number if malloc fails.
84921 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
84922 int i;
84923 pInfo->aCol = sqlite3ArrayAllocate(
84925 pInfo->aCol,
84926 sizeof(pInfo->aCol[0]),
84927 &pInfo->nColumn,
84930 return i;
84934 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
84935 ** the new element. Return a negative number if malloc fails.
84937 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
84938 int i;
84939 pInfo->aFunc = sqlite3ArrayAllocate(
84940 db,
84941 pInfo->aFunc,
84942 sizeof(pInfo->aFunc[0]),
84943 &pInfo->nFunc,
84946 return i;
84950 ** This is the xExprCallback for a tree walker. It is used to
84951 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
84952 ** for additional information.
84954 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
84955 int i;
84956 NameContext *pNC = pWalker->u.pNC;
84957 Parse *pParse = pNC->pParse;
84958 SrcList *pSrcList = pNC->pSrcList;
84959 AggInfo *pAggInfo = pNC->pAggInfo;
84961 switch( pExpr->op ){
84962 case TK_AGG_COLUMN:
84963 case TK_COLUMN: {
84964 testcase( pExpr->op==TK_AGG_COLUMN );
84965 testcase( pExpr->op==TK_COLUMN );
84966 /* Check to see if the column is in one of the tables in the FROM
84967 ** clause of the aggregate query */
84968 if( ALWAYS(pSrcList!=0) ){
84969 struct SrcList_item *pItem = pSrcList->a;
84970 for(i=0; i<pSrcList->nSrc; i++, pItem++){
84971 struct AggInfo_col *pCol;
84972 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
84973 if( pExpr->iTable==pItem->iCursor ){
84974 /* If we reach this point, it means that pExpr refers to a table
84975 ** that is in the FROM clause of the aggregate query.
84977 ** Make an entry for the column in pAggInfo->aCol[] if there
84978 ** is not an entry there already.
84980 int k;
84981 pCol = pAggInfo->aCol;
84982 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
84983 if( pCol->iTable==pExpr->iTable &&
84984 pCol->iColumn==pExpr->iColumn ){
84985 break;
84988 if( (k>=pAggInfo->nColumn)
84989 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
84991 pCol = &pAggInfo->aCol[k];
84992 pCol->pTab = pExpr->pTab;
84993 pCol->iTable = pExpr->iTable;
84994 pCol->iColumn = pExpr->iColumn;
84995 pCol->iMem = ++pParse->nMem;
84996 pCol->iSorterColumn = -1;
84997 pCol->pExpr = pExpr;
84998 if( pAggInfo->pGroupBy ){
84999 int j, n;
85000 ExprList *pGB = pAggInfo->pGroupBy;
85001 struct ExprList_item *pTerm = pGB->a;
85002 n = pGB->nExpr;
85003 for(j=0; j<n; j++, pTerm++){
85004 Expr *pE = pTerm->pExpr;
85005 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
85006 pE->iColumn==pExpr->iColumn ){
85007 pCol->iSorterColumn = j;
85008 break;
85012 if( pCol->iSorterColumn<0 ){
85013 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
85016 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
85017 ** because it was there before or because we just created it).
85018 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
85019 ** pAggInfo->aCol[] entry.
85021 ExprSetVVAProperty(pExpr, EP_NoReduce);
85022 pExpr->pAggInfo = pAggInfo;
85023 pExpr->op = TK_AGG_COLUMN;
85024 pExpr->iAgg = (i16)k;
85025 break;
85026 } /* endif pExpr->iTable==pItem->iCursor */
85027 } /* end loop over pSrcList */
85029 return WRC_Prune;
85031 case TK_AGG_FUNCTION: {
85032 if( (pNC->ncFlags & NC_InAggFunc)==0
85033 && pWalker->walkerDepth==pExpr->op2
85035 /* Check to see if pExpr is a duplicate of another aggregate
85036 ** function that is already in the pAggInfo structure
85038 struct AggInfo_func *pItem = pAggInfo->aFunc;
85039 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
85040 if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
85041 break;
85044 if( i>=pAggInfo->nFunc ){
85045 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
85047 u8 enc = ENC(pParse->db);
85048 i = addAggInfoFunc(pParse->db, pAggInfo);
85049 if( i>=0 ){
85050 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
85051 pItem = &pAggInfo->aFunc[i];
85052 pItem->pExpr = pExpr;
85053 pItem->iMem = ++pParse->nMem;
85054 assert( !ExprHasProperty(pExpr, EP_IntValue) );
85055 pItem->pFunc = sqlite3FindFunction(pParse->db,
85056 pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
85057 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
85058 if( pExpr->flags & EP_Distinct ){
85059 pItem->iDistinct = pParse->nTab++;
85060 }else{
85061 pItem->iDistinct = -1;
85065 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
85067 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
85068 ExprSetVVAProperty(pExpr, EP_NoReduce);
85069 pExpr->iAgg = (i16)i;
85070 pExpr->pAggInfo = pAggInfo;
85071 return WRC_Prune;
85072 }else{
85073 return WRC_Continue;
85077 return WRC_Continue;
85079 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
85080 UNUSED_PARAMETER(pWalker);
85081 UNUSED_PARAMETER(pSelect);
85082 return WRC_Continue;
85086 ** Analyze the pExpr expression looking for aggregate functions and
85087 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
85088 ** points to. Additional entries are made on the AggInfo object as
85089 ** necessary.
85091 ** This routine should only be called after the expression has been
85092 ** analyzed by sqlite3ResolveExprNames().
85094 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
85095 Walker w;
85096 memset(&w, 0, sizeof(w));
85097 w.xExprCallback = analyzeAggregate;
85098 w.xSelectCallback = analyzeAggregatesInSelect;
85099 w.u.pNC = pNC;
85100 assert( pNC->pSrcList!=0 );
85101 sqlite3WalkExpr(&w, pExpr);
85105 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
85106 ** expression list. Return the number of errors.
85108 ** If an error is found, the analysis is cut short.
85110 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
85111 struct ExprList_item *pItem;
85112 int i;
85113 if( pList ){
85114 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
85115 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
85121 ** Allocate a single new register for use to hold some intermediate result.
85123 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
85124 if( pParse->nTempReg==0 ){
85125 return ++pParse->nMem;
85127 return pParse->aTempReg[--pParse->nTempReg];
85131 ** Deallocate a register, making available for reuse for some other
85132 ** purpose.
85134 ** If a register is currently being used by the column cache, then
85135 ** the deallocation is deferred until the column cache line that uses
85136 ** the register becomes stale.
85138 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
85139 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
85140 int i;
85141 struct yColCache *p;
85142 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
85143 if( p->iReg==iReg ){
85144 p->tempReg = 1;
85145 return;
85148 pParse->aTempReg[pParse->nTempReg++] = iReg;
85153 ** Allocate or deallocate a block of nReg consecutive registers
85155 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
85156 int i, n;
85157 i = pParse->iRangeReg;
85158 n = pParse->nRangeReg;
85159 if( nReg<=n ){
85160 assert( !usedAsColumnCache(pParse, i, i+n-1) );
85161 pParse->iRangeReg += nReg;
85162 pParse->nRangeReg -= nReg;
85163 }else{
85164 i = pParse->nMem+1;
85165 pParse->nMem += nReg;
85167 return i;
85169 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
85170 sqlite3ExprCacheRemove(pParse, iReg, nReg);
85171 if( nReg>pParse->nRangeReg ){
85172 pParse->nRangeReg = nReg;
85173 pParse->iRangeReg = iReg;
85178 ** Mark all temporary registers as being unavailable for reuse.
85180 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
85181 pParse->nTempReg = 0;
85182 pParse->nRangeReg = 0;
85185 /************** End of expr.c ************************************************/
85186 /************** Begin file alter.c *******************************************/
85188 ** 2005 February 15
85190 ** The author disclaims copyright to this source code. In place of
85191 ** a legal notice, here is a blessing:
85193 ** May you do good and not evil.
85194 ** May you find forgiveness for yourself and forgive others.
85195 ** May you share freely, never taking more than you give.
85197 *************************************************************************
85198 ** This file contains C code routines that used to generate VDBE code
85199 ** that implements the ALTER TABLE command.
85203 ** The code in this file only exists if we are not omitting the
85204 ** ALTER TABLE logic from the build.
85206 #ifndef SQLITE_OMIT_ALTERTABLE
85210 ** This function is used by SQL generated to implement the
85211 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
85212 ** CREATE INDEX command. The second is a table name. The table name in
85213 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
85214 ** argument and the result returned. Examples:
85216 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
85217 ** -> 'CREATE TABLE def(a, b, c)'
85219 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
85220 ** -> 'CREATE INDEX i ON def(a, b, c)'
85222 static void renameTableFunc(
85223 sqlite3_context *context,
85224 int NotUsed,
85225 sqlite3_value **argv
85227 unsigned char const *zSql = sqlite3_value_text(argv[0]);
85228 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
85230 int token;
85231 Token tname;
85232 unsigned char const *zCsr = zSql;
85233 int len = 0;
85234 char *zRet;
85236 sqlite3 *db = sqlite3_context_db_handle(context);
85238 UNUSED_PARAMETER(NotUsed);
85240 /* The principle used to locate the table name in the CREATE TABLE
85241 ** statement is that the table name is the first non-space token that
85242 ** is immediately followed by a TK_LP or TK_USING token.
85244 if( zSql ){
85245 do {
85246 if( !*zCsr ){
85247 /* Ran out of input before finding an opening bracket. Return NULL. */
85248 return;
85251 /* Store the token that zCsr points to in tname. */
85252 tname.z = (char*)zCsr;
85253 tname.n = len;
85255 /* Advance zCsr to the next token. Store that token type in 'token',
85256 ** and its length in 'len' (to be used next iteration of this loop).
85258 do {
85259 zCsr += len;
85260 len = sqlite3GetToken(zCsr, &token);
85261 } while( token==TK_SPACE );
85262 assert( len>0 );
85263 } while( token!=TK_LP && token!=TK_USING );
85265 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
85266 zSql, zTableName, tname.z+tname.n);
85267 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
85272 ** This C function implements an SQL user function that is used by SQL code
85273 ** generated by the ALTER TABLE ... RENAME command to modify the definition
85274 ** of any foreign key constraints that use the table being renamed as the
85275 ** parent table. It is passed three arguments:
85277 ** 1) The complete text of the CREATE TABLE statement being modified,
85278 ** 2) The old name of the table being renamed, and
85279 ** 3) The new name of the table being renamed.
85281 ** It returns the new CREATE TABLE statement. For example:
85283 ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
85284 ** -> 'CREATE TABLE t1(a REFERENCES t3)'
85286 #ifndef SQLITE_OMIT_FOREIGN_KEY
85287 static void renameParentFunc(
85288 sqlite3_context *context,
85289 int NotUsed,
85290 sqlite3_value **argv
85292 sqlite3 *db = sqlite3_context_db_handle(context);
85293 char *zOutput = 0;
85294 char *zResult;
85295 unsigned char const *zInput = sqlite3_value_text(argv[0]);
85296 unsigned char const *zOld = sqlite3_value_text(argv[1]);
85297 unsigned char const *zNew = sqlite3_value_text(argv[2]);
85299 unsigned const char *z; /* Pointer to token */
85300 int n; /* Length of token z */
85301 int token; /* Type of token */
85303 UNUSED_PARAMETER(NotUsed);
85304 if( zInput==0 || zOld==0 ) return;
85305 for(z=zInput; *z; z=z+n){
85306 n = sqlite3GetToken(z, &token);
85307 if( token==TK_REFERENCES ){
85308 char *zParent;
85309 do {
85310 z += n;
85311 n = sqlite3GetToken(z, &token);
85312 }while( token==TK_SPACE );
85314 zParent = sqlite3DbStrNDup(db, (const char *)z, n);
85315 if( zParent==0 ) break;
85316 sqlite3Dequote(zParent);
85317 if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
85318 char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
85319 (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
85321 sqlite3DbFree(db, zOutput);
85322 zOutput = zOut;
85323 zInput = &z[n];
85325 sqlite3DbFree(db, zParent);
85329 zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
85330 sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
85331 sqlite3DbFree(db, zOutput);
85333 #endif
85335 #ifndef SQLITE_OMIT_TRIGGER
85336 /* This function is used by SQL generated to implement the
85337 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
85338 ** statement. The second is a table name. The table name in the CREATE
85339 ** TRIGGER statement is replaced with the third argument and the result
85340 ** returned. This is analagous to renameTableFunc() above, except for CREATE
85341 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
85343 static void renameTriggerFunc(
85344 sqlite3_context *context,
85345 int NotUsed,
85346 sqlite3_value **argv
85348 unsigned char const *zSql = sqlite3_value_text(argv[0]);
85349 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
85351 int token;
85352 Token tname;
85353 int dist = 3;
85354 unsigned char const *zCsr = zSql;
85355 int len = 0;
85356 char *zRet;
85357 sqlite3 *db = sqlite3_context_db_handle(context);
85359 UNUSED_PARAMETER(NotUsed);
85361 /* The principle used to locate the table name in the CREATE TRIGGER
85362 ** statement is that the table name is the first token that is immediately
85363 ** preceded by either TK_ON or TK_DOT and immediately followed by one
85364 ** of TK_WHEN, TK_BEGIN or TK_FOR.
85366 if( zSql ){
85367 do {
85369 if( !*zCsr ){
85370 /* Ran out of input before finding the table name. Return NULL. */
85371 return;
85374 /* Store the token that zCsr points to in tname. */
85375 tname.z = (char*)zCsr;
85376 tname.n = len;
85378 /* Advance zCsr to the next token. Store that token type in 'token',
85379 ** and its length in 'len' (to be used next iteration of this loop).
85381 do {
85382 zCsr += len;
85383 len = sqlite3GetToken(zCsr, &token);
85384 }while( token==TK_SPACE );
85385 assert( len>0 );
85387 /* Variable 'dist' stores the number of tokens read since the most
85388 ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
85389 ** token is read and 'dist' equals 2, the condition stated above
85390 ** to be met.
85392 ** Note that ON cannot be a database, table or column name, so
85393 ** there is no need to worry about syntax like
85394 ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
85396 dist++;
85397 if( token==TK_DOT || token==TK_ON ){
85398 dist = 0;
85400 } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
85402 /* Variable tname now contains the token that is the old table-name
85403 ** in the CREATE TRIGGER statement.
85405 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
85406 zSql, zTableName, tname.z+tname.n);
85407 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
85410 #endif /* !SQLITE_OMIT_TRIGGER */
85413 ** Register built-in functions used to help implement ALTER TABLE
85415 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
85416 static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
85417 FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
85418 #ifndef SQLITE_OMIT_TRIGGER
85419 FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
85420 #endif
85421 #ifndef SQLITE_OMIT_FOREIGN_KEY
85422 FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
85423 #endif
85425 int i;
85426 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
85427 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
85429 for(i=0; i<ArraySize(aAlterTableFuncs); i++){
85430 sqlite3FuncDefInsert(pHash, &aFunc[i]);
85435 ** This function is used to create the text of expressions of the form:
85437 ** name=<constant1> OR name=<constant2> OR ...
85439 ** If argument zWhere is NULL, then a pointer string containing the text
85440 ** "name=<constant>" is returned, where <constant> is the quoted version
85441 ** of the string passed as argument zConstant. The returned buffer is
85442 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
85443 ** caller to ensure that it is eventually freed.
85445 ** If argument zWhere is not NULL, then the string returned is
85446 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
85447 ** In this case zWhere is passed to sqlite3DbFree() before returning.
85450 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
85451 char *zNew;
85452 if( !zWhere ){
85453 zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
85454 }else{
85455 zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
85456 sqlite3DbFree(db, zWhere);
85458 return zNew;
85461 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
85463 ** Generate the text of a WHERE expression which can be used to select all
85464 ** tables that have foreign key constraints that refer to table pTab (i.e.
85465 ** constraints for which pTab is the parent table) from the sqlite_master
85466 ** table.
85468 static char *whereForeignKeys(Parse *pParse, Table *pTab){
85469 FKey *p;
85470 char *zWhere = 0;
85471 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
85472 zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
85474 return zWhere;
85476 #endif
85479 ** Generate the text of a WHERE expression which can be used to select all
85480 ** temporary triggers on table pTab from the sqlite_temp_master table. If
85481 ** table pTab has no temporary triggers, or is itself stored in the
85482 ** temporary database, NULL is returned.
85484 static char *whereTempTriggers(Parse *pParse, Table *pTab){
85485 Trigger *pTrig;
85486 char *zWhere = 0;
85487 const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
85489 /* If the table is not located in the temp-db (in which case NULL is
85490 ** returned, loop through the tables list of triggers. For each trigger
85491 ** that is not part of the temp-db schema, add a clause to the WHERE
85492 ** expression being built up in zWhere.
85494 if( pTab->pSchema!=pTempSchema ){
85495 sqlite3 *db = pParse->db;
85496 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
85497 if( pTrig->pSchema==pTempSchema ){
85498 zWhere = whereOrName(db, zWhere, pTrig->zName);
85502 if( zWhere ){
85503 char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
85504 sqlite3DbFree(pParse->db, zWhere);
85505 zWhere = zNew;
85507 return zWhere;
85511 ** Generate code to drop and reload the internal representation of table
85512 ** pTab from the database, including triggers and temporary triggers.
85513 ** Argument zName is the name of the table in the database schema at
85514 ** the time the generated code is executed. This can be different from
85515 ** pTab->zName if this function is being called to code part of an
85516 ** "ALTER TABLE RENAME TO" statement.
85518 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
85519 Vdbe *v;
85520 char *zWhere;
85521 int iDb; /* Index of database containing pTab */
85522 #ifndef SQLITE_OMIT_TRIGGER
85523 Trigger *pTrig;
85524 #endif
85526 v = sqlite3GetVdbe(pParse);
85527 if( NEVER(v==0) ) return;
85528 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
85529 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
85530 assert( iDb>=0 );
85532 #ifndef SQLITE_OMIT_TRIGGER
85533 /* Drop any table triggers from the internal schema. */
85534 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
85535 int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
85536 assert( iTrigDb==iDb || iTrigDb==1 );
85537 sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
85539 #endif
85541 /* Drop the table and index from the internal schema. */
85542 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
85544 /* Reload the table, index and permanent trigger schemas. */
85545 zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
85546 if( !zWhere ) return;
85547 sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
85549 #ifndef SQLITE_OMIT_TRIGGER
85550 /* Now, if the table is not stored in the temp database, reload any temp
85551 ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
85553 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
85554 sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
85556 #endif
85560 ** Parameter zName is the name of a table that is about to be altered
85561 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
85562 ** If the table is a system table, this function leaves an error message
85563 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
85565 ** Or, if zName is not a system table, zero is returned.
85567 static int isSystemTable(Parse *pParse, const char *zName){
85568 if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
85569 sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
85570 return 1;
85572 return 0;
85576 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
85577 ** command.
85579 SQLITE_PRIVATE void sqlite3AlterRenameTable(
85580 Parse *pParse, /* Parser context. */
85581 SrcList *pSrc, /* The table to rename. */
85582 Token *pName /* The new table name. */
85584 int iDb; /* Database that contains the table */
85585 char *zDb; /* Name of database iDb */
85586 Table *pTab; /* Table being renamed */
85587 char *zName = 0; /* NULL-terminated version of pName */
85588 sqlite3 *db = pParse->db; /* Database connection */
85589 int nTabName; /* Number of UTF-8 characters in zTabName */
85590 const char *zTabName; /* Original name of the table */
85591 Vdbe *v;
85592 #ifndef SQLITE_OMIT_TRIGGER
85593 char *zWhere = 0; /* Where clause to locate temp triggers */
85594 #endif
85595 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
85596 int savedDbFlags; /* Saved value of db->flags */
85598 savedDbFlags = db->flags;
85599 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
85600 assert( pSrc->nSrc==1 );
85601 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
85603 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
85604 if( !pTab ) goto exit_rename_table;
85605 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
85606 zDb = db->aDb[iDb].zName;
85607 db->flags |= SQLITE_PreferBuiltin;
85609 /* Get a NULL terminated version of the new table name. */
85610 zName = sqlite3NameFromToken(db, pName);
85611 if( !zName ) goto exit_rename_table;
85613 /* Check that a table or index named 'zName' does not already exist
85614 ** in database iDb. If so, this is an error.
85616 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
85617 sqlite3ErrorMsg(pParse,
85618 "there is already another table or index with this name: %s", zName);
85619 goto exit_rename_table;
85622 /* Make sure it is not a system table being altered, or a reserved name
85623 ** that the table is being renamed to.
85625 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
85626 goto exit_rename_table;
85628 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
85629 exit_rename_table;
85632 #ifndef SQLITE_OMIT_VIEW
85633 if( pTab->pSelect ){
85634 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
85635 goto exit_rename_table;
85637 #endif
85639 #ifndef SQLITE_OMIT_AUTHORIZATION
85640 /* Invoke the authorization callback. */
85641 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
85642 goto exit_rename_table;
85644 #endif
85646 #ifndef SQLITE_OMIT_VIRTUALTABLE
85647 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
85648 goto exit_rename_table;
85650 if( IsVirtual(pTab) ){
85651 pVTab = sqlite3GetVTable(db, pTab);
85652 if( pVTab->pVtab->pModule->xRename==0 ){
85653 pVTab = 0;
85656 #endif
85658 /* Begin a transaction for database iDb.
85659 ** Then modify the schema cookie (since the ALTER TABLE modifies the
85660 ** schema). Open a statement transaction if the table is a virtual
85661 ** table.
85663 v = sqlite3GetVdbe(pParse);
85664 if( v==0 ){
85665 goto exit_rename_table;
85667 sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
85668 sqlite3ChangeCookie(pParse, iDb);
85670 /* If this is a virtual table, invoke the xRename() function if
85671 ** one is defined. The xRename() callback will modify the names
85672 ** of any resources used by the v-table implementation (including other
85673 ** SQLite tables) that are identified by the name of the virtual table.
85675 #ifndef SQLITE_OMIT_VIRTUALTABLE
85676 if( pVTab ){
85677 int i = ++pParse->nMem;
85678 sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
85679 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
85680 sqlite3MayAbort(pParse);
85682 #endif
85684 /* figure out how many UTF-8 characters are in zName */
85685 zTabName = pTab->zName;
85686 nTabName = sqlite3Utf8CharLen(zTabName, -1);
85688 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
85689 if( db->flags&SQLITE_ForeignKeys ){
85690 /* If foreign-key support is enabled, rewrite the CREATE TABLE
85691 ** statements corresponding to all child tables of foreign key constraints
85692 ** for which the renamed table is the parent table. */
85693 if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
85694 sqlite3NestedParse(pParse,
85695 "UPDATE \"%w\".%s SET "
85696 "sql = sqlite_rename_parent(sql, %Q, %Q) "
85697 "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
85698 sqlite3DbFree(db, zWhere);
85701 #endif
85703 /* Modify the sqlite_master table to use the new table name. */
85704 sqlite3NestedParse(pParse,
85705 "UPDATE %Q.%s SET "
85706 #ifdef SQLITE_OMIT_TRIGGER
85707 "sql = sqlite_rename_table(sql, %Q), "
85708 #else
85709 "sql = CASE "
85710 "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
85711 "ELSE sqlite_rename_table(sql, %Q) END, "
85712 #endif
85713 "tbl_name = %Q, "
85714 "name = CASE "
85715 "WHEN type='table' THEN %Q "
85716 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
85717 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
85718 "ELSE name END "
85719 "WHERE tbl_name=%Q COLLATE nocase AND "
85720 "(type='table' OR type='index' OR type='trigger');",
85721 zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
85722 #ifndef SQLITE_OMIT_TRIGGER
85723 zName,
85724 #endif
85725 zName, nTabName, zTabName
85728 #ifndef SQLITE_OMIT_AUTOINCREMENT
85729 /* If the sqlite_sequence table exists in this database, then update
85730 ** it with the new table name.
85732 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
85733 sqlite3NestedParse(pParse,
85734 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
85735 zDb, zName, pTab->zName);
85737 #endif
85739 #ifndef SQLITE_OMIT_TRIGGER
85740 /* If there are TEMP triggers on this table, modify the sqlite_temp_master
85741 ** table. Don't do this if the table being ALTERed is itself located in
85742 ** the temp database.
85744 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
85745 sqlite3NestedParse(pParse,
85746 "UPDATE sqlite_temp_master SET "
85747 "sql = sqlite_rename_trigger(sql, %Q), "
85748 "tbl_name = %Q "
85749 "WHERE %s;", zName, zName, zWhere);
85750 sqlite3DbFree(db, zWhere);
85752 #endif
85754 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
85755 if( db->flags&SQLITE_ForeignKeys ){
85756 FKey *p;
85757 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
85758 Table *pFrom = p->pFrom;
85759 if( pFrom!=pTab ){
85760 reloadTableSchema(pParse, p->pFrom, pFrom->zName);
85764 #endif
85766 /* Drop and reload the internal table schema. */
85767 reloadTableSchema(pParse, pTab, zName);
85769 exit_rename_table:
85770 sqlite3SrcListDelete(db, pSrc);
85771 sqlite3DbFree(db, zName);
85772 db->flags = savedDbFlags;
85777 ** Generate code to make sure the file format number is at least minFormat.
85778 ** The generated code will increase the file format number if necessary.
85780 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
85781 Vdbe *v;
85782 v = sqlite3GetVdbe(pParse);
85783 /* The VDBE should have been allocated before this routine is called.
85784 ** If that allocation failed, we would have quit before reaching this
85785 ** point */
85786 if( ALWAYS(v) ){
85787 int r1 = sqlite3GetTempReg(pParse);
85788 int r2 = sqlite3GetTempReg(pParse);
85789 int j1;
85790 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
85791 sqlite3VdbeUsesBtree(v, iDb);
85792 sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
85793 j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
85794 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v);
85795 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
85796 sqlite3VdbeJumpHere(v, j1);
85797 sqlite3ReleaseTempReg(pParse, r1);
85798 sqlite3ReleaseTempReg(pParse, r2);
85803 ** This function is called after an "ALTER TABLE ... ADD" statement
85804 ** has been parsed. Argument pColDef contains the text of the new
85805 ** column definition.
85807 ** The Table structure pParse->pNewTable was extended to include
85808 ** the new column during parsing.
85810 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
85811 Table *pNew; /* Copy of pParse->pNewTable */
85812 Table *pTab; /* Table being altered */
85813 int iDb; /* Database number */
85814 const char *zDb; /* Database name */
85815 const char *zTab; /* Table name */
85816 char *zCol; /* Null-terminated column definition */
85817 Column *pCol; /* The new column */
85818 Expr *pDflt; /* Default value for the new column */
85819 sqlite3 *db; /* The database connection; */
85821 db = pParse->db;
85822 if( pParse->nErr || db->mallocFailed ) return;
85823 pNew = pParse->pNewTable;
85824 assert( pNew );
85826 assert( sqlite3BtreeHoldsAllMutexes(db) );
85827 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
85828 zDb = db->aDb[iDb].zName;
85829 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
85830 pCol = &pNew->aCol[pNew->nCol-1];
85831 pDflt = pCol->pDflt;
85832 pTab = sqlite3FindTable(db, zTab, zDb);
85833 assert( pTab );
85835 #ifndef SQLITE_OMIT_AUTHORIZATION
85836 /* Invoke the authorization callback. */
85837 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
85838 return;
85840 #endif
85842 /* If the default value for the new column was specified with a
85843 ** literal NULL, then set pDflt to 0. This simplifies checking
85844 ** for an SQL NULL default below.
85846 if( pDflt && pDflt->op==TK_NULL ){
85847 pDflt = 0;
85850 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
85851 ** If there is a NOT NULL constraint, then the default value for the
85852 ** column must not be NULL.
85854 if( pCol->colFlags & COLFLAG_PRIMKEY ){
85855 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
85856 return;
85858 if( pNew->pIndex ){
85859 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
85860 return;
85862 if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
85863 sqlite3ErrorMsg(pParse,
85864 "Cannot add a REFERENCES column with non-NULL default value");
85865 return;
85867 if( pCol->notNull && !pDflt ){
85868 sqlite3ErrorMsg(pParse,
85869 "Cannot add a NOT NULL column with default value NULL");
85870 return;
85873 /* Ensure the default expression is something that sqlite3ValueFromExpr()
85874 ** can handle (i.e. not CURRENT_TIME etc.)
85876 if( pDflt ){
85877 sqlite3_value *pVal = 0;
85878 if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
85879 db->mallocFailed = 1;
85880 return;
85882 if( !pVal ){
85883 sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
85884 return;
85886 sqlite3ValueFree(pVal);
85889 /* Modify the CREATE TABLE statement. */
85890 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
85891 if( zCol ){
85892 char *zEnd = &zCol[pColDef->n-1];
85893 int savedDbFlags = db->flags;
85894 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
85895 *zEnd-- = '\0';
85897 db->flags |= SQLITE_PreferBuiltin;
85898 sqlite3NestedParse(pParse,
85899 "UPDATE \"%w\".%s SET "
85900 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
85901 "WHERE type = 'table' AND name = %Q",
85902 zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
85903 zTab
85905 sqlite3DbFree(db, zCol);
85906 db->flags = savedDbFlags;
85909 /* If the default value of the new column is NULL, then set the file
85910 ** format to 2. If the default value of the new column is not NULL,
85911 ** the file format becomes 3.
85913 sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
85915 /* Reload the schema of the modified table. */
85916 reloadTableSchema(pParse, pTab, pTab->zName);
85920 ** This function is called by the parser after the table-name in
85921 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
85922 ** pSrc is the full-name of the table being altered.
85924 ** This routine makes a (partial) copy of the Table structure
85925 ** for the table being altered and sets Parse.pNewTable to point
85926 ** to it. Routines called by the parser as the column definition
85927 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
85928 ** the copy. The copy of the Table structure is deleted by tokenize.c
85929 ** after parsing is finished.
85931 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
85932 ** coding the "ALTER TABLE ... ADD" statement.
85934 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
85935 Table *pNew;
85936 Table *pTab;
85937 Vdbe *v;
85938 int iDb;
85939 int i;
85940 int nAlloc;
85941 sqlite3 *db = pParse->db;
85943 /* Look up the table being altered. */
85944 assert( pParse->pNewTable==0 );
85945 assert( sqlite3BtreeHoldsAllMutexes(db) );
85946 if( db->mallocFailed ) goto exit_begin_add_column;
85947 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
85948 if( !pTab ) goto exit_begin_add_column;
85950 #ifndef SQLITE_OMIT_VIRTUALTABLE
85951 if( IsVirtual(pTab) ){
85952 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
85953 goto exit_begin_add_column;
85955 #endif
85957 /* Make sure this is not an attempt to ALTER a view. */
85958 if( pTab->pSelect ){
85959 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
85960 goto exit_begin_add_column;
85962 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
85963 goto exit_begin_add_column;
85966 assert( pTab->addColOffset>0 );
85967 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
85969 /* Put a copy of the Table struct in Parse.pNewTable for the
85970 ** sqlite3AddColumn() function and friends to modify. But modify
85971 ** the name by adding an "sqlite_altertab_" prefix. By adding this
85972 ** prefix, we insure that the name will not collide with an existing
85973 ** table because user table are not allowed to have the "sqlite_"
85974 ** prefix on their name.
85976 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
85977 if( !pNew ) goto exit_begin_add_column;
85978 pParse->pNewTable = pNew;
85979 pNew->nRef = 1;
85980 pNew->nCol = pTab->nCol;
85981 assert( pNew->nCol>0 );
85982 nAlloc = (((pNew->nCol-1)/8)*8)+8;
85983 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
85984 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
85985 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
85986 if( !pNew->aCol || !pNew->zName ){
85987 db->mallocFailed = 1;
85988 goto exit_begin_add_column;
85990 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
85991 for(i=0; i<pNew->nCol; i++){
85992 Column *pCol = &pNew->aCol[i];
85993 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
85994 pCol->zColl = 0;
85995 pCol->zType = 0;
85996 pCol->pDflt = 0;
85997 pCol->zDflt = 0;
85999 pNew->pSchema = db->aDb[iDb].pSchema;
86000 pNew->addColOffset = pTab->addColOffset;
86001 pNew->nRef = 1;
86003 /* Begin a transaction and increment the schema cookie. */
86004 sqlite3BeginWriteOperation(pParse, 0, iDb);
86005 v = sqlite3GetVdbe(pParse);
86006 if( !v ) goto exit_begin_add_column;
86007 sqlite3ChangeCookie(pParse, iDb);
86009 exit_begin_add_column:
86010 sqlite3SrcListDelete(db, pSrc);
86011 return;
86013 #endif /* SQLITE_ALTER_TABLE */
86015 /************** End of alter.c ***********************************************/
86016 /************** Begin file analyze.c *****************************************/
86018 ** 2005-07-08
86020 ** The author disclaims copyright to this source code. In place of
86021 ** a legal notice, here is a blessing:
86023 ** May you do good and not evil.
86024 ** May you find forgiveness for yourself and forgive others.
86025 ** May you share freely, never taking more than you give.
86027 *************************************************************************
86028 ** This file contains code associated with the ANALYZE command.
86030 ** The ANALYZE command gather statistics about the content of tables
86031 ** and indices. These statistics are made available to the query planner
86032 ** to help it make better decisions about how to perform queries.
86034 ** The following system tables are or have been supported:
86036 ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
86037 ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
86038 ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
86039 ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
86041 ** Additional tables might be added in future releases of SQLite.
86042 ** The sqlite_stat2 table is not created or used unless the SQLite version
86043 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
86044 ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
86045 ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
86046 ** created and used by SQLite versions 3.7.9 and later and with
86047 ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
86048 ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
86049 ** version of sqlite_stat3 and is only available when compiled with
86050 ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
86051 ** not possible to enable both STAT3 and STAT4 at the same time. If they
86052 ** are both enabled, then STAT4 takes precedence.
86054 ** For most applications, sqlite_stat1 provides all the statistics required
86055 ** for the query planner to make good choices.
86057 ** Format of sqlite_stat1:
86059 ** There is normally one row per index, with the index identified by the
86060 ** name in the idx column. The tbl column is the name of the table to
86061 ** which the index belongs. In each such row, the stat column will be
86062 ** a string consisting of a list of integers. The first integer in this
86063 ** list is the number of rows in the index. (This is the same as the
86064 ** number of rows in the table, except for partial indices.) The second
86065 ** integer is the average number of rows in the index that have the same
86066 ** value in the first column of the index. The third integer is the average
86067 ** number of rows in the index that have the same value for the first two
86068 ** columns. The N-th integer (for N>1) is the average number of rows in
86069 ** the index which have the same value for the first N-1 columns. For
86070 ** a K-column index, there will be K+1 integers in the stat column. If
86071 ** the index is unique, then the last integer will be 1.
86073 ** The list of integers in the stat column can optionally be followed
86074 ** by the keyword "unordered". The "unordered" keyword, if it is present,
86075 ** must be separated from the last integer by a single space. If the
86076 ** "unordered" keyword is present, then the query planner assumes that
86077 ** the index is unordered and will not use the index for a range query.
86079 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
86080 ** column contains a single integer which is the (estimated) number of
86081 ** rows in the table identified by sqlite_stat1.tbl.
86083 ** Format of sqlite_stat2:
86085 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
86086 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
86087 ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
86088 ** about the distribution of keys within an index. The index is identified by
86089 ** the "idx" column and the "tbl" column is the name of the table to which
86090 ** the index belongs. There are usually 10 rows in the sqlite_stat2
86091 ** table for each index.
86093 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
86094 ** inclusive are samples of the left-most key value in the index taken at
86095 ** evenly spaced points along the index. Let the number of samples be S
86096 ** (10 in the standard build) and let C be the number of rows in the index.
86097 ** Then the sampled rows are given by:
86099 ** rownumber = (i*C*2 + C)/(S*2)
86101 ** For i between 0 and S-1. Conceptually, the index space is divided into
86102 ** S uniform buckets and the samples are the middle row from each bucket.
86104 ** The format for sqlite_stat2 is recorded here for legacy reference. This
86105 ** version of SQLite does not support sqlite_stat2. It neither reads nor
86106 ** writes the sqlite_stat2 table. This version of SQLite only supports
86107 ** sqlite_stat3.
86109 ** Format for sqlite_stat3:
86111 ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
86112 ** sqlite_stat4 format will be described first. Further information
86113 ** about sqlite_stat3 follows the sqlite_stat4 description.
86115 ** Format for sqlite_stat4:
86117 ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
86118 ** to aid the query planner in choosing good indices based on the values
86119 ** that indexed columns are compared against in the WHERE clauses of
86120 ** queries.
86122 ** The sqlite_stat4 table contains multiple entries for each index.
86123 ** The idx column names the index and the tbl column is the table of the
86124 ** index. If the idx and tbl columns are the same, then the sample is
86125 ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
86126 ** binary encoding of a key from the index. The nEq column is a
86127 ** list of integers. The first integer is the approximate number
86128 ** of entries in the index whose left-most column exactly matches
86129 ** the left-most column of the sample. The second integer in nEq
86130 ** is the approximate number of entries in the index where the
86131 ** first two columns match the first two columns of the sample.
86132 ** And so forth. nLt is another list of integers that show the approximate
86133 ** number of entries that are strictly less than the sample. The first
86134 ** integer in nLt contains the number of entries in the index where the
86135 ** left-most column is less than the left-most column of the sample.
86136 ** The K-th integer in the nLt entry is the number of index entries
86137 ** where the first K columns are less than the first K columns of the
86138 ** sample. The nDLt column is like nLt except that it contains the
86139 ** number of distinct entries in the index that are less than the
86140 ** sample.
86142 ** There can be an arbitrary number of sqlite_stat4 entries per index.
86143 ** The ANALYZE command will typically generate sqlite_stat4 tables
86144 ** that contain between 10 and 40 samples which are distributed across
86145 ** the key space, though not uniformly, and which include samples with
86146 ** large nEq values.
86148 ** Format for sqlite_stat3 redux:
86150 ** The sqlite_stat3 table is like sqlite_stat4 except that it only
86151 ** looks at the left-most column of the index. The sqlite_stat3.sample
86152 ** column contains the actual value of the left-most column instead
86153 ** of a blob encoding of the complete index key as is found in
86154 ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
86155 ** all contain just a single integer which is the same as the first
86156 ** integer in the equivalent columns in sqlite_stat4.
86158 #ifndef SQLITE_OMIT_ANALYZE
86160 #if defined(SQLITE_ENABLE_STAT4)
86161 # define IsStat4 1
86162 # define IsStat3 0
86163 #elif defined(SQLITE_ENABLE_STAT3)
86164 # define IsStat4 0
86165 # define IsStat3 1
86166 #else
86167 # define IsStat4 0
86168 # define IsStat3 0
86169 # undef SQLITE_STAT4_SAMPLES
86170 # define SQLITE_STAT4_SAMPLES 1
86171 #endif
86172 #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
86175 ** This routine generates code that opens the sqlite_statN tables.
86176 ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
86177 ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
86178 ** appropriate compile-time options are provided.
86180 ** If the sqlite_statN tables do not previously exist, it is created.
86182 ** Argument zWhere may be a pointer to a buffer containing a table name,
86183 ** or it may be a NULL pointer. If it is not NULL, then all entries in
86184 ** the sqlite_statN tables associated with the named table are deleted.
86185 ** If zWhere==0, then code is generated to delete all stat table entries.
86187 static void openStatTable(
86188 Parse *pParse, /* Parsing context */
86189 int iDb, /* The database we are looking in */
86190 int iStatCur, /* Open the sqlite_stat1 table on this cursor */
86191 const char *zWhere, /* Delete entries for this table or index */
86192 const char *zWhereType /* Either "tbl" or "idx" */
86194 static const struct {
86195 const char *zName;
86196 const char *zCols;
86197 } aTable[] = {
86198 { "sqlite_stat1", "tbl,idx,stat" },
86199 #if defined(SQLITE_ENABLE_STAT4)
86200 { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
86201 { "sqlite_stat3", 0 },
86202 #elif defined(SQLITE_ENABLE_STAT3)
86203 { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
86204 { "sqlite_stat4", 0 },
86205 #else
86206 { "sqlite_stat3", 0 },
86207 { "sqlite_stat4", 0 },
86208 #endif
86210 int i;
86211 sqlite3 *db = pParse->db;
86212 Db *pDb;
86213 Vdbe *v = sqlite3GetVdbe(pParse);
86214 int aRoot[ArraySize(aTable)];
86215 u8 aCreateTbl[ArraySize(aTable)];
86217 if( v==0 ) return;
86218 assert( sqlite3BtreeHoldsAllMutexes(db) );
86219 assert( sqlite3VdbeDb(v)==db );
86220 pDb = &db->aDb[iDb];
86222 /* Create new statistic tables if they do not exist, or clear them
86223 ** if they do already exist.
86225 for(i=0; i<ArraySize(aTable); i++){
86226 const char *zTab = aTable[i].zName;
86227 Table *pStat;
86228 if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
86229 if( aTable[i].zCols ){
86230 /* The sqlite_statN table does not exist. Create it. Note that a
86231 ** side-effect of the CREATE TABLE statement is to leave the rootpage
86232 ** of the new table in register pParse->regRoot. This is important
86233 ** because the OpenWrite opcode below will be needing it. */
86234 sqlite3NestedParse(pParse,
86235 "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
86237 aRoot[i] = pParse->regRoot;
86238 aCreateTbl[i] = OPFLAG_P2ISREG;
86240 }else{
86241 /* The table already exists. If zWhere is not NULL, delete all entries
86242 ** associated with the table zWhere. If zWhere is NULL, delete the
86243 ** entire contents of the table. */
86244 aRoot[i] = pStat->tnum;
86245 aCreateTbl[i] = 0;
86246 sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
86247 if( zWhere ){
86248 sqlite3NestedParse(pParse,
86249 "DELETE FROM %Q.%s WHERE %s=%Q",
86250 pDb->zName, zTab, zWhereType, zWhere
86252 }else{
86253 /* The sqlite_stat[134] table already exists. Delete all rows. */
86254 sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
86259 /* Open the sqlite_stat[134] tables for writing. */
86260 for(i=0; aTable[i].zCols; i++){
86261 assert( i<ArraySize(aTable) );
86262 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
86263 sqlite3VdbeChangeP5(v, aCreateTbl[i]);
86264 VdbeComment((v, aTable[i].zName));
86269 ** Recommended number of samples for sqlite_stat4
86271 #ifndef SQLITE_STAT4_SAMPLES
86272 # define SQLITE_STAT4_SAMPLES 24
86273 #endif
86276 ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
86277 ** share an instance of the following structure to hold their state
86278 ** information.
86280 typedef struct Stat4Accum Stat4Accum;
86281 typedef struct Stat4Sample Stat4Sample;
86282 struct Stat4Sample {
86283 tRowcnt *anEq; /* sqlite_stat4.nEq */
86284 tRowcnt *anDLt; /* sqlite_stat4.nDLt */
86285 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86286 tRowcnt *anLt; /* sqlite_stat4.nLt */
86287 union {
86288 i64 iRowid; /* Rowid in main table of the key */
86289 u8 *aRowid; /* Key for WITHOUT ROWID tables */
86290 } u;
86291 u32 nRowid; /* Sizeof aRowid[] */
86292 u8 isPSample; /* True if a periodic sample */
86293 int iCol; /* If !isPSample, the reason for inclusion */
86294 u32 iHash; /* Tiebreaker hash */
86295 #endif
86297 struct Stat4Accum {
86298 tRowcnt nRow; /* Number of rows in the entire table */
86299 tRowcnt nPSample; /* How often to do a periodic sample */
86300 int nCol; /* Number of columns in index + pk/rowid */
86301 int nKeyCol; /* Number of index columns w/o the pk/rowid */
86302 int mxSample; /* Maximum number of samples to accumulate */
86303 Stat4Sample current; /* Current row as a Stat4Sample */
86304 u32 iPrn; /* Pseudo-random number used for sampling */
86305 Stat4Sample *aBest; /* Array of nCol best samples */
86306 int iMin; /* Index in a[] of entry with minimum score */
86307 int nSample; /* Current number of samples */
86308 int iGet; /* Index of current sample accessed by stat_get() */
86309 Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
86310 sqlite3 *db; /* Database connection, for malloc() */
86313 /* Reclaim memory used by a Stat4Sample
86315 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86316 static void sampleClear(sqlite3 *db, Stat4Sample *p){
86317 assert( db!=0 );
86318 if( p->nRowid ){
86319 sqlite3DbFree(db, p->u.aRowid);
86320 p->nRowid = 0;
86323 #endif
86325 /* Initialize the BLOB value of a ROWID
86327 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86328 static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
86329 assert( db!=0 );
86330 if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
86331 p->u.aRowid = sqlite3DbMallocRaw(db, n);
86332 if( p->u.aRowid ){
86333 p->nRowid = n;
86334 memcpy(p->u.aRowid, pData, n);
86335 }else{
86336 p->nRowid = 0;
86339 #endif
86341 /* Initialize the INTEGER value of a ROWID.
86343 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86344 static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
86345 assert( db!=0 );
86346 if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
86347 p->nRowid = 0;
86348 p->u.iRowid = iRowid;
86350 #endif
86354 ** Copy the contents of object (*pFrom) into (*pTo).
86356 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86357 static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
86358 pTo->isPSample = pFrom->isPSample;
86359 pTo->iCol = pFrom->iCol;
86360 pTo->iHash = pFrom->iHash;
86361 memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
86362 memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
86363 memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
86364 if( pFrom->nRowid ){
86365 sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
86366 }else{
86367 sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
86370 #endif
86373 ** Reclaim all memory of a Stat4Accum structure.
86375 static void stat4Destructor(void *pOld){
86376 Stat4Accum *p = (Stat4Accum*)pOld;
86377 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86378 int i;
86379 for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
86380 for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
86381 sampleClear(p->db, &p->current);
86382 #endif
86383 sqlite3DbFree(p->db, p);
86387 ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
86388 ** are:
86389 ** N: The number of columns in the index including the rowid/pk (note 1)
86390 ** K: The number of columns in the index excluding the rowid/pk.
86391 ** C: The number of rows in the index (note 2)
86393 ** Note 1: In the special case of the covering index that implements a
86394 ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
86395 ** total number of columns in the table.
86397 ** Note 2: C is only used for STAT3 and STAT4.
86399 ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
86400 ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
86401 ** PRIMARY KEY of the table. The covering index that implements the
86402 ** original WITHOUT ROWID table as N==K as a special case.
86404 ** This routine allocates the Stat4Accum object in heap memory. The return
86405 ** value is a pointer to the Stat4Accum object. The datatype of the
86406 ** return value is BLOB, but it is really just a pointer to the Stat4Accum
86407 ** object.
86409 static void statInit(
86410 sqlite3_context *context,
86411 int argc,
86412 sqlite3_value **argv
86414 Stat4Accum *p;
86415 int nCol; /* Number of columns in index being sampled */
86416 int nKeyCol; /* Number of key columns */
86417 int nColUp; /* nCol rounded up for alignment */
86418 int n; /* Bytes of space to allocate */
86419 sqlite3 *db; /* Database connection */
86420 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86421 int mxSample = SQLITE_STAT4_SAMPLES;
86422 #endif
86424 /* Decode the three function arguments */
86425 UNUSED_PARAMETER(argc);
86426 nCol = sqlite3_value_int(argv[0]);
86427 assert( nCol>0 );
86428 nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
86429 nKeyCol = sqlite3_value_int(argv[1]);
86430 assert( nKeyCol<=nCol );
86431 assert( nKeyCol>0 );
86433 /* Allocate the space required for the Stat4Accum object */
86434 n = sizeof(*p)
86435 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
86436 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
86437 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86438 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
86439 + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
86440 + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
86441 #endif
86443 db = sqlite3_context_db_handle(context);
86444 p = sqlite3DbMallocZero(db, n);
86445 if( p==0 ){
86446 sqlite3_result_error_nomem(context);
86447 return;
86450 p->db = db;
86451 p->nRow = 0;
86452 p->nCol = nCol;
86453 p->nKeyCol = nKeyCol;
86454 p->current.anDLt = (tRowcnt*)&p[1];
86455 p->current.anEq = &p->current.anDLt[nColUp];
86457 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86459 u8 *pSpace; /* Allocated space not yet assigned */
86460 int i; /* Used to iterate through p->aSample[] */
86462 p->iGet = -1;
86463 p->mxSample = mxSample;
86464 p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
86465 p->current.anLt = &p->current.anEq[nColUp];
86466 p->iPrn = nCol*0x689e962d ^ sqlite3_value_int(argv[2])*0xd0944565;
86468 /* Set up the Stat4Accum.a[] and aBest[] arrays */
86469 p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
86470 p->aBest = &p->a[mxSample];
86471 pSpace = (u8*)(&p->a[mxSample+nCol]);
86472 for(i=0; i<(mxSample+nCol); i++){
86473 p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
86474 p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
86475 p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
86477 assert( (pSpace - (u8*)p)==n );
86479 for(i=0; i<nCol; i++){
86480 p->aBest[i].iCol = i;
86483 #endif
86485 /* Return a pointer to the allocated object to the caller. Note that
86486 ** only the pointer (the 2nd parameter) matters. The size of the object
86487 ** (given by the 3rd parameter) is never used and can be any positive
86488 ** value. */
86489 sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
86491 static const FuncDef statInitFuncdef = {
86492 2+IsStat34, /* nArg */
86493 SQLITE_UTF8, /* funcFlags */
86494 0, /* pUserData */
86495 0, /* pNext */
86496 statInit, /* xFunc */
86497 0, /* xStep */
86498 0, /* xFinalize */
86499 "stat_init", /* zName */
86500 0, /* pHash */
86501 0 /* pDestructor */
86504 #ifdef SQLITE_ENABLE_STAT4
86506 ** pNew and pOld are both candidate non-periodic samples selected for
86507 ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
86508 ** considering only any trailing columns and the sample hash value, this
86509 ** function returns true if sample pNew is to be preferred over pOld.
86510 ** In other words, if we assume that the cardinalities of the selected
86511 ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
86513 ** This function assumes that for each argument sample, the contents of
86514 ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
86516 static int sampleIsBetterPost(
86517 Stat4Accum *pAccum,
86518 Stat4Sample *pNew,
86519 Stat4Sample *pOld
86521 int nCol = pAccum->nCol;
86522 int i;
86523 assert( pNew->iCol==pOld->iCol );
86524 for(i=pNew->iCol+1; i<nCol; i++){
86525 if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
86526 if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
86528 if( pNew->iHash>pOld->iHash ) return 1;
86529 return 0;
86531 #endif
86533 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86535 ** Return true if pNew is to be preferred over pOld.
86537 ** This function assumes that for each argument sample, the contents of
86538 ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
86540 static int sampleIsBetter(
86541 Stat4Accum *pAccum,
86542 Stat4Sample *pNew,
86543 Stat4Sample *pOld
86545 tRowcnt nEqNew = pNew->anEq[pNew->iCol];
86546 tRowcnt nEqOld = pOld->anEq[pOld->iCol];
86548 assert( pOld->isPSample==0 && pNew->isPSample==0 );
86549 assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
86551 if( (nEqNew>nEqOld) ) return 1;
86552 #ifdef SQLITE_ENABLE_STAT4
86553 if( nEqNew==nEqOld ){
86554 if( pNew->iCol<pOld->iCol ) return 1;
86555 return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
86557 return 0;
86558 #else
86559 return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
86560 #endif
86564 ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
86565 ** remove the least desirable sample from p->a[] to make room.
86567 static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
86568 Stat4Sample *pSample = 0;
86569 int i;
86571 assert( IsStat4 || nEqZero==0 );
86573 #ifdef SQLITE_ENABLE_STAT4
86574 if( pNew->isPSample==0 ){
86575 Stat4Sample *pUpgrade = 0;
86576 assert( pNew->anEq[pNew->iCol]>0 );
86578 /* This sample is being added because the prefix that ends in column
86579 ** iCol occurs many times in the table. However, if we have already
86580 ** added a sample that shares this prefix, there is no need to add
86581 ** this one. Instead, upgrade the priority of the highest priority
86582 ** existing sample that shares this prefix. */
86583 for(i=p->nSample-1; i>=0; i--){
86584 Stat4Sample *pOld = &p->a[i];
86585 if( pOld->anEq[pNew->iCol]==0 ){
86586 if( pOld->isPSample ) return;
86587 assert( pOld->iCol>pNew->iCol );
86588 assert( sampleIsBetter(p, pNew, pOld) );
86589 if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
86590 pUpgrade = pOld;
86594 if( pUpgrade ){
86595 pUpgrade->iCol = pNew->iCol;
86596 pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
86597 goto find_new_min;
86600 #endif
86602 /* If necessary, remove sample iMin to make room for the new sample. */
86603 if( p->nSample>=p->mxSample ){
86604 Stat4Sample *pMin = &p->a[p->iMin];
86605 tRowcnt *anEq = pMin->anEq;
86606 tRowcnt *anLt = pMin->anLt;
86607 tRowcnt *anDLt = pMin->anDLt;
86608 sampleClear(p->db, pMin);
86609 memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
86610 pSample = &p->a[p->nSample-1];
86611 pSample->nRowid = 0;
86612 pSample->anEq = anEq;
86613 pSample->anDLt = anDLt;
86614 pSample->anLt = anLt;
86615 p->nSample = p->mxSample-1;
86618 /* The "rows less-than" for the rowid column must be greater than that
86619 ** for the last sample in the p->a[] array. Otherwise, the samples would
86620 ** be out of order. */
86621 #ifdef SQLITE_ENABLE_STAT4
86622 assert( p->nSample==0
86623 || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
86624 #endif
86626 /* Insert the new sample */
86627 pSample = &p->a[p->nSample];
86628 sampleCopy(p, pSample, pNew);
86629 p->nSample++;
86631 /* Zero the first nEqZero entries in the anEq[] array. */
86632 memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
86634 #ifdef SQLITE_ENABLE_STAT4
86635 find_new_min:
86636 #endif
86637 if( p->nSample>=p->mxSample ){
86638 int iMin = -1;
86639 for(i=0; i<p->mxSample; i++){
86640 if( p->a[i].isPSample ) continue;
86641 if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
86642 iMin = i;
86645 assert( iMin>=0 );
86646 p->iMin = iMin;
86649 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
86652 ** Field iChng of the index being scanned has changed. So at this point
86653 ** p->current contains a sample that reflects the previous row of the
86654 ** index. The value of anEq[iChng] and subsequent anEq[] elements are
86655 ** correct at this point.
86657 static void samplePushPrevious(Stat4Accum *p, int iChng){
86658 #ifdef SQLITE_ENABLE_STAT4
86659 int i;
86661 /* Check if any samples from the aBest[] array should be pushed
86662 ** into IndexSample.a[] at this point. */
86663 for(i=(p->nCol-2); i>=iChng; i--){
86664 Stat4Sample *pBest = &p->aBest[i];
86665 pBest->anEq[i] = p->current.anEq[i];
86666 if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
86667 sampleInsert(p, pBest, i);
86671 /* Update the anEq[] fields of any samples already collected. */
86672 for(i=p->nSample-1; i>=0; i--){
86673 int j;
86674 for(j=iChng; j<p->nCol; j++){
86675 if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
86678 #endif
86680 #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
86681 if( iChng==0 ){
86682 tRowcnt nLt = p->current.anLt[0];
86683 tRowcnt nEq = p->current.anEq[0];
86685 /* Check if this is to be a periodic sample. If so, add it. */
86686 if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
86687 p->current.isPSample = 1;
86688 sampleInsert(p, &p->current, 0);
86689 p->current.isPSample = 0;
86690 }else
86692 /* Or if it is a non-periodic sample. Add it in this case too. */
86693 if( p->nSample<p->mxSample
86694 || sampleIsBetter(p, &p->current, &p->a[p->iMin])
86696 sampleInsert(p, &p->current, 0);
86699 #endif
86701 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
86702 UNUSED_PARAMETER( p );
86703 UNUSED_PARAMETER( iChng );
86704 #endif
86708 ** Implementation of the stat_push SQL function: stat_push(P,C,R)
86709 ** Arguments:
86711 ** P Pointer to the Stat4Accum object created by stat_init()
86712 ** C Index of left-most column to differ from previous row
86713 ** R Rowid for the current row. Might be a key record for
86714 ** WITHOUT ROWID tables.
86716 ** This SQL function always returns NULL. It's purpose it to accumulate
86717 ** statistical data and/or samples in the Stat4Accum object about the
86718 ** index being analyzed. The stat_get() SQL function will later be used to
86719 ** extract relevant information for constructing the sqlite_statN tables.
86721 ** The R parameter is only used for STAT3 and STAT4
86723 static void statPush(
86724 sqlite3_context *context,
86725 int argc,
86726 sqlite3_value **argv
86728 int i;
86730 /* The three function arguments */
86731 Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
86732 int iChng = sqlite3_value_int(argv[1]);
86734 UNUSED_PARAMETER( argc );
86735 UNUSED_PARAMETER( context );
86736 assert( p->nCol>0 );
86737 assert( iChng<p->nCol );
86739 if( p->nRow==0 ){
86740 /* This is the first call to this function. Do initialization. */
86741 for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
86742 }else{
86743 /* Second and subsequent calls get processed here */
86744 samplePushPrevious(p, iChng);
86746 /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
86747 ** to the current row of the index. */
86748 for(i=0; i<iChng; i++){
86749 p->current.anEq[i]++;
86751 for(i=iChng; i<p->nCol; i++){
86752 p->current.anDLt[i]++;
86753 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86754 p->current.anLt[i] += p->current.anEq[i];
86755 #endif
86756 p->current.anEq[i] = 1;
86759 p->nRow++;
86760 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86761 if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
86762 sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
86763 }else{
86764 sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
86765 sqlite3_value_blob(argv[2]));
86767 p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
86768 #endif
86770 #ifdef SQLITE_ENABLE_STAT4
86772 tRowcnt nLt = p->current.anLt[p->nCol-1];
86774 /* Check if this is to be a periodic sample. If so, add it. */
86775 if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
86776 p->current.isPSample = 1;
86777 p->current.iCol = 0;
86778 sampleInsert(p, &p->current, p->nCol-1);
86779 p->current.isPSample = 0;
86782 /* Update the aBest[] array. */
86783 for(i=0; i<(p->nCol-1); i++){
86784 p->current.iCol = i;
86785 if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
86786 sampleCopy(p, &p->aBest[i], &p->current);
86790 #endif
86792 static const FuncDef statPushFuncdef = {
86793 2+IsStat34, /* nArg */
86794 SQLITE_UTF8, /* funcFlags */
86795 0, /* pUserData */
86796 0, /* pNext */
86797 statPush, /* xFunc */
86798 0, /* xStep */
86799 0, /* xFinalize */
86800 "stat_push", /* zName */
86801 0, /* pHash */
86802 0 /* pDestructor */
86805 #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
86806 #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
86807 #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
86808 #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
86809 #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
86812 ** Implementation of the stat_get(P,J) SQL function. This routine is
86813 ** used to query statistical information that has been gathered into
86814 ** the Stat4Accum object by prior calls to stat_push(). The P parameter
86815 ** has type BLOB but it is really just a pointer to the Stat4Accum object.
86816 ** The content to returned is determined by the parameter J
86817 ** which is one of the STAT_GET_xxxx values defined above.
86819 ** If neither STAT3 nor STAT4 are enabled, then J is always
86820 ** STAT_GET_STAT1 and is hence omitted and this routine becomes
86821 ** a one-parameter function, stat_get(P), that always returns the
86822 ** stat1 table entry information.
86824 static void statGet(
86825 sqlite3_context *context,
86826 int argc,
86827 sqlite3_value **argv
86829 Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
86830 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86831 /* STAT3 and STAT4 have a parameter on this routine. */
86832 int eCall = sqlite3_value_int(argv[1]);
86833 assert( argc==2 );
86834 assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
86835 || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
86836 || eCall==STAT_GET_NDLT
86838 if( eCall==STAT_GET_STAT1 )
86839 #else
86840 assert( argc==1 );
86841 #endif
86843 /* Return the value to store in the "stat" column of the sqlite_stat1
86844 ** table for this index.
86846 ** The value is a string composed of a list of integers describing
86847 ** the index. The first integer in the list is the total number of
86848 ** entries in the index. There is one additional integer in the list
86849 ** for each indexed column. This additional integer is an estimate of
86850 ** the number of rows matched by a stabbing query on the index using
86851 ** a key with the corresponding number of fields. In other words,
86852 ** if the index is on columns (a,b) and the sqlite_stat1 value is
86853 ** "100 10 2", then SQLite estimates that:
86855 ** * the index contains 100 rows,
86856 ** * "WHERE a=?" matches 10 rows, and
86857 ** * "WHERE a=? AND b=?" matches 2 rows.
86859 ** If D is the count of distinct values and K is the total number of
86860 ** rows, then each estimate is computed as:
86862 ** I = (K+D-1)/D
86864 char *z;
86865 int i;
86867 char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
86868 if( zRet==0 ){
86869 sqlite3_result_error_nomem(context);
86870 return;
86873 sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
86874 z = zRet + sqlite3Strlen30(zRet);
86875 for(i=0; i<p->nKeyCol; i++){
86876 u64 nDistinct = p->current.anDLt[i] + 1;
86877 u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
86878 sqlite3_snprintf(24, z, " %llu", iVal);
86879 z += sqlite3Strlen30(z);
86880 assert( p->current.anEq[i] );
86882 assert( z[0]=='\0' && z>zRet );
86884 sqlite3_result_text(context, zRet, -1, sqlite3_free);
86886 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86887 else if( eCall==STAT_GET_ROWID ){
86888 if( p->iGet<0 ){
86889 samplePushPrevious(p, 0);
86890 p->iGet = 0;
86892 if( p->iGet<p->nSample ){
86893 Stat4Sample *pS = p->a + p->iGet;
86894 if( pS->nRowid==0 ){
86895 sqlite3_result_int64(context, pS->u.iRowid);
86896 }else{
86897 sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
86898 SQLITE_TRANSIENT);
86901 }else{
86902 tRowcnt *aCnt = 0;
86904 assert( p->iGet<p->nSample );
86905 switch( eCall ){
86906 case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
86907 case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
86908 default: {
86909 aCnt = p->a[p->iGet].anDLt;
86910 p->iGet++;
86911 break;
86915 if( IsStat3 ){
86916 sqlite3_result_int64(context, (i64)aCnt[0]);
86917 }else{
86918 char *zRet = sqlite3MallocZero(p->nCol * 25);
86919 if( zRet==0 ){
86920 sqlite3_result_error_nomem(context);
86921 }else{
86922 int i;
86923 char *z = zRet;
86924 for(i=0; i<p->nCol; i++){
86925 sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
86926 z += sqlite3Strlen30(z);
86928 assert( z[0]=='\0' && z>zRet );
86929 z[-1] = '\0';
86930 sqlite3_result_text(context, zRet, -1, sqlite3_free);
86934 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
86935 #ifndef SQLITE_DEBUG
86936 UNUSED_PARAMETER( argc );
86937 #endif
86939 static const FuncDef statGetFuncdef = {
86940 1+IsStat34, /* nArg */
86941 SQLITE_UTF8, /* funcFlags */
86942 0, /* pUserData */
86943 0, /* pNext */
86944 statGet, /* xFunc */
86945 0, /* xStep */
86946 0, /* xFinalize */
86947 "stat_get", /* zName */
86948 0, /* pHash */
86949 0 /* pDestructor */
86952 static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
86953 assert( regOut!=regStat4 && regOut!=regStat4+1 );
86954 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86955 sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
86956 #elif SQLITE_DEBUG
86957 assert( iParam==STAT_GET_STAT1 );
86958 #else
86959 UNUSED_PARAMETER( iParam );
86960 #endif
86961 sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
86962 sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
86963 sqlite3VdbeChangeP5(v, 1 + IsStat34);
86967 ** Generate code to do an analysis of all indices associated with
86968 ** a single table.
86970 static void analyzeOneTable(
86971 Parse *pParse, /* Parser context */
86972 Table *pTab, /* Table whose indices are to be analyzed */
86973 Index *pOnlyIdx, /* If not NULL, only analyze this one index */
86974 int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
86975 int iMem, /* Available memory locations begin here */
86976 int iTab /* Next available cursor */
86978 sqlite3 *db = pParse->db; /* Database handle */
86979 Index *pIdx; /* An index to being analyzed */
86980 int iIdxCur; /* Cursor open on index being analyzed */
86981 int iTabCur; /* Table cursor */
86982 Vdbe *v; /* The virtual machine being built up */
86983 int i; /* Loop counter */
86984 int jZeroRows = -1; /* Jump from here if number of rows is zero */
86985 int iDb; /* Index of database containing pTab */
86986 u8 needTableCnt = 1; /* True to count the table */
86987 int regNewRowid = iMem++; /* Rowid for the inserted record */
86988 int regStat4 = iMem++; /* Register to hold Stat4Accum object */
86989 int regChng = iMem++; /* Index of changed index field */
86990 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86991 int regRowid = iMem++; /* Rowid argument passed to stat_push() */
86992 #endif
86993 int regTemp = iMem++; /* Temporary use register */
86994 int regTabname = iMem++; /* Register containing table name */
86995 int regIdxname = iMem++; /* Register containing index name */
86996 int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
86997 int regPrev = iMem; /* MUST BE LAST (see below) */
86999 pParse->nMem = MAX(pParse->nMem, iMem);
87000 v = sqlite3GetVdbe(pParse);
87001 if( v==0 || NEVER(pTab==0) ){
87002 return;
87004 if( pTab->tnum==0 ){
87005 /* Do not gather statistics on views or virtual tables */
87006 return;
87008 if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
87009 /* Do not gather statistics on system tables */
87010 return;
87012 assert( sqlite3BtreeHoldsAllMutexes(db) );
87013 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
87014 assert( iDb>=0 );
87015 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
87016 #ifndef SQLITE_OMIT_AUTHORIZATION
87017 if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
87018 db->aDb[iDb].zName ) ){
87019 return;
87021 #endif
87023 /* Establish a read-lock on the table at the shared-cache level.
87024 ** Open a read-only cursor on the table. Also allocate a cursor number
87025 ** to use for scanning indexes (iIdxCur). No index cursor is opened at
87026 ** this time though. */
87027 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
87028 iTabCur = iTab++;
87029 iIdxCur = iTab++;
87030 pParse->nTab = MAX(pParse->nTab, iTab);
87031 sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
87032 sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
87034 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
87035 int nCol; /* Number of columns in pIdx. "N" */
87036 int addrRewind; /* Address of "OP_Rewind iIdxCur" */
87037 int addrNextRow; /* Address of "next_row:" */
87038 const char *zIdxName; /* Name of the index */
87039 int nColTest; /* Number of columns to test for changes */
87041 if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
87042 if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
87043 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
87044 nCol = pIdx->nKeyCol;
87045 zIdxName = pTab->zName;
87046 nColTest = nCol - 1;
87047 }else{
87048 nCol = pIdx->nColumn;
87049 zIdxName = pIdx->zName;
87050 nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
87053 /* Populate the register containing the index name. */
87054 sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, zIdxName, 0);
87055 VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
87058 ** Pseudo-code for loop that calls stat_push():
87060 ** Rewind csr
87061 ** if eof(csr) goto end_of_scan;
87062 ** regChng = 0
87063 ** goto chng_addr_0;
87065 ** next_row:
87066 ** regChng = 0
87067 ** if( idx(0) != regPrev(0) ) goto chng_addr_0
87068 ** regChng = 1
87069 ** if( idx(1) != regPrev(1) ) goto chng_addr_1
87070 ** ...
87071 ** regChng = N
87072 ** goto chng_addr_N
87074 ** chng_addr_0:
87075 ** regPrev(0) = idx(0)
87076 ** chng_addr_1:
87077 ** regPrev(1) = idx(1)
87078 ** ...
87080 ** endDistinctTest:
87081 ** regRowid = idx(rowid)
87082 ** stat_push(P, regChng, regRowid)
87083 ** Next csr
87084 ** if !eof(csr) goto next_row;
87086 ** end_of_scan:
87089 /* Make sure there are enough memory cells allocated to accommodate
87090 ** the regPrev array and a trailing rowid (the rowid slot is required
87091 ** when building a record to insert into the sample column of
87092 ** the sqlite_stat4 table. */
87093 pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
87095 /* Open a read-only cursor on the index being analyzed. */
87096 assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
87097 sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
87098 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
87099 VdbeComment((v, "%s", pIdx->zName));
87101 /* Invoke the stat_init() function. The arguments are:
87103 ** (1) the number of columns in the index including the rowid
87104 ** (or for a WITHOUT ROWID table, the number of PK columns),
87105 ** (2) the number of columns in the key without the rowid/pk
87106 ** (3) the number of rows in the index,
87109 ** The third argument is only used for STAT3 and STAT4
87111 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87112 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
87113 #endif
87114 sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
87115 sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
87116 sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
87117 sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
87118 sqlite3VdbeChangeP5(v, 2+IsStat34);
87120 /* Implementation of the following:
87122 ** Rewind csr
87123 ** if eof(csr) goto end_of_scan;
87124 ** regChng = 0
87125 ** goto next_push_0;
87128 addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
87129 VdbeCoverage(v);
87130 sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
87131 addrNextRow = sqlite3VdbeCurrentAddr(v);
87133 if( nColTest>0 ){
87134 int endDistinctTest = sqlite3VdbeMakeLabel(v);
87135 int *aGotoChng; /* Array of jump instruction addresses */
87136 aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*nColTest);
87137 if( aGotoChng==0 ) continue;
87140 ** next_row:
87141 ** regChng = 0
87142 ** if( idx(0) != regPrev(0) ) goto chng_addr_0
87143 ** regChng = 1
87144 ** if( idx(1) != regPrev(1) ) goto chng_addr_1
87145 ** ...
87146 ** regChng = N
87147 ** goto endDistinctTest
87149 sqlite3VdbeAddOp0(v, OP_Goto);
87150 addrNextRow = sqlite3VdbeCurrentAddr(v);
87151 if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
87152 /* For a single-column UNIQUE index, once we have found a non-NULL
87153 ** row, we know that all the rest will be distinct, so skip
87154 ** subsequent distinctness tests. */
87155 sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
87156 VdbeCoverage(v);
87158 for(i=0; i<nColTest; i++){
87159 char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
87160 sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
87161 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
87162 aGotoChng[i] =
87163 sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
87164 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
87165 VdbeCoverage(v);
87167 sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
87168 sqlite3VdbeAddOp2(v, OP_Goto, 0, endDistinctTest);
87172 ** chng_addr_0:
87173 ** regPrev(0) = idx(0)
87174 ** chng_addr_1:
87175 ** regPrev(1) = idx(1)
87176 ** ...
87178 sqlite3VdbeJumpHere(v, addrNextRow-1);
87179 for(i=0; i<nColTest; i++){
87180 sqlite3VdbeJumpHere(v, aGotoChng[i]);
87181 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
87183 sqlite3VdbeResolveLabel(v, endDistinctTest);
87184 sqlite3DbFree(db, aGotoChng);
87188 ** chng_addr_N:
87189 ** regRowid = idx(rowid) // STAT34 only
87190 ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
87191 ** Next csr
87192 ** if !eof(csr) goto next_row;
87194 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87195 assert( regRowid==(regStat4+2) );
87196 if( HasRowid(pTab) ){
87197 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
87198 }else{
87199 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
87200 int j, k, regKey;
87201 regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
87202 for(j=0; j<pPk->nKeyCol; j++){
87203 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
87204 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
87205 VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
87207 sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
87208 sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
87210 #endif
87211 assert( regChng==(regStat4+1) );
87212 sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
87213 sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
87214 sqlite3VdbeChangeP5(v, 2+IsStat34);
87215 sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
87217 /* Add the entry to the stat1 table. */
87218 callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
87219 assert( "BBB"[0]==SQLITE_AFF_TEXT );
87220 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
87221 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
87222 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
87223 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
87225 /* Add the entries to the stat3 or stat4 table. */
87226 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87228 int regEq = regStat1;
87229 int regLt = regStat1+1;
87230 int regDLt = regStat1+2;
87231 int regSample = regStat1+3;
87232 int regCol = regStat1+4;
87233 int regSampleRowid = regCol + nCol;
87234 int addrNext;
87235 int addrIsNull;
87236 u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
87238 pParse->nMem = MAX(pParse->nMem, regCol+nCol);
87240 addrNext = sqlite3VdbeCurrentAddr(v);
87241 callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
87242 addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
87243 VdbeCoverage(v);
87244 callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
87245 callStatGet(v, regStat4, STAT_GET_NLT, regLt);
87246 callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
87247 sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
87248 /* We know that the regSampleRowid row exists because it was read by
87249 ** the previous loop. Thus the not-found jump of seekOp will never
87250 ** be taken */
87251 VdbeCoverageNeverTaken(v);
87252 #ifdef SQLITE_ENABLE_STAT3
87253 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
87254 pIdx->aiColumn[0], regSample);
87255 #else
87256 for(i=0; i<nCol; i++){
87257 i16 iCol = pIdx->aiColumn[i];
87258 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
87260 sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
87261 #endif
87262 sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
87263 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
87264 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
87265 sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
87266 sqlite3VdbeJumpHere(v, addrIsNull);
87268 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
87270 /* End of analysis */
87271 sqlite3VdbeJumpHere(v, addrRewind);
87275 /* Create a single sqlite_stat1 entry containing NULL as the index
87276 ** name and the row count as the content.
87278 if( pOnlyIdx==0 && needTableCnt ){
87279 VdbeComment((v, "%s", pTab->zName));
87280 sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
87281 jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
87282 sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
87283 assert( "BBB"[0]==SQLITE_AFF_TEXT );
87284 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
87285 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
87286 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
87287 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
87288 sqlite3VdbeJumpHere(v, jZeroRows);
87294 ** Generate code that will cause the most recent index analysis to
87295 ** be loaded into internal hash tables where is can be used.
87297 static void loadAnalysis(Parse *pParse, int iDb){
87298 Vdbe *v = sqlite3GetVdbe(pParse);
87299 if( v ){
87300 sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
87305 ** Generate code that will do an analysis of an entire database
87307 static void analyzeDatabase(Parse *pParse, int iDb){
87308 sqlite3 *db = pParse->db;
87309 Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
87310 HashElem *k;
87311 int iStatCur;
87312 int iMem;
87313 int iTab;
87315 sqlite3BeginWriteOperation(pParse, 0, iDb);
87316 iStatCur = pParse->nTab;
87317 pParse->nTab += 3;
87318 openStatTable(pParse, iDb, iStatCur, 0, 0);
87319 iMem = pParse->nMem+1;
87320 iTab = pParse->nTab;
87321 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
87322 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
87323 Table *pTab = (Table*)sqliteHashData(k);
87324 analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
87326 loadAnalysis(pParse, iDb);
87330 ** Generate code that will do an analysis of a single table in
87331 ** a database. If pOnlyIdx is not NULL then it is a single index
87332 ** in pTab that should be analyzed.
87334 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
87335 int iDb;
87336 int iStatCur;
87338 assert( pTab!=0 );
87339 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
87340 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
87341 sqlite3BeginWriteOperation(pParse, 0, iDb);
87342 iStatCur = pParse->nTab;
87343 pParse->nTab += 3;
87344 if( pOnlyIdx ){
87345 openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
87346 }else{
87347 openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
87349 analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
87350 loadAnalysis(pParse, iDb);
87354 ** Generate code for the ANALYZE command. The parser calls this routine
87355 ** when it recognizes an ANALYZE command.
87357 ** ANALYZE -- 1
87358 ** ANALYZE <database> -- 2
87359 ** ANALYZE ?<database>.?<tablename> -- 3
87361 ** Form 1 causes all indices in all attached databases to be analyzed.
87362 ** Form 2 analyzes all indices the single database named.
87363 ** Form 3 analyzes all indices associated with the named table.
87365 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
87366 sqlite3 *db = pParse->db;
87367 int iDb;
87368 int i;
87369 char *z, *zDb;
87370 Table *pTab;
87371 Index *pIdx;
87372 Token *pTableName;
87373 Vdbe *v;
87375 /* Read the database schema. If an error occurs, leave an error message
87376 ** and code in pParse and return NULL. */
87377 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
87378 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
87379 return;
87382 assert( pName2!=0 || pName1==0 );
87383 if( pName1==0 ){
87384 /* Form 1: Analyze everything */
87385 for(i=0; i<db->nDb; i++){
87386 if( i==1 ) continue; /* Do not analyze the TEMP database */
87387 analyzeDatabase(pParse, i);
87389 }else if( pName2->n==0 ){
87390 /* Form 2: Analyze the database or table named */
87391 iDb = sqlite3FindDb(db, pName1);
87392 if( iDb>=0 ){
87393 analyzeDatabase(pParse, iDb);
87394 }else{
87395 z = sqlite3NameFromToken(db, pName1);
87396 if( z ){
87397 if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
87398 analyzeTable(pParse, pIdx->pTable, pIdx);
87399 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
87400 analyzeTable(pParse, pTab, 0);
87402 sqlite3DbFree(db, z);
87405 }else{
87406 /* Form 3: Analyze the fully qualified table name */
87407 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
87408 if( iDb>=0 ){
87409 zDb = db->aDb[iDb].zName;
87410 z = sqlite3NameFromToken(db, pTableName);
87411 if( z ){
87412 if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
87413 analyzeTable(pParse, pIdx->pTable, pIdx);
87414 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
87415 analyzeTable(pParse, pTab, 0);
87417 sqlite3DbFree(db, z);
87421 v = sqlite3GetVdbe(pParse);
87422 if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
87426 ** Used to pass information from the analyzer reader through to the
87427 ** callback routine.
87429 typedef struct analysisInfo analysisInfo;
87430 struct analysisInfo {
87431 sqlite3 *db;
87432 const char *zDatabase;
87436 ** The first argument points to a nul-terminated string containing a
87437 ** list of space separated integers. Read the first nOut of these into
87438 ** the array aOut[].
87440 static void decodeIntArray(
87441 char *zIntArray, /* String containing int array to decode */
87442 int nOut, /* Number of slots in aOut[] */
87443 tRowcnt *aOut, /* Store integers here */
87444 LogEst *aLog, /* Or, if aOut==0, here */
87445 Index *pIndex /* Handle extra flags for this index, if not NULL */
87447 char *z = zIntArray;
87448 int c;
87449 int i;
87450 tRowcnt v;
87452 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87453 if( z==0 ) z = "";
87454 #else
87455 assert( z!=0 );
87456 #endif
87457 for(i=0; *z && i<nOut; i++){
87458 v = 0;
87459 while( (c=z[0])>='0' && c<='9' ){
87460 v = v*10 + c - '0';
87461 z++;
87463 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87464 if( aOut ) aOut[i] = v;
87465 if( aLog ) aLog[i] = sqlite3LogEst(v);
87466 #else
87467 assert( aOut==0 );
87468 UNUSED_PARAMETER(aOut);
87469 assert( aLog!=0 );
87470 aLog[i] = sqlite3LogEst(v);
87471 #endif
87472 if( *z==' ' ) z++;
87474 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
87475 assert( pIndex!=0 );
87476 #else
87477 if( pIndex )
87478 #endif
87479 while( z[0] ){
87480 if( sqlite3_strglob("unordered*", z)==0 ){
87481 pIndex->bUnordered = 1;
87482 }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
87483 pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
87485 #ifdef SQLITE_ENABLE_COSTMULT
87486 else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
87487 pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
87489 #endif
87490 while( z[0]!=0 && z[0]!=' ' ) z++;
87491 while( z[0]==' ' ) z++;
87496 ** This callback is invoked once for each index when reading the
87497 ** sqlite_stat1 table.
87499 ** argv[0] = name of the table
87500 ** argv[1] = name of the index (might be NULL)
87501 ** argv[2] = results of analysis - on integer for each column
87503 ** Entries for which argv[1]==NULL simply record the number of rows in
87504 ** the table.
87506 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
87507 analysisInfo *pInfo = (analysisInfo*)pData;
87508 Index *pIndex;
87509 Table *pTable;
87510 const char *z;
87512 assert( argc==3 );
87513 UNUSED_PARAMETER2(NotUsed, argc);
87515 if( argv==0 || argv[0]==0 || argv[2]==0 ){
87516 return 0;
87518 pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
87519 if( pTable==0 ){
87520 return 0;
87522 if( argv[1]==0 ){
87523 pIndex = 0;
87524 }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
87525 pIndex = sqlite3PrimaryKeyIndex(pTable);
87526 }else{
87527 pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
87529 z = argv[2];
87531 if( pIndex ){
87532 int nCol = pIndex->nKeyCol+1;
87533 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87534 tRowcnt * const aiRowEst = pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(
87535 sizeof(tRowcnt) * nCol
87537 if( aiRowEst==0 ) pInfo->db->mallocFailed = 1;
87538 #else
87539 tRowcnt * const aiRowEst = 0;
87540 #endif
87541 pIndex->bUnordered = 0;
87542 decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
87543 if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
87544 }else{
87545 Index fakeIdx;
87546 fakeIdx.szIdxRow = pTable->szTabRow;
87547 #ifdef SQLITE_ENABLE_COSTMULT
87548 fakeIdx.pTable = pTable;
87549 #endif
87550 decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
87551 pTable->szTabRow = fakeIdx.szIdxRow;
87554 return 0;
87558 ** If the Index.aSample variable is not NULL, delete the aSample[] array
87559 ** and its contents.
87561 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
87562 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87563 if( pIdx->aSample ){
87564 int j;
87565 for(j=0; j<pIdx->nSample; j++){
87566 IndexSample *p = &pIdx->aSample[j];
87567 sqlite3DbFree(db, p->p);
87569 sqlite3DbFree(db, pIdx->aSample);
87571 if( db && db->pnBytesFreed==0 ){
87572 pIdx->nSample = 0;
87573 pIdx->aSample = 0;
87575 #else
87576 UNUSED_PARAMETER(db);
87577 UNUSED_PARAMETER(pIdx);
87578 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
87581 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87583 ** Populate the pIdx->aAvgEq[] array based on the samples currently
87584 ** stored in pIdx->aSample[].
87586 static void initAvgEq(Index *pIdx){
87587 if( pIdx ){
87588 IndexSample *aSample = pIdx->aSample;
87589 IndexSample *pFinal = &aSample[pIdx->nSample-1];
87590 int iCol;
87591 int nCol = 1;
87592 if( pIdx->nSampleCol>1 ){
87593 /* If this is stat4 data, then calculate aAvgEq[] values for all
87594 ** sample columns except the last. The last is always set to 1, as
87595 ** once the trailing PK fields are considered all index keys are
87596 ** unique. */
87597 nCol = pIdx->nSampleCol-1;
87598 pIdx->aAvgEq[nCol] = 1;
87600 for(iCol=0; iCol<nCol; iCol++){
87601 int nSample = pIdx->nSample;
87602 int i; /* Used to iterate through samples */
87603 tRowcnt sumEq = 0; /* Sum of the nEq values */
87604 tRowcnt avgEq = 0;
87605 tRowcnt nRow; /* Number of rows in index */
87606 i64 nSum100 = 0; /* Number of terms contributing to sumEq */
87607 i64 nDist100; /* Number of distinct values in index */
87609 if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
87610 nRow = pFinal->anLt[iCol];
87611 nDist100 = (i64)100 * pFinal->anDLt[iCol];
87612 nSample--;
87613 }else{
87614 nRow = pIdx->aiRowEst[0];
87615 nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
87618 /* Set nSum to the number of distinct (iCol+1) field prefixes that
87619 ** occur in the stat4 table for this index. Set sumEq to the sum of
87620 ** the nEq values for column iCol for the same set (adding the value
87621 ** only once where there exist duplicate prefixes). */
87622 for(i=0; i<nSample; i++){
87623 if( i==(pIdx->nSample-1)
87624 || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
87626 sumEq += aSample[i].anEq[iCol];
87627 nSum100 += 100;
87631 if( nDist100>nSum100 ){
87632 avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
87634 if( avgEq==0 ) avgEq = 1;
87635 pIdx->aAvgEq[iCol] = avgEq;
87641 ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
87642 ** is supplied instead, find the PRIMARY KEY index for that table.
87644 static Index *findIndexOrPrimaryKey(
87645 sqlite3 *db,
87646 const char *zName,
87647 const char *zDb
87649 Index *pIdx = sqlite3FindIndex(db, zName, zDb);
87650 if( pIdx==0 ){
87651 Table *pTab = sqlite3FindTable(db, zName, zDb);
87652 if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
87654 return pIdx;
87658 ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
87659 ** into the relevant Index.aSample[] arrays.
87661 ** Arguments zSql1 and zSql2 must point to SQL statements that return
87662 ** data equivalent to the following (statements are different for stat3,
87663 ** see the caller of this function for details):
87665 ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
87666 ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
87668 ** where %Q is replaced with the database name before the SQL is executed.
87670 static int loadStatTbl(
87671 sqlite3 *db, /* Database handle */
87672 int bStat3, /* Assume single column records only */
87673 const char *zSql1, /* SQL statement 1 (see above) */
87674 const char *zSql2, /* SQL statement 2 (see above) */
87675 const char *zDb /* Database name (e.g. "main") */
87677 int rc; /* Result codes from subroutines */
87678 sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
87679 char *zSql; /* Text of the SQL statement */
87680 Index *pPrevIdx = 0; /* Previous index in the loop */
87681 IndexSample *pSample; /* A slot in pIdx->aSample[] */
87683 assert( db->lookaside.bEnabled==0 );
87684 zSql = sqlite3MPrintf(db, zSql1, zDb);
87685 if( !zSql ){
87686 return SQLITE_NOMEM;
87688 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
87689 sqlite3DbFree(db, zSql);
87690 if( rc ) return rc;
87692 while( sqlite3_step(pStmt)==SQLITE_ROW ){
87693 int nIdxCol = 1; /* Number of columns in stat4 records */
87695 char *zIndex; /* Index name */
87696 Index *pIdx; /* Pointer to the index object */
87697 int nSample; /* Number of samples */
87698 int nByte; /* Bytes of space required */
87699 int i; /* Bytes of space required */
87700 tRowcnt *pSpace;
87702 zIndex = (char *)sqlite3_column_text(pStmt, 0);
87703 if( zIndex==0 ) continue;
87704 nSample = sqlite3_column_int(pStmt, 1);
87705 pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
87706 assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
87707 /* Index.nSample is non-zero at this point if data has already been
87708 ** loaded from the stat4 table. In this case ignore stat3 data. */
87709 if( pIdx==0 || pIdx->nSample ) continue;
87710 if( bStat3==0 ){
87711 assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
87712 if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
87713 nIdxCol = pIdx->nKeyCol;
87714 }else{
87715 nIdxCol = pIdx->nColumn;
87718 pIdx->nSampleCol = nIdxCol;
87719 nByte = sizeof(IndexSample) * nSample;
87720 nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
87721 nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
87723 pIdx->aSample = sqlite3DbMallocZero(db, nByte);
87724 if( pIdx->aSample==0 ){
87725 sqlite3_finalize(pStmt);
87726 return SQLITE_NOMEM;
87728 pSpace = (tRowcnt*)&pIdx->aSample[nSample];
87729 pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
87730 for(i=0; i<nSample; i++){
87731 pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
87732 pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
87733 pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
87735 assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
87737 rc = sqlite3_finalize(pStmt);
87738 if( rc ) return rc;
87740 zSql = sqlite3MPrintf(db, zSql2, zDb);
87741 if( !zSql ){
87742 return SQLITE_NOMEM;
87744 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
87745 sqlite3DbFree(db, zSql);
87746 if( rc ) return rc;
87748 while( sqlite3_step(pStmt)==SQLITE_ROW ){
87749 char *zIndex; /* Index name */
87750 Index *pIdx; /* Pointer to the index object */
87751 int nCol = 1; /* Number of columns in index */
87753 zIndex = (char *)sqlite3_column_text(pStmt, 0);
87754 if( zIndex==0 ) continue;
87755 pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
87756 if( pIdx==0 ) continue;
87757 /* This next condition is true if data has already been loaded from
87758 ** the sqlite_stat4 table. In this case ignore stat3 data. */
87759 nCol = pIdx->nSampleCol;
87760 if( bStat3 && nCol>1 ) continue;
87761 if( pIdx!=pPrevIdx ){
87762 initAvgEq(pPrevIdx);
87763 pPrevIdx = pIdx;
87765 pSample = &pIdx->aSample[pIdx->nSample];
87766 decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
87767 decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
87768 decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
87770 /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
87771 ** This is in case the sample record is corrupted. In that case, the
87772 ** sqlite3VdbeRecordCompare() may read up to two varints past the
87773 ** end of the allocated buffer before it realizes it is dealing with
87774 ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
87775 ** a buffer overread. */
87776 pSample->n = sqlite3_column_bytes(pStmt, 4);
87777 pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
87778 if( pSample->p==0 ){
87779 sqlite3_finalize(pStmt);
87780 return SQLITE_NOMEM;
87782 memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
87783 pIdx->nSample++;
87785 rc = sqlite3_finalize(pStmt);
87786 if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
87787 return rc;
87791 ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
87792 ** the Index.aSample[] arrays of all indices.
87794 static int loadStat4(sqlite3 *db, const char *zDb){
87795 int rc = SQLITE_OK; /* Result codes from subroutines */
87797 assert( db->lookaside.bEnabled==0 );
87798 if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
87799 rc = loadStatTbl(db, 0,
87800 "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
87801 "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
87806 if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
87807 rc = loadStatTbl(db, 1,
87808 "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
87809 "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
87814 return rc;
87816 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
87819 ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
87820 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
87821 ** arrays. The contents of sqlite_stat3/4 are used to populate the
87822 ** Index.aSample[] arrays.
87824 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
87825 ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
87826 ** during compilation and the sqlite_stat3/4 table is present, no data is
87827 ** read from it.
87829 ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
87830 ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
87831 ** returned. However, in this case, data is read from the sqlite_stat1
87832 ** table (if it is present) before returning.
87834 ** If an OOM error occurs, this function always sets db->mallocFailed.
87835 ** This means if the caller does not care about other errors, the return
87836 ** code may be ignored.
87838 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
87839 analysisInfo sInfo;
87840 HashElem *i;
87841 char *zSql;
87842 int rc;
87844 assert( iDb>=0 && iDb<db->nDb );
87845 assert( db->aDb[iDb].pBt!=0 );
87847 /* Clear any prior statistics */
87848 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
87849 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
87850 Index *pIdx = sqliteHashData(i);
87851 sqlite3DefaultRowEst(pIdx);
87852 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87853 sqlite3DeleteIndexSamples(db, pIdx);
87854 pIdx->aSample = 0;
87855 #endif
87858 /* Check to make sure the sqlite_stat1 table exists */
87859 sInfo.db = db;
87860 sInfo.zDatabase = db->aDb[iDb].zName;
87861 if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
87862 return SQLITE_ERROR;
87865 /* Load new statistics out of the sqlite_stat1 table */
87866 zSql = sqlite3MPrintf(db,
87867 "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
87868 if( zSql==0 ){
87869 rc = SQLITE_NOMEM;
87870 }else{
87871 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
87872 sqlite3DbFree(db, zSql);
87876 /* Load the statistics from the sqlite_stat4 table. */
87877 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87878 if( rc==SQLITE_OK ){
87879 int lookasideEnabled = db->lookaside.bEnabled;
87880 db->lookaside.bEnabled = 0;
87881 rc = loadStat4(db, sInfo.zDatabase);
87882 db->lookaside.bEnabled = lookasideEnabled;
87884 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
87885 Index *pIdx = sqliteHashData(i);
87886 sqlite3_free(pIdx->aiRowEst);
87887 pIdx->aiRowEst = 0;
87889 #endif
87891 if( rc==SQLITE_NOMEM ){
87892 db->mallocFailed = 1;
87894 return rc;
87898 #endif /* SQLITE_OMIT_ANALYZE */
87900 /************** End of analyze.c *********************************************/
87901 /************** Begin file attach.c ******************************************/
87903 ** 2003 April 6
87905 ** The author disclaims copyright to this source code. In place of
87906 ** a legal notice, here is a blessing:
87908 ** May you do good and not evil.
87909 ** May you find forgiveness for yourself and forgive others.
87910 ** May you share freely, never taking more than you give.
87912 *************************************************************************
87913 ** This file contains code used to implement the ATTACH and DETACH commands.
87916 #ifndef SQLITE_OMIT_ATTACH
87918 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
87919 ** is slightly different from resolving a normal SQL expression, because simple
87920 ** identifiers are treated as strings, not possible column names or aliases.
87922 ** i.e. if the parser sees:
87924 ** ATTACH DATABASE abc AS def
87926 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
87927 ** looking for columns of the same name.
87929 ** This only applies to the root node of pExpr, so the statement:
87931 ** ATTACH DATABASE abc||def AS 'db2'
87933 ** will fail because neither abc or def can be resolved.
87935 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
87937 int rc = SQLITE_OK;
87938 if( pExpr ){
87939 if( pExpr->op!=TK_ID ){
87940 rc = sqlite3ResolveExprNames(pName, pExpr);
87941 }else{
87942 pExpr->op = TK_STRING;
87945 return rc;
87949 ** An SQL user-function registered to do the work of an ATTACH statement. The
87950 ** three arguments to the function come directly from an attach statement:
87952 ** ATTACH DATABASE x AS y KEY z
87954 ** SELECT sqlite_attach(x, y, z)
87956 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
87957 ** third argument.
87959 static void attachFunc(
87960 sqlite3_context *context,
87961 int NotUsed,
87962 sqlite3_value **argv
87964 int i;
87965 int rc = 0;
87966 sqlite3 *db = sqlite3_context_db_handle(context);
87967 const char *zName;
87968 const char *zFile;
87969 char *zPath = 0;
87970 char *zErr = 0;
87971 unsigned int flags;
87972 Db *aNew;
87973 char *zErrDyn = 0;
87974 sqlite3_vfs *pVfs;
87976 UNUSED_PARAMETER(NotUsed);
87978 zFile = (const char *)sqlite3_value_text(argv[0]);
87979 zName = (const char *)sqlite3_value_text(argv[1]);
87980 if( zFile==0 ) zFile = "";
87981 if( zName==0 ) zName = "";
87983 /* Check for the following errors:
87985 ** * Too many attached databases,
87986 ** * Transaction currently open
87987 ** * Specified database name already being used.
87989 if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
87990 zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
87991 db->aLimit[SQLITE_LIMIT_ATTACHED]
87993 goto attach_error;
87995 if( !db->autoCommit ){
87996 zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
87997 goto attach_error;
87999 for(i=0; i<db->nDb; i++){
88000 char *z = db->aDb[i].zName;
88001 assert( z && zName );
88002 if( sqlite3StrICmp(z, zName)==0 ){
88003 zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
88004 goto attach_error;
88008 /* Allocate the new entry in the db->aDb[] array and initialize the schema
88009 ** hash tables.
88011 if( db->aDb==db->aDbStatic ){
88012 aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
88013 if( aNew==0 ) return;
88014 memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
88015 }else{
88016 aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
88017 if( aNew==0 ) return;
88019 db->aDb = aNew;
88020 aNew = &db->aDb[db->nDb];
88021 memset(aNew, 0, sizeof(*aNew));
88023 /* Open the database file. If the btree is successfully opened, use
88024 ** it to obtain the database schema. At this point the schema may
88025 ** or may not be initialized.
88027 flags = db->openFlags;
88028 rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
88029 if( rc!=SQLITE_OK ){
88030 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
88031 sqlite3_result_error(context, zErr, -1);
88032 sqlite3_free(zErr);
88033 return;
88035 assert( pVfs );
88036 flags |= SQLITE_OPEN_MAIN_DB;
88037 rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
88038 sqlite3_free( zPath );
88039 db->nDb++;
88040 if( rc==SQLITE_CONSTRAINT ){
88041 rc = SQLITE_ERROR;
88042 zErrDyn = sqlite3MPrintf(db, "database is already attached");
88043 }else if( rc==SQLITE_OK ){
88044 Pager *pPager;
88045 aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
88046 if( !aNew->pSchema ){
88047 rc = SQLITE_NOMEM;
88048 }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
88049 zErrDyn = sqlite3MPrintf(db,
88050 "attached databases must use the same text encoding as main database");
88051 rc = SQLITE_ERROR;
88053 pPager = sqlite3BtreePager(aNew->pBt);
88054 sqlite3PagerLockingMode(pPager, db->dfltLockMode);
88055 sqlite3BtreeSecureDelete(aNew->pBt,
88056 sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
88057 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
88058 sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
88059 #endif
88061 aNew->safety_level = 3;
88062 aNew->zName = sqlite3DbStrDup(db, zName);
88063 if( rc==SQLITE_OK && aNew->zName==0 ){
88064 rc = SQLITE_NOMEM;
88068 #ifdef SQLITE_HAS_CODEC
88069 if( rc==SQLITE_OK ){
88070 extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
88071 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
88072 int nKey;
88073 char *zKey;
88074 int t = sqlite3_value_type(argv[2]);
88075 switch( t ){
88076 case SQLITE_INTEGER:
88077 case SQLITE_FLOAT:
88078 zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
88079 rc = SQLITE_ERROR;
88080 break;
88082 case SQLITE_TEXT:
88083 case SQLITE_BLOB:
88084 nKey = sqlite3_value_bytes(argv[2]);
88085 zKey = (char *)sqlite3_value_blob(argv[2]);
88086 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
88087 break;
88089 case SQLITE_NULL:
88090 /* No key specified. Use the key from the main database */
88091 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
88092 if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
88093 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
88095 break;
88098 #endif
88100 /* If the file was opened successfully, read the schema for the new database.
88101 ** If this fails, or if opening the file failed, then close the file and
88102 ** remove the entry from the db->aDb[] array. i.e. put everything back the way
88103 ** we found it.
88105 if( rc==SQLITE_OK ){
88106 sqlite3BtreeEnterAll(db);
88107 rc = sqlite3Init(db, &zErrDyn);
88108 sqlite3BtreeLeaveAll(db);
88110 #ifdef SQLITE_USER_AUTHENTICATION
88111 if( rc==SQLITE_OK ){
88112 u8 newAuth = 0;
88113 rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
88114 if( newAuth<db->auth.authLevel ){
88115 rc = SQLITE_AUTH_USER;
88118 #endif
88119 if( rc ){
88120 int iDb = db->nDb - 1;
88121 assert( iDb>=2 );
88122 if( db->aDb[iDb].pBt ){
88123 sqlite3BtreeClose(db->aDb[iDb].pBt);
88124 db->aDb[iDb].pBt = 0;
88125 db->aDb[iDb].pSchema = 0;
88127 sqlite3ResetAllSchemasOfConnection(db);
88128 db->nDb = iDb;
88129 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
88130 db->mallocFailed = 1;
88131 sqlite3DbFree(db, zErrDyn);
88132 zErrDyn = sqlite3MPrintf(db, "out of memory");
88133 }else if( zErrDyn==0 ){
88134 zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
88136 goto attach_error;
88139 return;
88141 attach_error:
88142 /* Return an error if we get here */
88143 if( zErrDyn ){
88144 sqlite3_result_error(context, zErrDyn, -1);
88145 sqlite3DbFree(db, zErrDyn);
88147 if( rc ) sqlite3_result_error_code(context, rc);
88151 ** An SQL user-function registered to do the work of an DETACH statement. The
88152 ** three arguments to the function come directly from a detach statement:
88154 ** DETACH DATABASE x
88156 ** SELECT sqlite_detach(x)
88158 static void detachFunc(
88159 sqlite3_context *context,
88160 int NotUsed,
88161 sqlite3_value **argv
88163 const char *zName = (const char *)sqlite3_value_text(argv[0]);
88164 sqlite3 *db = sqlite3_context_db_handle(context);
88165 int i;
88166 Db *pDb = 0;
88167 char zErr[128];
88169 UNUSED_PARAMETER(NotUsed);
88171 if( zName==0 ) zName = "";
88172 for(i=0; i<db->nDb; i++){
88173 pDb = &db->aDb[i];
88174 if( pDb->pBt==0 ) continue;
88175 if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
88178 if( i>=db->nDb ){
88179 sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
88180 goto detach_error;
88182 if( i<2 ){
88183 sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
88184 goto detach_error;
88186 if( !db->autoCommit ){
88187 sqlite3_snprintf(sizeof(zErr), zErr,
88188 "cannot DETACH database within transaction");
88189 goto detach_error;
88191 if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
88192 sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
88193 goto detach_error;
88196 sqlite3BtreeClose(pDb->pBt);
88197 pDb->pBt = 0;
88198 pDb->pSchema = 0;
88199 sqlite3ResetAllSchemasOfConnection(db);
88200 return;
88202 detach_error:
88203 sqlite3_result_error(context, zErr, -1);
88207 ** This procedure generates VDBE code for a single invocation of either the
88208 ** sqlite_detach() or sqlite_attach() SQL user functions.
88210 static void codeAttach(
88211 Parse *pParse, /* The parser context */
88212 int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
88213 FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
88214 Expr *pAuthArg, /* Expression to pass to authorization callback */
88215 Expr *pFilename, /* Name of database file */
88216 Expr *pDbname, /* Name of the database to use internally */
88217 Expr *pKey /* Database key for encryption extension */
88219 int rc;
88220 NameContext sName;
88221 Vdbe *v;
88222 sqlite3* db = pParse->db;
88223 int regArgs;
88225 memset(&sName, 0, sizeof(NameContext));
88226 sName.pParse = pParse;
88228 if(
88229 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
88230 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
88231 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
88233 pParse->nErr++;
88234 goto attach_end;
88237 #ifndef SQLITE_OMIT_AUTHORIZATION
88238 if( pAuthArg ){
88239 char *zAuthArg;
88240 if( pAuthArg->op==TK_STRING ){
88241 zAuthArg = pAuthArg->u.zToken;
88242 }else{
88243 zAuthArg = 0;
88245 rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
88246 if(rc!=SQLITE_OK ){
88247 goto attach_end;
88250 #endif /* SQLITE_OMIT_AUTHORIZATION */
88253 v = sqlite3GetVdbe(pParse);
88254 regArgs = sqlite3GetTempRange(pParse, 4);
88255 sqlite3ExprCode(pParse, pFilename, regArgs);
88256 sqlite3ExprCode(pParse, pDbname, regArgs+1);
88257 sqlite3ExprCode(pParse, pKey, regArgs+2);
88259 assert( v || db->mallocFailed );
88260 if( v ){
88261 sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
88262 assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
88263 sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
88264 sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
88266 /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
88267 ** statement only). For DETACH, set it to false (expire all existing
88268 ** statements).
88270 sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
88273 attach_end:
88274 sqlite3ExprDelete(db, pFilename);
88275 sqlite3ExprDelete(db, pDbname);
88276 sqlite3ExprDelete(db, pKey);
88280 ** Called by the parser to compile a DETACH statement.
88282 ** DETACH pDbname
88284 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
88285 static const FuncDef detach_func = {
88286 1, /* nArg */
88287 SQLITE_UTF8, /* funcFlags */
88288 0, /* pUserData */
88289 0, /* pNext */
88290 detachFunc, /* xFunc */
88291 0, /* xStep */
88292 0, /* xFinalize */
88293 "sqlite_detach", /* zName */
88294 0, /* pHash */
88295 0 /* pDestructor */
88297 codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
88301 ** Called by the parser to compile an ATTACH statement.
88303 ** ATTACH p AS pDbname KEY pKey
88305 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
88306 static const FuncDef attach_func = {
88307 3, /* nArg */
88308 SQLITE_UTF8, /* funcFlags */
88309 0, /* pUserData */
88310 0, /* pNext */
88311 attachFunc, /* xFunc */
88312 0, /* xStep */
88313 0, /* xFinalize */
88314 "sqlite_attach", /* zName */
88315 0, /* pHash */
88316 0 /* pDestructor */
88318 codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
88320 #endif /* SQLITE_OMIT_ATTACH */
88323 ** Initialize a DbFixer structure. This routine must be called prior
88324 ** to passing the structure to one of the sqliteFixAAAA() routines below.
88326 SQLITE_PRIVATE void sqlite3FixInit(
88327 DbFixer *pFix, /* The fixer to be initialized */
88328 Parse *pParse, /* Error messages will be written here */
88329 int iDb, /* This is the database that must be used */
88330 const char *zType, /* "view", "trigger", or "index" */
88331 const Token *pName /* Name of the view, trigger, or index */
88333 sqlite3 *db;
88335 db = pParse->db;
88336 assert( db->nDb>iDb );
88337 pFix->pParse = pParse;
88338 pFix->zDb = db->aDb[iDb].zName;
88339 pFix->pSchema = db->aDb[iDb].pSchema;
88340 pFix->zType = zType;
88341 pFix->pName = pName;
88342 pFix->bVarOnly = (iDb==1);
88346 ** The following set of routines walk through the parse tree and assign
88347 ** a specific database to all table references where the database name
88348 ** was left unspecified in the original SQL statement. The pFix structure
88349 ** must have been initialized by a prior call to sqlite3FixInit().
88351 ** These routines are used to make sure that an index, trigger, or
88352 ** view in one database does not refer to objects in a different database.
88353 ** (Exception: indices, triggers, and views in the TEMP database are
88354 ** allowed to refer to anything.) If a reference is explicitly made
88355 ** to an object in a different database, an error message is added to
88356 ** pParse->zErrMsg and these routines return non-zero. If everything
88357 ** checks out, these routines return 0.
88359 SQLITE_PRIVATE int sqlite3FixSrcList(
88360 DbFixer *pFix, /* Context of the fixation */
88361 SrcList *pList /* The Source list to check and modify */
88363 int i;
88364 const char *zDb;
88365 struct SrcList_item *pItem;
88367 if( NEVER(pList==0) ) return 0;
88368 zDb = pFix->zDb;
88369 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
88370 if( pFix->bVarOnly==0 ){
88371 if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
88372 sqlite3ErrorMsg(pFix->pParse,
88373 "%s %T cannot reference objects in database %s",
88374 pFix->zType, pFix->pName, pItem->zDatabase);
88375 return 1;
88377 sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
88378 pItem->zDatabase = 0;
88379 pItem->pSchema = pFix->pSchema;
88381 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
88382 if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
88383 if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
88384 #endif
88386 return 0;
88388 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
88389 SQLITE_PRIVATE int sqlite3FixSelect(
88390 DbFixer *pFix, /* Context of the fixation */
88391 Select *pSelect /* The SELECT statement to be fixed to one database */
88393 while( pSelect ){
88394 if( sqlite3FixExprList(pFix, pSelect->pEList) ){
88395 return 1;
88397 if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
88398 return 1;
88400 if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
88401 return 1;
88403 if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
88404 return 1;
88406 if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
88407 return 1;
88409 if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
88410 return 1;
88412 if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
88413 return 1;
88415 if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
88416 return 1;
88418 pSelect = pSelect->pPrior;
88420 return 0;
88422 SQLITE_PRIVATE int sqlite3FixExpr(
88423 DbFixer *pFix, /* Context of the fixation */
88424 Expr *pExpr /* The expression to be fixed to one database */
88426 while( pExpr ){
88427 if( pExpr->op==TK_VARIABLE ){
88428 if( pFix->pParse->db->init.busy ){
88429 pExpr->op = TK_NULL;
88430 }else{
88431 sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
88432 return 1;
88435 if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
88436 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
88437 if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
88438 }else{
88439 if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
88441 if( sqlite3FixExpr(pFix, pExpr->pRight) ){
88442 return 1;
88444 pExpr = pExpr->pLeft;
88446 return 0;
88448 SQLITE_PRIVATE int sqlite3FixExprList(
88449 DbFixer *pFix, /* Context of the fixation */
88450 ExprList *pList /* The expression to be fixed to one database */
88452 int i;
88453 struct ExprList_item *pItem;
88454 if( pList==0 ) return 0;
88455 for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
88456 if( sqlite3FixExpr(pFix, pItem->pExpr) ){
88457 return 1;
88460 return 0;
88462 #endif
88464 #ifndef SQLITE_OMIT_TRIGGER
88465 SQLITE_PRIVATE int sqlite3FixTriggerStep(
88466 DbFixer *pFix, /* Context of the fixation */
88467 TriggerStep *pStep /* The trigger step be fixed to one database */
88469 while( pStep ){
88470 if( sqlite3FixSelect(pFix, pStep->pSelect) ){
88471 return 1;
88473 if( sqlite3FixExpr(pFix, pStep->pWhere) ){
88474 return 1;
88476 if( sqlite3FixExprList(pFix, pStep->pExprList) ){
88477 return 1;
88479 pStep = pStep->pNext;
88481 return 0;
88483 #endif
88485 /************** End of attach.c **********************************************/
88486 /************** Begin file auth.c ********************************************/
88488 ** 2003 January 11
88490 ** The author disclaims copyright to this source code. In place of
88491 ** a legal notice, here is a blessing:
88493 ** May you do good and not evil.
88494 ** May you find forgiveness for yourself and forgive others.
88495 ** May you share freely, never taking more than you give.
88497 *************************************************************************
88498 ** This file contains code used to implement the sqlite3_set_authorizer()
88499 ** API. This facility is an optional feature of the library. Embedded
88500 ** systems that do not need this facility may omit it by recompiling
88501 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
88505 ** All of the code in this file may be omitted by defining a single
88506 ** macro.
88508 #ifndef SQLITE_OMIT_AUTHORIZATION
88511 ** Set or clear the access authorization function.
88513 ** The access authorization function is be called during the compilation
88514 ** phase to verify that the user has read and/or write access permission on
88515 ** various fields of the database. The first argument to the auth function
88516 ** is a copy of the 3rd argument to this routine. The second argument
88517 ** to the auth function is one of these constants:
88519 ** SQLITE_CREATE_INDEX
88520 ** SQLITE_CREATE_TABLE
88521 ** SQLITE_CREATE_TEMP_INDEX
88522 ** SQLITE_CREATE_TEMP_TABLE
88523 ** SQLITE_CREATE_TEMP_TRIGGER
88524 ** SQLITE_CREATE_TEMP_VIEW
88525 ** SQLITE_CREATE_TRIGGER
88526 ** SQLITE_CREATE_VIEW
88527 ** SQLITE_DELETE
88528 ** SQLITE_DROP_INDEX
88529 ** SQLITE_DROP_TABLE
88530 ** SQLITE_DROP_TEMP_INDEX
88531 ** SQLITE_DROP_TEMP_TABLE
88532 ** SQLITE_DROP_TEMP_TRIGGER
88533 ** SQLITE_DROP_TEMP_VIEW
88534 ** SQLITE_DROP_TRIGGER
88535 ** SQLITE_DROP_VIEW
88536 ** SQLITE_INSERT
88537 ** SQLITE_PRAGMA
88538 ** SQLITE_READ
88539 ** SQLITE_SELECT
88540 ** SQLITE_TRANSACTION
88541 ** SQLITE_UPDATE
88543 ** The third and fourth arguments to the auth function are the name of
88544 ** the table and the column that are being accessed. The auth function
88545 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
88546 ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
88547 ** means that the SQL statement will never-run - the sqlite3_exec() call
88548 ** will return with an error. SQLITE_IGNORE means that the SQL statement
88549 ** should run but attempts to read the specified column will return NULL
88550 ** and attempts to write the column will be ignored.
88552 ** Setting the auth function to NULL disables this hook. The default
88553 ** setting of the auth function is NULL.
88555 SQLITE_API int sqlite3_set_authorizer(
88556 sqlite3 *db,
88557 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
88558 void *pArg
88560 sqlite3_mutex_enter(db->mutex);
88561 db->xAuth = (sqlite3_xauth)xAuth;
88562 db->pAuthArg = pArg;
88563 sqlite3ExpirePreparedStatements(db);
88564 sqlite3_mutex_leave(db->mutex);
88565 return SQLITE_OK;
88569 ** Write an error message into pParse->zErrMsg that explains that the
88570 ** user-supplied authorization function returned an illegal value.
88572 static void sqliteAuthBadReturnCode(Parse *pParse){
88573 sqlite3ErrorMsg(pParse, "authorizer malfunction");
88574 pParse->rc = SQLITE_ERROR;
88578 ** Invoke the authorization callback for permission to read column zCol from
88579 ** table zTab in database zDb. This function assumes that an authorization
88580 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
88582 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
88583 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
88584 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
88586 SQLITE_PRIVATE int sqlite3AuthReadCol(
88587 Parse *pParse, /* The parser context */
88588 const char *zTab, /* Table name */
88589 const char *zCol, /* Column name */
88590 int iDb /* Index of containing database. */
88592 sqlite3 *db = pParse->db; /* Database handle */
88593 char *zDb = db->aDb[iDb].zName; /* Name of attached database */
88594 int rc; /* Auth callback return code */
88596 rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
88597 #ifdef SQLITE_USER_AUTHENTICATION
88598 ,db->auth.zAuthUser
88599 #endif
88601 if( rc==SQLITE_DENY ){
88602 if( db->nDb>2 || iDb!=0 ){
88603 sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
88604 }else{
88605 sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
88607 pParse->rc = SQLITE_AUTH;
88608 }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
88609 sqliteAuthBadReturnCode(pParse);
88611 return rc;
88615 ** The pExpr should be a TK_COLUMN expression. The table referred to
88616 ** is in pTabList or else it is the NEW or OLD table of a trigger.
88617 ** Check to see if it is OK to read this particular column.
88619 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
88620 ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
88621 ** then generate an error.
88623 SQLITE_PRIVATE void sqlite3AuthRead(
88624 Parse *pParse, /* The parser context */
88625 Expr *pExpr, /* The expression to check authorization on */
88626 Schema *pSchema, /* The schema of the expression */
88627 SrcList *pTabList /* All table that pExpr might refer to */
88629 sqlite3 *db = pParse->db;
88630 Table *pTab = 0; /* The table being read */
88631 const char *zCol; /* Name of the column of the table */
88632 int iSrc; /* Index in pTabList->a[] of table being read */
88633 int iDb; /* The index of the database the expression refers to */
88634 int iCol; /* Index of column in table */
88636 if( db->xAuth==0 ) return;
88637 iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
88638 if( iDb<0 ){
88639 /* An attempt to read a column out of a subquery or other
88640 ** temporary table. */
88641 return;
88644 assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
88645 if( pExpr->op==TK_TRIGGER ){
88646 pTab = pParse->pTriggerTab;
88647 }else{
88648 assert( pTabList );
88649 for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
88650 if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
88651 pTab = pTabList->a[iSrc].pTab;
88652 break;
88656 iCol = pExpr->iColumn;
88657 if( NEVER(pTab==0) ) return;
88659 if( iCol>=0 ){
88660 assert( iCol<pTab->nCol );
88661 zCol = pTab->aCol[iCol].zName;
88662 }else if( pTab->iPKey>=0 ){
88663 assert( pTab->iPKey<pTab->nCol );
88664 zCol = pTab->aCol[pTab->iPKey].zName;
88665 }else{
88666 zCol = "ROWID";
88668 assert( iDb>=0 && iDb<db->nDb );
88669 if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
88670 pExpr->op = TK_NULL;
88675 ** Do an authorization check using the code and arguments given. Return
88676 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
88677 ** is returned, then the error count and error message in pParse are
88678 ** modified appropriately.
88680 SQLITE_PRIVATE int sqlite3AuthCheck(
88681 Parse *pParse,
88682 int code,
88683 const char *zArg1,
88684 const char *zArg2,
88685 const char *zArg3
88687 sqlite3 *db = pParse->db;
88688 int rc;
88690 /* Don't do any authorization checks if the database is initialising
88691 ** or if the parser is being invoked from within sqlite3_declare_vtab.
88693 if( db->init.busy || IN_DECLARE_VTAB ){
88694 return SQLITE_OK;
88697 if( db->xAuth==0 ){
88698 return SQLITE_OK;
88700 rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
88701 #ifdef SQLITE_USER_AUTHENTICATION
88702 ,db->auth.zAuthUser
88703 #endif
88705 if( rc==SQLITE_DENY ){
88706 sqlite3ErrorMsg(pParse, "not authorized");
88707 pParse->rc = SQLITE_AUTH;
88708 }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
88709 rc = SQLITE_DENY;
88710 sqliteAuthBadReturnCode(pParse);
88712 return rc;
88716 ** Push an authorization context. After this routine is called, the
88717 ** zArg3 argument to authorization callbacks will be zContext until
88718 ** popped. Or if pParse==0, this routine is a no-op.
88720 SQLITE_PRIVATE void sqlite3AuthContextPush(
88721 Parse *pParse,
88722 AuthContext *pContext,
88723 const char *zContext
88725 assert( pParse );
88726 pContext->pParse = pParse;
88727 pContext->zAuthContext = pParse->zAuthContext;
88728 pParse->zAuthContext = zContext;
88732 ** Pop an authorization context that was previously pushed
88733 ** by sqlite3AuthContextPush
88735 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
88736 if( pContext->pParse ){
88737 pContext->pParse->zAuthContext = pContext->zAuthContext;
88738 pContext->pParse = 0;
88742 #endif /* SQLITE_OMIT_AUTHORIZATION */
88744 /************** End of auth.c ************************************************/
88745 /************** Begin file build.c *******************************************/
88747 ** 2001 September 15
88749 ** The author disclaims copyright to this source code. In place of
88750 ** a legal notice, here is a blessing:
88752 ** May you do good and not evil.
88753 ** May you find forgiveness for yourself and forgive others.
88754 ** May you share freely, never taking more than you give.
88756 *************************************************************************
88757 ** This file contains C code routines that are called by the SQLite parser
88758 ** when syntax rules are reduced. The routines in this file handle the
88759 ** following kinds of SQL syntax:
88761 ** CREATE TABLE
88762 ** DROP TABLE
88763 ** CREATE INDEX
88764 ** DROP INDEX
88765 ** creating ID lists
88766 ** BEGIN TRANSACTION
88767 ** COMMIT
88768 ** ROLLBACK
88772 ** This routine is called when a new SQL statement is beginning to
88773 ** be parsed. Initialize the pParse structure as needed.
88775 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
88776 pParse->explain = (u8)explainFlag;
88777 pParse->nVar = 0;
88780 #ifndef SQLITE_OMIT_SHARED_CACHE
88782 ** The TableLock structure is only used by the sqlite3TableLock() and
88783 ** codeTableLocks() functions.
88785 struct TableLock {
88786 int iDb; /* The database containing the table to be locked */
88787 int iTab; /* The root page of the table to be locked */
88788 u8 isWriteLock; /* True for write lock. False for a read lock */
88789 const char *zName; /* Name of the table */
88793 ** Record the fact that we want to lock a table at run-time.
88795 ** The table to be locked has root page iTab and is found in database iDb.
88796 ** A read or a write lock can be taken depending on isWritelock.
88798 ** This routine just records the fact that the lock is desired. The
88799 ** code to make the lock occur is generated by a later call to
88800 ** codeTableLocks() which occurs during sqlite3FinishCoding().
88802 SQLITE_PRIVATE void sqlite3TableLock(
88803 Parse *pParse, /* Parsing context */
88804 int iDb, /* Index of the database containing the table to lock */
88805 int iTab, /* Root page number of the table to be locked */
88806 u8 isWriteLock, /* True for a write lock */
88807 const char *zName /* Name of the table to be locked */
88809 Parse *pToplevel = sqlite3ParseToplevel(pParse);
88810 int i;
88811 int nBytes;
88812 TableLock *p;
88813 assert( iDb>=0 );
88815 for(i=0; i<pToplevel->nTableLock; i++){
88816 p = &pToplevel->aTableLock[i];
88817 if( p->iDb==iDb && p->iTab==iTab ){
88818 p->isWriteLock = (p->isWriteLock || isWriteLock);
88819 return;
88823 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
88824 pToplevel->aTableLock =
88825 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
88826 if( pToplevel->aTableLock ){
88827 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
88828 p->iDb = iDb;
88829 p->iTab = iTab;
88830 p->isWriteLock = isWriteLock;
88831 p->zName = zName;
88832 }else{
88833 pToplevel->nTableLock = 0;
88834 pToplevel->db->mallocFailed = 1;
88839 ** Code an OP_TableLock instruction for each table locked by the
88840 ** statement (configured by calls to sqlite3TableLock()).
88842 static void codeTableLocks(Parse *pParse){
88843 int i;
88844 Vdbe *pVdbe;
88846 pVdbe = sqlite3GetVdbe(pParse);
88847 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
88849 for(i=0; i<pParse->nTableLock; i++){
88850 TableLock *p = &pParse->aTableLock[i];
88851 int p1 = p->iDb;
88852 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
88853 p->zName, P4_STATIC);
88856 #else
88857 #define codeTableLocks(x)
88858 #endif
88861 ** Return TRUE if the given yDbMask object is empty - if it contains no
88862 ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
88863 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
88865 #if SQLITE_MAX_ATTACHED>30
88866 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
88867 int i;
88868 for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
88869 return 1;
88871 #endif
88874 ** This routine is called after a single SQL statement has been
88875 ** parsed and a VDBE program to execute that statement has been
88876 ** prepared. This routine puts the finishing touches on the
88877 ** VDBE program and resets the pParse structure for the next
88878 ** parse.
88880 ** Note that if an error occurred, it might be the case that
88881 ** no VDBE code was generated.
88883 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
88884 sqlite3 *db;
88885 Vdbe *v;
88887 assert( pParse->pToplevel==0 );
88888 db = pParse->db;
88889 if( db->mallocFailed ) return;
88890 if( pParse->nested ) return;
88891 if( pParse->nErr ) return;
88893 /* Begin by generating some termination code at the end of the
88894 ** vdbe program
88896 v = sqlite3GetVdbe(pParse);
88897 assert( !pParse->isMultiWrite
88898 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
88899 if( v ){
88900 while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
88901 sqlite3VdbeAddOp0(v, OP_Halt);
88903 #if SQLITE_USER_AUTHENTICATION
88904 if( pParse->nTableLock>0 && db->init.busy==0 ){
88905 sqlite3UserAuthInit(db);
88906 if( db->auth.authLevel<UAUTH_User ){
88907 pParse->rc = SQLITE_AUTH_USER;
88908 sqlite3ErrorMsg(pParse, "user not authenticated");
88909 return;
88912 #endif
88914 /* The cookie mask contains one bit for each database file open.
88915 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
88916 ** set for each database that is used. Generate code to start a
88917 ** transaction on each used database and to verify the schema cookie
88918 ** on each used database.
88920 if( db->mallocFailed==0
88921 && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
88923 int iDb, i;
88924 assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
88925 sqlite3VdbeJumpHere(v, 0);
88926 for(iDb=0; iDb<db->nDb; iDb++){
88927 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
88928 sqlite3VdbeUsesBtree(v, iDb);
88929 sqlite3VdbeAddOp4Int(v,
88930 OP_Transaction, /* Opcode */
88931 iDb, /* P1 */
88932 DbMaskTest(pParse->writeMask,iDb), /* P2 */
88933 pParse->cookieValue[iDb], /* P3 */
88934 db->aDb[iDb].pSchema->iGeneration /* P4 */
88936 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
88938 #ifndef SQLITE_OMIT_VIRTUALTABLE
88939 for(i=0; i<pParse->nVtabLock; i++){
88940 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
88941 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
88943 pParse->nVtabLock = 0;
88944 #endif
88946 /* Once all the cookies have been verified and transactions opened,
88947 ** obtain the required table-locks. This is a no-op unless the
88948 ** shared-cache feature is enabled.
88950 codeTableLocks(pParse);
88952 /* Initialize any AUTOINCREMENT data structures required.
88954 sqlite3AutoincrementBegin(pParse);
88956 /* Code constant expressions that where factored out of inner loops */
88957 if( pParse->pConstExpr ){
88958 ExprList *pEL = pParse->pConstExpr;
88959 pParse->okConstFactor = 0;
88960 for(i=0; i<pEL->nExpr; i++){
88961 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
88965 /* Finally, jump back to the beginning of the executable code. */
88966 sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
88971 /* Get the VDBE program ready for execution
88973 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
88974 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
88975 /* A minimum of one cursor is required if autoincrement is used
88976 * See ticket [a696379c1f08866] */
88977 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
88978 sqlite3VdbeMakeReady(v, pParse);
88979 pParse->rc = SQLITE_DONE;
88980 pParse->colNamesSet = 0;
88981 }else{
88982 pParse->rc = SQLITE_ERROR;
88984 pParse->nTab = 0;
88985 pParse->nMem = 0;
88986 pParse->nSet = 0;
88987 pParse->nVar = 0;
88988 DbMaskZero(pParse->cookieMask);
88992 ** Run the parser and code generator recursively in order to generate
88993 ** code for the SQL statement given onto the end of the pParse context
88994 ** currently under construction. When the parser is run recursively
88995 ** this way, the final OP_Halt is not appended and other initialization
88996 ** and finalization steps are omitted because those are handling by the
88997 ** outermost parser.
88999 ** Not everything is nestable. This facility is designed to permit
89000 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
89001 ** care if you decide to try to use this routine for some other purposes.
89003 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
89004 va_list ap;
89005 char *zSql;
89006 char *zErrMsg = 0;
89007 sqlite3 *db = pParse->db;
89008 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
89009 char saveBuf[SAVE_SZ];
89011 if( pParse->nErr ) return;
89012 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
89013 va_start(ap, zFormat);
89014 zSql = sqlite3VMPrintf(db, zFormat, ap);
89015 va_end(ap);
89016 if( zSql==0 ){
89017 return; /* A malloc must have failed */
89019 pParse->nested++;
89020 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
89021 memset(&pParse->nVar, 0, SAVE_SZ);
89022 sqlite3RunParser(pParse, zSql, &zErrMsg);
89023 sqlite3DbFree(db, zErrMsg);
89024 sqlite3DbFree(db, zSql);
89025 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
89026 pParse->nested--;
89029 #if SQLITE_USER_AUTHENTICATION
89031 ** Return TRUE if zTable is the name of the system table that stores the
89032 ** list of users and their access credentials.
89034 SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
89035 return sqlite3_stricmp(zTable, "sqlite_user")==0;
89037 #endif
89040 ** Locate the in-memory structure that describes a particular database
89041 ** table given the name of that table and (optionally) the name of the
89042 ** database containing the table. Return NULL if not found.
89044 ** If zDatabase is 0, all databases are searched for the table and the
89045 ** first matching table is returned. (No checking for duplicate table
89046 ** names is done.) The search order is TEMP first, then MAIN, then any
89047 ** auxiliary databases added using the ATTACH command.
89049 ** See also sqlite3LocateTable().
89051 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
89052 Table *p = 0;
89053 int i;
89054 assert( zName!=0 );
89055 /* All mutexes are required for schema access. Make sure we hold them. */
89056 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
89057 #if SQLITE_USER_AUTHENTICATION
89058 /* Only the admin user is allowed to know that the sqlite_user table
89059 ** exists */
89060 if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
89061 return 0;
89063 #endif
89064 for(i=OMIT_TEMPDB; i<db->nDb; i++){
89065 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
89066 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
89067 assert( sqlite3SchemaMutexHeld(db, j, 0) );
89068 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
89069 if( p ) break;
89071 return p;
89075 ** Locate the in-memory structure that describes a particular database
89076 ** table given the name of that table and (optionally) the name of the
89077 ** database containing the table. Return NULL if not found. Also leave an
89078 ** error message in pParse->zErrMsg.
89080 ** The difference between this routine and sqlite3FindTable() is that this
89081 ** routine leaves an error message in pParse->zErrMsg where
89082 ** sqlite3FindTable() does not.
89084 SQLITE_PRIVATE Table *sqlite3LocateTable(
89085 Parse *pParse, /* context in which to report errors */
89086 int isView, /* True if looking for a VIEW rather than a TABLE */
89087 const char *zName, /* Name of the table we are looking for */
89088 const char *zDbase /* Name of the database. Might be NULL */
89090 Table *p;
89092 /* Read the database schema. If an error occurs, leave an error message
89093 ** and code in pParse and return NULL. */
89094 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
89095 return 0;
89098 p = sqlite3FindTable(pParse->db, zName, zDbase);
89099 if( p==0 ){
89100 const char *zMsg = isView ? "no such view" : "no such table";
89101 if( zDbase ){
89102 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
89103 }else{
89104 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
89106 pParse->checkSchema = 1;
89108 #if SQLITE_USER_AUTHENICATION
89109 else if( pParse->db->auth.authLevel<UAUTH_User ){
89110 sqlite3ErrorMsg(pParse, "user not authenticated");
89111 p = 0;
89113 #endif
89114 return p;
89118 ** Locate the table identified by *p.
89120 ** This is a wrapper around sqlite3LocateTable(). The difference between
89121 ** sqlite3LocateTable() and this function is that this function restricts
89122 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
89123 ** non-NULL if it is part of a view or trigger program definition. See
89124 ** sqlite3FixSrcList() for details.
89126 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
89127 Parse *pParse,
89128 int isView,
89129 struct SrcList_item *p
89131 const char *zDb;
89132 assert( p->pSchema==0 || p->zDatabase==0 );
89133 if( p->pSchema ){
89134 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
89135 zDb = pParse->db->aDb[iDb].zName;
89136 }else{
89137 zDb = p->zDatabase;
89139 return sqlite3LocateTable(pParse, isView, p->zName, zDb);
89143 ** Locate the in-memory structure that describes
89144 ** a particular index given the name of that index
89145 ** and the name of the database that contains the index.
89146 ** Return NULL if not found.
89148 ** If zDatabase is 0, all databases are searched for the
89149 ** table and the first matching index is returned. (No checking
89150 ** for duplicate index names is done.) The search order is
89151 ** TEMP first, then MAIN, then any auxiliary databases added
89152 ** using the ATTACH command.
89154 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
89155 Index *p = 0;
89156 int i;
89157 /* All mutexes are required for schema access. Make sure we hold them. */
89158 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
89159 for(i=OMIT_TEMPDB; i<db->nDb; i++){
89160 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
89161 Schema *pSchema = db->aDb[j].pSchema;
89162 assert( pSchema );
89163 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
89164 assert( sqlite3SchemaMutexHeld(db, j, 0) );
89165 p = sqlite3HashFind(&pSchema->idxHash, zName);
89166 if( p ) break;
89168 return p;
89172 ** Reclaim the memory used by an index
89174 static void freeIndex(sqlite3 *db, Index *p){
89175 #ifndef SQLITE_OMIT_ANALYZE
89176 sqlite3DeleteIndexSamples(db, p);
89177 #endif
89178 if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo);
89179 sqlite3ExprDelete(db, p->pPartIdxWhere);
89180 sqlite3DbFree(db, p->zColAff);
89181 if( p->isResized ) sqlite3DbFree(db, p->azColl);
89182 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89183 sqlite3_free(p->aiRowEst);
89184 #endif
89185 sqlite3DbFree(db, p);
89189 ** For the index called zIdxName which is found in the database iDb,
89190 ** unlike that index from its Table then remove the index from
89191 ** the index hash table and free all memory structures associated
89192 ** with the index.
89194 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
89195 Index *pIndex;
89196 Hash *pHash;
89198 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89199 pHash = &db->aDb[iDb].pSchema->idxHash;
89200 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
89201 if( ALWAYS(pIndex) ){
89202 if( pIndex->pTable->pIndex==pIndex ){
89203 pIndex->pTable->pIndex = pIndex->pNext;
89204 }else{
89205 Index *p;
89206 /* Justification of ALWAYS(); The index must be on the list of
89207 ** indices. */
89208 p = pIndex->pTable->pIndex;
89209 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
89210 if( ALWAYS(p && p->pNext==pIndex) ){
89211 p->pNext = pIndex->pNext;
89214 freeIndex(db, pIndex);
89216 db->flags |= SQLITE_InternChanges;
89220 ** Look through the list of open database files in db->aDb[] and if
89221 ** any have been closed, remove them from the list. Reallocate the
89222 ** db->aDb[] structure to a smaller size, if possible.
89224 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
89225 ** are never candidates for being collapsed.
89227 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
89228 int i, j;
89229 for(i=j=2; i<db->nDb; i++){
89230 struct Db *pDb = &db->aDb[i];
89231 if( pDb->pBt==0 ){
89232 sqlite3DbFree(db, pDb->zName);
89233 pDb->zName = 0;
89234 continue;
89236 if( j<i ){
89237 db->aDb[j] = db->aDb[i];
89239 j++;
89241 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
89242 db->nDb = j;
89243 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
89244 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
89245 sqlite3DbFree(db, db->aDb);
89246 db->aDb = db->aDbStatic;
89251 ** Reset the schema for the database at index iDb. Also reset the
89252 ** TEMP schema.
89254 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
89255 Db *pDb;
89256 assert( iDb<db->nDb );
89258 /* Case 1: Reset the single schema identified by iDb */
89259 pDb = &db->aDb[iDb];
89260 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89261 assert( pDb->pSchema!=0 );
89262 sqlite3SchemaClear(pDb->pSchema);
89264 /* If any database other than TEMP is reset, then also reset TEMP
89265 ** since TEMP might be holding triggers that reference tables in the
89266 ** other database.
89268 if( iDb!=1 ){
89269 pDb = &db->aDb[1];
89270 assert( pDb->pSchema!=0 );
89271 sqlite3SchemaClear(pDb->pSchema);
89273 return;
89277 ** Erase all schema information from all attached databases (including
89278 ** "main" and "temp") for a single database connection.
89280 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
89281 int i;
89282 sqlite3BtreeEnterAll(db);
89283 for(i=0; i<db->nDb; i++){
89284 Db *pDb = &db->aDb[i];
89285 if( pDb->pSchema ){
89286 sqlite3SchemaClear(pDb->pSchema);
89289 db->flags &= ~SQLITE_InternChanges;
89290 sqlite3VtabUnlockList(db);
89291 sqlite3BtreeLeaveAll(db);
89292 sqlite3CollapseDatabaseArray(db);
89296 ** This routine is called when a commit occurs.
89298 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
89299 db->flags &= ~SQLITE_InternChanges;
89303 ** Delete memory allocated for the column names of a table or view (the
89304 ** Table.aCol[] array).
89306 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
89307 int i;
89308 Column *pCol;
89309 assert( pTable!=0 );
89310 if( (pCol = pTable->aCol)!=0 ){
89311 for(i=0; i<pTable->nCol; i++, pCol++){
89312 sqlite3DbFree(db, pCol->zName);
89313 sqlite3ExprDelete(db, pCol->pDflt);
89314 sqlite3DbFree(db, pCol->zDflt);
89315 sqlite3DbFree(db, pCol->zType);
89316 sqlite3DbFree(db, pCol->zColl);
89318 sqlite3DbFree(db, pTable->aCol);
89323 ** Remove the memory data structures associated with the given
89324 ** Table. No changes are made to disk by this routine.
89326 ** This routine just deletes the data structure. It does not unlink
89327 ** the table data structure from the hash table. But it does destroy
89328 ** memory structures of the indices and foreign keys associated with
89329 ** the table.
89331 ** The db parameter is optional. It is needed if the Table object
89332 ** contains lookaside memory. (Table objects in the schema do not use
89333 ** lookaside memory, but some ephemeral Table objects do.) Or the
89334 ** db parameter can be used with db->pnBytesFreed to measure the memory
89335 ** used by the Table object.
89337 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
89338 Index *pIndex, *pNext;
89339 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
89341 assert( !pTable || pTable->nRef>0 );
89343 /* Do not delete the table until the reference count reaches zero. */
89344 if( !pTable ) return;
89345 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
89347 /* Record the number of outstanding lookaside allocations in schema Tables
89348 ** prior to doing any free() operations. Since schema Tables do not use
89349 ** lookaside, this number should not change. */
89350 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
89351 db->lookaside.nOut : 0 );
89353 /* Delete all indices associated with this table. */
89354 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
89355 pNext = pIndex->pNext;
89356 assert( pIndex->pSchema==pTable->pSchema );
89357 if( !db || db->pnBytesFreed==0 ){
89358 char *zName = pIndex->zName;
89359 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
89360 &pIndex->pSchema->idxHash, zName, 0
89362 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
89363 assert( pOld==pIndex || pOld==0 );
89365 freeIndex(db, pIndex);
89368 /* Delete any foreign keys attached to this table. */
89369 sqlite3FkDelete(db, pTable);
89371 /* Delete the Table structure itself.
89373 sqliteDeleteColumnNames(db, pTable);
89374 sqlite3DbFree(db, pTable->zName);
89375 sqlite3DbFree(db, pTable->zColAff);
89376 sqlite3SelectDelete(db, pTable->pSelect);
89377 #ifndef SQLITE_OMIT_CHECK
89378 sqlite3ExprListDelete(db, pTable->pCheck);
89379 #endif
89380 #ifndef SQLITE_OMIT_VIRTUALTABLE
89381 sqlite3VtabClear(db, pTable);
89382 #endif
89383 sqlite3DbFree(db, pTable);
89385 /* Verify that no lookaside memory was used by schema tables */
89386 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
89390 ** Unlink the given table from the hash tables and the delete the
89391 ** table structure with all its indices and foreign keys.
89393 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
89394 Table *p;
89395 Db *pDb;
89397 assert( db!=0 );
89398 assert( iDb>=0 && iDb<db->nDb );
89399 assert( zTabName );
89400 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89401 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
89402 pDb = &db->aDb[iDb];
89403 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
89404 sqlite3DeleteTable(db, p);
89405 db->flags |= SQLITE_InternChanges;
89409 ** Given a token, return a string that consists of the text of that
89410 ** token. Space to hold the returned string
89411 ** is obtained from sqliteMalloc() and must be freed by the calling
89412 ** function.
89414 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
89415 ** surround the body of the token are removed.
89417 ** Tokens are often just pointers into the original SQL text and so
89418 ** are not \000 terminated and are not persistent. The returned string
89419 ** is \000 terminated and is persistent.
89421 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
89422 char *zName;
89423 if( pName ){
89424 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
89425 sqlite3Dequote(zName);
89426 }else{
89427 zName = 0;
89429 return zName;
89433 ** Open the sqlite_master table stored in database number iDb for
89434 ** writing. The table is opened using cursor 0.
89436 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
89437 Vdbe *v = sqlite3GetVdbe(p);
89438 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
89439 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
89440 if( p->nTab==0 ){
89441 p->nTab = 1;
89446 ** Parameter zName points to a nul-terminated buffer containing the name
89447 ** of a database ("main", "temp" or the name of an attached db). This
89448 ** function returns the index of the named database in db->aDb[], or
89449 ** -1 if the named db cannot be found.
89451 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
89452 int i = -1; /* Database number */
89453 if( zName ){
89454 Db *pDb;
89455 int n = sqlite3Strlen30(zName);
89456 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
89457 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
89458 0==sqlite3StrICmp(pDb->zName, zName) ){
89459 break;
89463 return i;
89467 ** The token *pName contains the name of a database (either "main" or
89468 ** "temp" or the name of an attached db). This routine returns the
89469 ** index of the named database in db->aDb[], or -1 if the named db
89470 ** does not exist.
89472 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
89473 int i; /* Database number */
89474 char *zName; /* Name we are searching for */
89475 zName = sqlite3NameFromToken(db, pName);
89476 i = sqlite3FindDbName(db, zName);
89477 sqlite3DbFree(db, zName);
89478 return i;
89481 /* The table or view or trigger name is passed to this routine via tokens
89482 ** pName1 and pName2. If the table name was fully qualified, for example:
89484 ** CREATE TABLE xxx.yyy (...);
89486 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
89487 ** the table name is not fully qualified, i.e.:
89489 ** CREATE TABLE yyy(...);
89491 ** Then pName1 is set to "yyy" and pName2 is "".
89493 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
89494 ** pName2) that stores the unqualified table name. The index of the
89495 ** database "xxx" is returned.
89497 SQLITE_PRIVATE int sqlite3TwoPartName(
89498 Parse *pParse, /* Parsing and code generating context */
89499 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
89500 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
89501 Token **pUnqual /* Write the unqualified object name here */
89503 int iDb; /* Database holding the object */
89504 sqlite3 *db = pParse->db;
89506 if( ALWAYS(pName2!=0) && pName2->n>0 ){
89507 if( db->init.busy ) {
89508 sqlite3ErrorMsg(pParse, "corrupt database");
89509 pParse->nErr++;
89510 return -1;
89512 *pUnqual = pName2;
89513 iDb = sqlite3FindDb(db, pName1);
89514 if( iDb<0 ){
89515 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
89516 pParse->nErr++;
89517 return -1;
89519 }else{
89520 assert( db->init.iDb==0 || db->init.busy );
89521 iDb = db->init.iDb;
89522 *pUnqual = pName1;
89524 return iDb;
89528 ** This routine is used to check if the UTF-8 string zName is a legal
89529 ** unqualified name for a new schema object (table, index, view or
89530 ** trigger). All names are legal except those that begin with the string
89531 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
89532 ** is reserved for internal use.
89534 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
89535 if( !pParse->db->init.busy && pParse->nested==0
89536 && (pParse->db->flags & SQLITE_WriteSchema)==0
89537 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
89538 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
89539 return SQLITE_ERROR;
89541 return SQLITE_OK;
89545 ** Return the PRIMARY KEY index of a table
89547 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
89548 Index *p;
89549 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
89550 return p;
89554 ** Return the column of index pIdx that corresponds to table
89555 ** column iCol. Return -1 if not found.
89557 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
89558 int i;
89559 for(i=0; i<pIdx->nColumn; i++){
89560 if( iCol==pIdx->aiColumn[i] ) return i;
89562 return -1;
89566 ** Begin constructing a new table representation in memory. This is
89567 ** the first of several action routines that get called in response
89568 ** to a CREATE TABLE statement. In particular, this routine is called
89569 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
89570 ** flag is true if the table should be stored in the auxiliary database
89571 ** file instead of in the main database file. This is normally the case
89572 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
89573 ** CREATE and TABLE.
89575 ** The new table record is initialized and put in pParse->pNewTable.
89576 ** As more of the CREATE TABLE statement is parsed, additional action
89577 ** routines will be called to add more information to this record.
89578 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
89579 ** is called to complete the construction of the new table record.
89581 SQLITE_PRIVATE void sqlite3StartTable(
89582 Parse *pParse, /* Parser context */
89583 Token *pName1, /* First part of the name of the table or view */
89584 Token *pName2, /* Second part of the name of the table or view */
89585 int isTemp, /* True if this is a TEMP table */
89586 int isView, /* True if this is a VIEW */
89587 int isVirtual, /* True if this is a VIRTUAL table */
89588 int noErr /* Do nothing if table already exists */
89590 Table *pTable;
89591 char *zName = 0; /* The name of the new table */
89592 sqlite3 *db = pParse->db;
89593 Vdbe *v;
89594 int iDb; /* Database number to create the table in */
89595 Token *pName; /* Unqualified name of the table to create */
89597 /* The table or view name to create is passed to this routine via tokens
89598 ** pName1 and pName2. If the table name was fully qualified, for example:
89600 ** CREATE TABLE xxx.yyy (...);
89602 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
89603 ** the table name is not fully qualified, i.e.:
89605 ** CREATE TABLE yyy(...);
89607 ** Then pName1 is set to "yyy" and pName2 is "".
89609 ** The call below sets the pName pointer to point at the token (pName1 or
89610 ** pName2) that stores the unqualified table name. The variable iDb is
89611 ** set to the index of the database that the table or view is to be
89612 ** created in.
89614 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
89615 if( iDb<0 ) return;
89616 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
89617 /* If creating a temp table, the name may not be qualified. Unless
89618 ** the database name is "temp" anyway. */
89619 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
89620 return;
89622 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
89624 pParse->sNameToken = *pName;
89625 zName = sqlite3NameFromToken(db, pName);
89626 if( zName==0 ) return;
89627 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
89628 goto begin_table_error;
89630 if( db->init.iDb==1 ) isTemp = 1;
89631 #ifndef SQLITE_OMIT_AUTHORIZATION
89632 assert( (isTemp & 1)==isTemp );
89634 int code;
89635 char *zDb = db->aDb[iDb].zName;
89636 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
89637 goto begin_table_error;
89639 if( isView ){
89640 if( !OMIT_TEMPDB && isTemp ){
89641 code = SQLITE_CREATE_TEMP_VIEW;
89642 }else{
89643 code = SQLITE_CREATE_VIEW;
89645 }else{
89646 if( !OMIT_TEMPDB && isTemp ){
89647 code = SQLITE_CREATE_TEMP_TABLE;
89648 }else{
89649 code = SQLITE_CREATE_TABLE;
89652 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
89653 goto begin_table_error;
89656 #endif
89658 /* Make sure the new table name does not collide with an existing
89659 ** index or table name in the same database. Issue an error message if
89660 ** it does. The exception is if the statement being parsed was passed
89661 ** to an sqlite3_declare_vtab() call. In that case only the column names
89662 ** and types will be used, so there is no need to test for namespace
89663 ** collisions.
89665 if( !IN_DECLARE_VTAB ){
89666 char *zDb = db->aDb[iDb].zName;
89667 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
89668 goto begin_table_error;
89670 pTable = sqlite3FindTable(db, zName, zDb);
89671 if( pTable ){
89672 if( !noErr ){
89673 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
89674 }else{
89675 assert( !db->init.busy );
89676 sqlite3CodeVerifySchema(pParse, iDb);
89678 goto begin_table_error;
89680 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
89681 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
89682 goto begin_table_error;
89686 pTable = sqlite3DbMallocZero(db, sizeof(Table));
89687 if( pTable==0 ){
89688 db->mallocFailed = 1;
89689 pParse->rc = SQLITE_NOMEM;
89690 pParse->nErr++;
89691 goto begin_table_error;
89693 pTable->zName = zName;
89694 pTable->iPKey = -1;
89695 pTable->pSchema = db->aDb[iDb].pSchema;
89696 pTable->nRef = 1;
89697 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
89698 assert( pParse->pNewTable==0 );
89699 pParse->pNewTable = pTable;
89701 /* If this is the magic sqlite_sequence table used by autoincrement,
89702 ** then record a pointer to this table in the main database structure
89703 ** so that INSERT can find the table easily.
89705 #ifndef SQLITE_OMIT_AUTOINCREMENT
89706 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
89707 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89708 pTable->pSchema->pSeqTab = pTable;
89710 #endif
89712 /* Begin generating the code that will insert the table record into
89713 ** the SQLITE_MASTER table. Note in particular that we must go ahead
89714 ** and allocate the record number for the table entry now. Before any
89715 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
89716 ** indices to be created and the table record must come before the
89717 ** indices. Hence, the record number for the table must be allocated
89718 ** now.
89720 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
89721 int j1;
89722 int fileFormat;
89723 int reg1, reg2, reg3;
89724 sqlite3BeginWriteOperation(pParse, 0, iDb);
89726 #ifndef SQLITE_OMIT_VIRTUALTABLE
89727 if( isVirtual ){
89728 sqlite3VdbeAddOp0(v, OP_VBegin);
89730 #endif
89732 /* If the file format and encoding in the database have not been set,
89733 ** set them now.
89735 reg1 = pParse->regRowid = ++pParse->nMem;
89736 reg2 = pParse->regRoot = ++pParse->nMem;
89737 reg3 = ++pParse->nMem;
89738 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
89739 sqlite3VdbeUsesBtree(v, iDb);
89740 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
89741 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
89742 1 : SQLITE_MAX_FILE_FORMAT;
89743 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
89744 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
89745 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
89746 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
89747 sqlite3VdbeJumpHere(v, j1);
89749 /* This just creates a place-holder record in the sqlite_master table.
89750 ** The record created does not contain anything yet. It will be replaced
89751 ** by the real entry in code generated at sqlite3EndTable().
89753 ** The rowid for the new entry is left in register pParse->regRowid.
89754 ** The root page number of the new table is left in reg pParse->regRoot.
89755 ** The rowid and root page number values are needed by the code that
89756 ** sqlite3EndTable will generate.
89758 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
89759 if( isView || isVirtual ){
89760 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
89761 }else
89762 #endif
89764 pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
89766 sqlite3OpenMasterTable(pParse, iDb);
89767 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
89768 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
89769 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
89770 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
89771 sqlite3VdbeAddOp0(v, OP_Close);
89774 /* Normal (non-error) return. */
89775 return;
89777 /* If an error occurs, we jump here */
89778 begin_table_error:
89779 sqlite3DbFree(db, zName);
89780 return;
89784 ** This macro is used to compare two strings in a case-insensitive manner.
89785 ** It is slightly faster than calling sqlite3StrICmp() directly, but
89786 ** produces larger code.
89788 ** WARNING: This macro is not compatible with the strcmp() family. It
89789 ** returns true if the two strings are equal, otherwise false.
89791 #define STRICMP(x, y) (\
89792 sqlite3UpperToLower[*(unsigned char *)(x)]== \
89793 sqlite3UpperToLower[*(unsigned char *)(y)] \
89794 && sqlite3StrICmp((x)+1,(y)+1)==0 )
89797 ** Add a new column to the table currently being constructed.
89799 ** The parser calls this routine once for each column declaration
89800 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
89801 ** first to get things going. Then this routine is called for each
89802 ** column.
89804 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
89805 Table *p;
89806 int i;
89807 char *z;
89808 Column *pCol;
89809 sqlite3 *db = pParse->db;
89810 if( (p = pParse->pNewTable)==0 ) return;
89811 #if SQLITE_MAX_COLUMN
89812 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
89813 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
89814 return;
89816 #endif
89817 z = sqlite3NameFromToken(db, pName);
89818 if( z==0 ) return;
89819 for(i=0; i<p->nCol; i++){
89820 if( STRICMP(z, p->aCol[i].zName) ){
89821 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
89822 sqlite3DbFree(db, z);
89823 return;
89826 if( (p->nCol & 0x7)==0 ){
89827 Column *aNew;
89828 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
89829 if( aNew==0 ){
89830 sqlite3DbFree(db, z);
89831 return;
89833 p->aCol = aNew;
89835 pCol = &p->aCol[p->nCol];
89836 memset(pCol, 0, sizeof(p->aCol[0]));
89837 pCol->zName = z;
89839 /* If there is no type specified, columns have the default affinity
89840 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
89841 ** be called next to set pCol->affinity correctly.
89843 pCol->affinity = SQLITE_AFF_NONE;
89844 pCol->szEst = 1;
89845 p->nCol++;
89849 ** This routine is called by the parser while in the middle of
89850 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
89851 ** been seen on a column. This routine sets the notNull flag on
89852 ** the column currently under construction.
89854 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
89855 Table *p;
89856 p = pParse->pNewTable;
89857 if( p==0 || NEVER(p->nCol<1) ) return;
89858 p->aCol[p->nCol-1].notNull = (u8)onError;
89862 ** Scan the column type name zType (length nType) and return the
89863 ** associated affinity type.
89865 ** This routine does a case-independent search of zType for the
89866 ** substrings in the following table. If one of the substrings is
89867 ** found, the corresponding affinity is returned. If zType contains
89868 ** more than one of the substrings, entries toward the top of
89869 ** the table take priority. For example, if zType is 'BLOBINT',
89870 ** SQLITE_AFF_INTEGER is returned.
89872 ** Substring | Affinity
89873 ** --------------------------------
89874 ** 'INT' | SQLITE_AFF_INTEGER
89875 ** 'CHAR' | SQLITE_AFF_TEXT
89876 ** 'CLOB' | SQLITE_AFF_TEXT
89877 ** 'TEXT' | SQLITE_AFF_TEXT
89878 ** 'BLOB' | SQLITE_AFF_NONE
89879 ** 'REAL' | SQLITE_AFF_REAL
89880 ** 'FLOA' | SQLITE_AFF_REAL
89881 ** 'DOUB' | SQLITE_AFF_REAL
89883 ** If none of the substrings in the above table are found,
89884 ** SQLITE_AFF_NUMERIC is returned.
89886 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
89887 u32 h = 0;
89888 char aff = SQLITE_AFF_NUMERIC;
89889 const char *zChar = 0;
89891 if( zIn==0 ) return aff;
89892 while( zIn[0] ){
89893 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
89894 zIn++;
89895 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
89896 aff = SQLITE_AFF_TEXT;
89897 zChar = zIn;
89898 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
89899 aff = SQLITE_AFF_TEXT;
89900 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
89901 aff = SQLITE_AFF_TEXT;
89902 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
89903 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
89904 aff = SQLITE_AFF_NONE;
89905 if( zIn[0]=='(' ) zChar = zIn;
89906 #ifndef SQLITE_OMIT_FLOATING_POINT
89907 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
89908 && aff==SQLITE_AFF_NUMERIC ){
89909 aff = SQLITE_AFF_REAL;
89910 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
89911 && aff==SQLITE_AFF_NUMERIC ){
89912 aff = SQLITE_AFF_REAL;
89913 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
89914 && aff==SQLITE_AFF_NUMERIC ){
89915 aff = SQLITE_AFF_REAL;
89916 #endif
89917 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
89918 aff = SQLITE_AFF_INTEGER;
89919 break;
89923 /* If pszEst is not NULL, store an estimate of the field size. The
89924 ** estimate is scaled so that the size of an integer is 1. */
89925 if( pszEst ){
89926 *pszEst = 1; /* default size is approx 4 bytes */
89927 if( aff<SQLITE_AFF_NUMERIC ){
89928 if( zChar ){
89929 while( zChar[0] ){
89930 if( sqlite3Isdigit(zChar[0]) ){
89931 int v = 0;
89932 sqlite3GetInt32(zChar, &v);
89933 v = v/4 + 1;
89934 if( v>255 ) v = 255;
89935 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
89936 break;
89938 zChar++;
89940 }else{
89941 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
89945 return aff;
89949 ** This routine is called by the parser while in the middle of
89950 ** parsing a CREATE TABLE statement. The pFirst token is the first
89951 ** token in the sequence of tokens that describe the type of the
89952 ** column currently under construction. pLast is the last token
89953 ** in the sequence. Use this information to construct a string
89954 ** that contains the typename of the column and store that string
89955 ** in zType.
89957 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
89958 Table *p;
89959 Column *pCol;
89961 p = pParse->pNewTable;
89962 if( p==0 || NEVER(p->nCol<1) ) return;
89963 pCol = &p->aCol[p->nCol-1];
89964 assert( pCol->zType==0 );
89965 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
89966 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
89970 ** The expression is the default value for the most recently added column
89971 ** of the table currently under construction.
89973 ** Default value expressions must be constant. Raise an exception if this
89974 ** is not the case.
89976 ** This routine is called by the parser while in the middle of
89977 ** parsing a CREATE TABLE statement.
89979 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
89980 Table *p;
89981 Column *pCol;
89982 sqlite3 *db = pParse->db;
89983 p = pParse->pNewTable;
89984 if( p!=0 ){
89985 pCol = &(p->aCol[p->nCol-1]);
89986 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
89987 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
89988 pCol->zName);
89989 }else{
89990 /* A copy of pExpr is used instead of the original, as pExpr contains
89991 ** tokens that point to volatile memory. The 'span' of the expression
89992 ** is required by pragma table_info.
89994 sqlite3ExprDelete(db, pCol->pDflt);
89995 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
89996 sqlite3DbFree(db, pCol->zDflt);
89997 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
89998 (int)(pSpan->zEnd - pSpan->zStart));
90001 sqlite3ExprDelete(db, pSpan->pExpr);
90005 ** Designate the PRIMARY KEY for the table. pList is a list of names
90006 ** of columns that form the primary key. If pList is NULL, then the
90007 ** most recently added column of the table is the primary key.
90009 ** A table can have at most one primary key. If the table already has
90010 ** a primary key (and this is the second primary key) then create an
90011 ** error.
90013 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
90014 ** then we will try to use that column as the rowid. Set the Table.iPKey
90015 ** field of the table under construction to be the index of the
90016 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
90017 ** no INTEGER PRIMARY KEY.
90019 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
90020 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
90022 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
90023 Parse *pParse, /* Parsing context */
90024 ExprList *pList, /* List of field names to be indexed */
90025 int onError, /* What to do with a uniqueness conflict */
90026 int autoInc, /* True if the AUTOINCREMENT keyword is present */
90027 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
90029 Table *pTab = pParse->pNewTable;
90030 char *zType = 0;
90031 int iCol = -1, i;
90032 int nTerm;
90033 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
90034 if( pTab->tabFlags & TF_HasPrimaryKey ){
90035 sqlite3ErrorMsg(pParse,
90036 "table \"%s\" has more than one primary key", pTab->zName);
90037 goto primary_key_exit;
90039 pTab->tabFlags |= TF_HasPrimaryKey;
90040 if( pList==0 ){
90041 iCol = pTab->nCol - 1;
90042 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
90043 zType = pTab->aCol[iCol].zType;
90044 nTerm = 1;
90045 }else{
90046 nTerm = pList->nExpr;
90047 for(i=0; i<nTerm; i++){
90048 for(iCol=0; iCol<pTab->nCol; iCol++){
90049 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
90050 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
90051 zType = pTab->aCol[iCol].zType;
90052 break;
90057 if( nTerm==1
90058 && zType && sqlite3StrICmp(zType, "INTEGER")==0
90059 && sortOrder==SQLITE_SO_ASC
90061 pTab->iPKey = iCol;
90062 pTab->keyConf = (u8)onError;
90063 assert( autoInc==0 || autoInc==1 );
90064 pTab->tabFlags |= autoInc*TF_Autoincrement;
90065 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
90066 }else if( autoInc ){
90067 #ifndef SQLITE_OMIT_AUTOINCREMENT
90068 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
90069 "INTEGER PRIMARY KEY");
90070 #endif
90071 }else{
90072 Vdbe *v = pParse->pVdbe;
90073 Index *p;
90074 if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
90075 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
90076 0, sortOrder, 0);
90077 if( p ){
90078 p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
90079 if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
90081 pList = 0;
90084 primary_key_exit:
90085 sqlite3ExprListDelete(pParse->db, pList);
90086 return;
90090 ** Add a new CHECK constraint to the table currently under construction.
90092 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
90093 Parse *pParse, /* Parsing context */
90094 Expr *pCheckExpr /* The check expression */
90096 #ifndef SQLITE_OMIT_CHECK
90097 Table *pTab = pParse->pNewTable;
90098 sqlite3 *db = pParse->db;
90099 if( pTab && !IN_DECLARE_VTAB
90100 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
90102 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
90103 if( pParse->constraintName.n ){
90104 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
90106 }else
90107 #endif
90109 sqlite3ExprDelete(pParse->db, pCheckExpr);
90114 ** Set the collation function of the most recently parsed table column
90115 ** to the CollSeq given.
90117 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
90118 Table *p;
90119 int i;
90120 char *zColl; /* Dequoted name of collation sequence */
90121 sqlite3 *db;
90123 if( (p = pParse->pNewTable)==0 ) return;
90124 i = p->nCol-1;
90125 db = pParse->db;
90126 zColl = sqlite3NameFromToken(db, pToken);
90127 if( !zColl ) return;
90129 if( sqlite3LocateCollSeq(pParse, zColl) ){
90130 Index *pIdx;
90131 sqlite3DbFree(db, p->aCol[i].zColl);
90132 p->aCol[i].zColl = zColl;
90134 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
90135 ** then an index may have been created on this column before the
90136 ** collation type was added. Correct this if it is the case.
90138 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
90139 assert( pIdx->nKeyCol==1 );
90140 if( pIdx->aiColumn[0]==i ){
90141 pIdx->azColl[0] = p->aCol[i].zColl;
90144 }else{
90145 sqlite3DbFree(db, zColl);
90150 ** This function returns the collation sequence for database native text
90151 ** encoding identified by the string zName, length nName.
90153 ** If the requested collation sequence is not available, or not available
90154 ** in the database native encoding, the collation factory is invoked to
90155 ** request it. If the collation factory does not supply such a sequence,
90156 ** and the sequence is available in another text encoding, then that is
90157 ** returned instead.
90159 ** If no versions of the requested collations sequence are available, or
90160 ** another error occurs, NULL is returned and an error message written into
90161 ** pParse.
90163 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
90164 ** invokes the collation factory if the named collation cannot be found
90165 ** and generates an error message.
90167 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
90169 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
90170 sqlite3 *db = pParse->db;
90171 u8 enc = ENC(db);
90172 u8 initbusy = db->init.busy;
90173 CollSeq *pColl;
90175 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
90176 if( !initbusy && (!pColl || !pColl->xCmp) ){
90177 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
90180 return pColl;
90185 ** Generate code that will increment the schema cookie.
90187 ** The schema cookie is used to determine when the schema for the
90188 ** database changes. After each schema change, the cookie value
90189 ** changes. When a process first reads the schema it records the
90190 ** cookie. Thereafter, whenever it goes to access the database,
90191 ** it checks the cookie to make sure the schema has not changed
90192 ** since it was last read.
90194 ** This plan is not completely bullet-proof. It is possible for
90195 ** the schema to change multiple times and for the cookie to be
90196 ** set back to prior value. But schema changes are infrequent
90197 ** and the probability of hitting the same cookie value is only
90198 ** 1 chance in 2^32. So we're safe enough.
90200 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
90201 int r1 = sqlite3GetTempReg(pParse);
90202 sqlite3 *db = pParse->db;
90203 Vdbe *v = pParse->pVdbe;
90204 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
90205 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
90206 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
90207 sqlite3ReleaseTempReg(pParse, r1);
90211 ** Measure the number of characters needed to output the given
90212 ** identifier. The number returned includes any quotes used
90213 ** but does not include the null terminator.
90215 ** The estimate is conservative. It might be larger that what is
90216 ** really needed.
90218 static int identLength(const char *z){
90219 int n;
90220 for(n=0; *z; n++, z++){
90221 if( *z=='"' ){ n++; }
90223 return n + 2;
90227 ** The first parameter is a pointer to an output buffer. The second
90228 ** parameter is a pointer to an integer that contains the offset at
90229 ** which to write into the output buffer. This function copies the
90230 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
90231 ** to the specified offset in the buffer and updates *pIdx to refer
90232 ** to the first byte after the last byte written before returning.
90234 ** If the string zSignedIdent consists entirely of alpha-numeric
90235 ** characters, does not begin with a digit and is not an SQL keyword,
90236 ** then it is copied to the output buffer exactly as it is. Otherwise,
90237 ** it is quoted using double-quotes.
90239 static void identPut(char *z, int *pIdx, char *zSignedIdent){
90240 unsigned char *zIdent = (unsigned char*)zSignedIdent;
90241 int i, j, needQuote;
90242 i = *pIdx;
90244 for(j=0; zIdent[j]; j++){
90245 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
90247 needQuote = sqlite3Isdigit(zIdent[0])
90248 || sqlite3KeywordCode(zIdent, j)!=TK_ID
90249 || zIdent[j]!=0
90250 || j==0;
90252 if( needQuote ) z[i++] = '"';
90253 for(j=0; zIdent[j]; j++){
90254 z[i++] = zIdent[j];
90255 if( zIdent[j]=='"' ) z[i++] = '"';
90257 if( needQuote ) z[i++] = '"';
90258 z[i] = 0;
90259 *pIdx = i;
90263 ** Generate a CREATE TABLE statement appropriate for the given
90264 ** table. Memory to hold the text of the statement is obtained
90265 ** from sqliteMalloc() and must be freed by the calling function.
90267 static char *createTableStmt(sqlite3 *db, Table *p){
90268 int i, k, n;
90269 char *zStmt;
90270 char *zSep, *zSep2, *zEnd;
90271 Column *pCol;
90272 n = 0;
90273 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
90274 n += identLength(pCol->zName) + 5;
90276 n += identLength(p->zName);
90277 if( n<50 ){
90278 zSep = "";
90279 zSep2 = ",";
90280 zEnd = ")";
90281 }else{
90282 zSep = "\n ";
90283 zSep2 = ",\n ";
90284 zEnd = "\n)";
90286 n += 35 + 6*p->nCol;
90287 zStmt = sqlite3DbMallocRaw(0, n);
90288 if( zStmt==0 ){
90289 db->mallocFailed = 1;
90290 return 0;
90292 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
90293 k = sqlite3Strlen30(zStmt);
90294 identPut(zStmt, &k, p->zName);
90295 zStmt[k++] = '(';
90296 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
90297 static const char * const azType[] = {
90298 /* SQLITE_AFF_NONE */ "",
90299 /* SQLITE_AFF_TEXT */ " TEXT",
90300 /* SQLITE_AFF_NUMERIC */ " NUM",
90301 /* SQLITE_AFF_INTEGER */ " INT",
90302 /* SQLITE_AFF_REAL */ " REAL"
90304 int len;
90305 const char *zType;
90307 sqlite3_snprintf(n-k, &zStmt[k], zSep);
90308 k += sqlite3Strlen30(&zStmt[k]);
90309 zSep = zSep2;
90310 identPut(zStmt, &k, pCol->zName);
90311 assert( pCol->affinity-SQLITE_AFF_NONE >= 0 );
90312 assert( pCol->affinity-SQLITE_AFF_NONE < ArraySize(azType) );
90313 testcase( pCol->affinity==SQLITE_AFF_NONE );
90314 testcase( pCol->affinity==SQLITE_AFF_TEXT );
90315 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
90316 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
90317 testcase( pCol->affinity==SQLITE_AFF_REAL );
90319 zType = azType[pCol->affinity - SQLITE_AFF_NONE];
90320 len = sqlite3Strlen30(zType);
90321 assert( pCol->affinity==SQLITE_AFF_NONE
90322 || pCol->affinity==sqlite3AffinityType(zType, 0) );
90323 memcpy(&zStmt[k], zType, len);
90324 k += len;
90325 assert( k<=n );
90327 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
90328 return zStmt;
90332 ** Resize an Index object to hold N columns total. Return SQLITE_OK
90333 ** on success and SQLITE_NOMEM on an OOM error.
90335 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
90336 char *zExtra;
90337 int nByte;
90338 if( pIdx->nColumn>=N ) return SQLITE_OK;
90339 assert( pIdx->isResized==0 );
90340 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
90341 zExtra = sqlite3DbMallocZero(db, nByte);
90342 if( zExtra==0 ) return SQLITE_NOMEM;
90343 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
90344 pIdx->azColl = (char**)zExtra;
90345 zExtra += sizeof(char*)*N;
90346 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
90347 pIdx->aiColumn = (i16*)zExtra;
90348 zExtra += sizeof(i16)*N;
90349 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
90350 pIdx->aSortOrder = (u8*)zExtra;
90351 pIdx->nColumn = N;
90352 pIdx->isResized = 1;
90353 return SQLITE_OK;
90357 ** Estimate the total row width for a table.
90359 static void estimateTableWidth(Table *pTab){
90360 unsigned wTable = 0;
90361 const Column *pTabCol;
90362 int i;
90363 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
90364 wTable += pTabCol->szEst;
90366 if( pTab->iPKey<0 ) wTable++;
90367 pTab->szTabRow = sqlite3LogEst(wTable*4);
90371 ** Estimate the average size of a row for an index.
90373 static void estimateIndexWidth(Index *pIdx){
90374 unsigned wIndex = 0;
90375 int i;
90376 const Column *aCol = pIdx->pTable->aCol;
90377 for(i=0; i<pIdx->nColumn; i++){
90378 i16 x = pIdx->aiColumn[i];
90379 assert( x<pIdx->pTable->nCol );
90380 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
90382 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
90385 /* Return true if value x is found any of the first nCol entries of aiCol[]
90387 static int hasColumn(const i16 *aiCol, int nCol, int x){
90388 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
90389 return 0;
90393 ** This routine runs at the end of parsing a CREATE TABLE statement that
90394 ** has a WITHOUT ROWID clause. The job of this routine is to convert both
90395 ** internal schema data structures and the generated VDBE code so that they
90396 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
90397 ** Changes include:
90399 ** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
90400 ** no rowid btree for a WITHOUT ROWID. Instead, the canonical
90401 ** data storage is a covering index btree.
90402 ** (2) Bypass the creation of the sqlite_master table entry
90403 ** for the PRIMARY KEY as the primary key index is now
90404 ** identified by the sqlite_master table entry of the table itself.
90405 ** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
90406 ** schema to the rootpage from the main table.
90407 ** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
90408 ** (5) Add all table columns to the PRIMARY KEY Index object
90409 ** so that the PRIMARY KEY is a covering index. The surplus
90410 ** columns are part of KeyInfo.nXField and are not used for
90411 ** sorting or lookup or uniqueness checks.
90412 ** (6) Replace the rowid tail on all automatically generated UNIQUE
90413 ** indices with the PRIMARY KEY columns.
90415 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
90416 Index *pIdx;
90417 Index *pPk;
90418 int nPk;
90419 int i, j;
90420 sqlite3 *db = pParse->db;
90421 Vdbe *v = pParse->pVdbe;
90423 /* Convert the OP_CreateTable opcode that would normally create the
90424 ** root-page for the table into an OP_CreateIndex opcode. The index
90425 ** created will become the PRIMARY KEY index.
90427 if( pParse->addrCrTab ){
90428 assert( v );
90429 sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
90432 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
90433 ** table entry.
90435 if( pParse->addrSkipPK ){
90436 assert( v );
90437 sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
90440 /* Locate the PRIMARY KEY index. Or, if this table was originally
90441 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
90443 if( pTab->iPKey>=0 ){
90444 ExprList *pList;
90445 pList = sqlite3ExprListAppend(pParse, 0, 0);
90446 if( pList==0 ) return;
90447 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
90448 pTab->aCol[pTab->iPKey].zName);
90449 pList->a[0].sortOrder = pParse->iPkSortOrder;
90450 assert( pParse->pNewTable==pTab );
90451 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
90452 if( pPk==0 ) return;
90453 pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
90454 pTab->iPKey = -1;
90455 }else{
90456 pPk = sqlite3PrimaryKeyIndex(pTab);
90458 pPk->isCovering = 1;
90459 assert( pPk!=0 );
90460 nPk = pPk->nKeyCol;
90462 /* Make sure every column of the PRIMARY KEY is NOT NULL */
90463 for(i=0; i<nPk; i++){
90464 pTab->aCol[pPk->aiColumn[i]].notNull = 1;
90466 pPk->uniqNotNull = 1;
90468 /* The root page of the PRIMARY KEY is the table root page */
90469 pPk->tnum = pTab->tnum;
90471 /* Update the in-memory representation of all UNIQUE indices by converting
90472 ** the final rowid column into one or more columns of the PRIMARY KEY.
90474 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
90475 int n;
90476 if( IsPrimaryKeyIndex(pIdx) ) continue;
90477 for(i=n=0; i<nPk; i++){
90478 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
90480 if( n==0 ){
90481 /* This index is a superset of the primary key */
90482 pIdx->nColumn = pIdx->nKeyCol;
90483 continue;
90485 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
90486 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
90487 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
90488 pIdx->aiColumn[j] = pPk->aiColumn[i];
90489 pIdx->azColl[j] = pPk->azColl[i];
90490 j++;
90493 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
90494 assert( pIdx->nColumn>=j );
90497 /* Add all table columns to the PRIMARY KEY index
90499 if( nPk<pTab->nCol ){
90500 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
90501 for(i=0, j=nPk; i<pTab->nCol; i++){
90502 if( !hasColumn(pPk->aiColumn, j, i) ){
90503 assert( j<pPk->nColumn );
90504 pPk->aiColumn[j] = i;
90505 pPk->azColl[j] = "BINARY";
90506 j++;
90509 assert( pPk->nColumn==j );
90510 assert( pTab->nCol==j );
90511 }else{
90512 pPk->nColumn = pTab->nCol;
90517 ** This routine is called to report the final ")" that terminates
90518 ** a CREATE TABLE statement.
90520 ** The table structure that other action routines have been building
90521 ** is added to the internal hash tables, assuming no errors have
90522 ** occurred.
90524 ** An entry for the table is made in the master table on disk, unless
90525 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
90526 ** it means we are reading the sqlite_master table because we just
90527 ** connected to the database or because the sqlite_master table has
90528 ** recently changed, so the entry for this table already exists in
90529 ** the sqlite_master table. We do not want to create it again.
90531 ** If the pSelect argument is not NULL, it means that this routine
90532 ** was called to create a table generated from a
90533 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
90534 ** the new table will match the result set of the SELECT.
90536 SQLITE_PRIVATE void sqlite3EndTable(
90537 Parse *pParse, /* Parse context */
90538 Token *pCons, /* The ',' token after the last column defn. */
90539 Token *pEnd, /* The ')' before options in the CREATE TABLE */
90540 u8 tabOpts, /* Extra table options. Usually 0. */
90541 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
90543 Table *p; /* The new table */
90544 sqlite3 *db = pParse->db; /* The database connection */
90545 int iDb; /* Database in which the table lives */
90546 Index *pIdx; /* An implied index of the table */
90548 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
90549 return;
90551 p = pParse->pNewTable;
90552 if( p==0 ) return;
90554 assert( !db->init.busy || !pSelect );
90556 /* If the db->init.busy is 1 it means we are reading the SQL off the
90557 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
90558 ** So do not write to the disk again. Extract the root page number
90559 ** for the table from the db->init.newTnum field. (The page number
90560 ** should have been put there by the sqliteOpenCb routine.)
90562 if( db->init.busy ){
90563 p->tnum = db->init.newTnum;
90566 /* Special processing for WITHOUT ROWID Tables */
90567 if( tabOpts & TF_WithoutRowid ){
90568 if( (p->tabFlags & TF_Autoincrement) ){
90569 sqlite3ErrorMsg(pParse,
90570 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
90571 return;
90573 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
90574 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
90575 }else{
90576 p->tabFlags |= TF_WithoutRowid;
90577 convertToWithoutRowidTable(pParse, p);
90581 iDb = sqlite3SchemaToIndex(db, p->pSchema);
90583 #ifndef SQLITE_OMIT_CHECK
90584 /* Resolve names in all CHECK constraint expressions.
90586 if( p->pCheck ){
90587 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
90589 #endif /* !defined(SQLITE_OMIT_CHECK) */
90591 /* Estimate the average row size for the table and for all implied indices */
90592 estimateTableWidth(p);
90593 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
90594 estimateIndexWidth(pIdx);
90597 /* If not initializing, then create a record for the new table
90598 ** in the SQLITE_MASTER table of the database.
90600 ** If this is a TEMPORARY table, write the entry into the auxiliary
90601 ** file instead of into the main database file.
90603 if( !db->init.busy ){
90604 int n;
90605 Vdbe *v;
90606 char *zType; /* "view" or "table" */
90607 char *zType2; /* "VIEW" or "TABLE" */
90608 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
90610 v = sqlite3GetVdbe(pParse);
90611 if( NEVER(v==0) ) return;
90613 sqlite3VdbeAddOp1(v, OP_Close, 0);
90616 ** Initialize zType for the new view or table.
90618 if( p->pSelect==0 ){
90619 /* A regular table */
90620 zType = "table";
90621 zType2 = "TABLE";
90622 #ifndef SQLITE_OMIT_VIEW
90623 }else{
90624 /* A view */
90625 zType = "view";
90626 zType2 = "VIEW";
90627 #endif
90630 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
90631 ** statement to populate the new table. The root-page number for the
90632 ** new table is in register pParse->regRoot.
90634 ** Once the SELECT has been coded by sqlite3Select(), it is in a
90635 ** suitable state to query for the column names and types to be used
90636 ** by the new table.
90638 ** A shared-cache write-lock is not required to write to the new table,
90639 ** as a schema-lock must have already been obtained to create it. Since
90640 ** a schema-lock excludes all other database users, the write-lock would
90641 ** be redundant.
90643 if( pSelect ){
90644 SelectDest dest;
90645 Table *pSelTab;
90647 assert(pParse->nTab==1);
90648 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
90649 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
90650 pParse->nTab = 2;
90651 sqlite3SelectDestInit(&dest, SRT_Table, 1);
90652 sqlite3Select(pParse, pSelect, &dest);
90653 sqlite3VdbeAddOp1(v, OP_Close, 1);
90654 if( pParse->nErr==0 ){
90655 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
90656 if( pSelTab==0 ) return;
90657 assert( p->aCol==0 );
90658 p->nCol = pSelTab->nCol;
90659 p->aCol = pSelTab->aCol;
90660 pSelTab->nCol = 0;
90661 pSelTab->aCol = 0;
90662 sqlite3DeleteTable(db, pSelTab);
90666 /* Compute the complete text of the CREATE statement */
90667 if( pSelect ){
90668 zStmt = createTableStmt(db, p);
90669 }else{
90670 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
90671 n = (int)(pEnd2->z - pParse->sNameToken.z);
90672 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
90673 zStmt = sqlite3MPrintf(db,
90674 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
90678 /* A slot for the record has already been allocated in the
90679 ** SQLITE_MASTER table. We just need to update that slot with all
90680 ** the information we've collected.
90682 sqlite3NestedParse(pParse,
90683 "UPDATE %Q.%s "
90684 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
90685 "WHERE rowid=#%d",
90686 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
90687 zType,
90688 p->zName,
90689 p->zName,
90690 pParse->regRoot,
90691 zStmt,
90692 pParse->regRowid
90694 sqlite3DbFree(db, zStmt);
90695 sqlite3ChangeCookie(pParse, iDb);
90697 #ifndef SQLITE_OMIT_AUTOINCREMENT
90698 /* Check to see if we need to create an sqlite_sequence table for
90699 ** keeping track of autoincrement keys.
90701 if( p->tabFlags & TF_Autoincrement ){
90702 Db *pDb = &db->aDb[iDb];
90703 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
90704 if( pDb->pSchema->pSeqTab==0 ){
90705 sqlite3NestedParse(pParse,
90706 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
90707 pDb->zName
90711 #endif
90713 /* Reparse everything to update our internal data structures */
90714 sqlite3VdbeAddParseSchemaOp(v, iDb,
90715 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
90719 /* Add the table to the in-memory representation of the database.
90721 if( db->init.busy ){
90722 Table *pOld;
90723 Schema *pSchema = p->pSchema;
90724 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
90725 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
90726 if( pOld ){
90727 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
90728 db->mallocFailed = 1;
90729 return;
90731 pParse->pNewTable = 0;
90732 db->flags |= SQLITE_InternChanges;
90734 #ifndef SQLITE_OMIT_ALTERTABLE
90735 if( !p->pSelect ){
90736 const char *zName = (const char *)pParse->sNameToken.z;
90737 int nName;
90738 assert( !pSelect && pCons && pEnd );
90739 if( pCons->z==0 ){
90740 pCons = pEnd;
90742 nName = (int)((const char *)pCons->z - zName);
90743 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
90745 #endif
90749 #ifndef SQLITE_OMIT_VIEW
90751 ** The parser calls this routine in order to create a new VIEW
90753 SQLITE_PRIVATE void sqlite3CreateView(
90754 Parse *pParse, /* The parsing context */
90755 Token *pBegin, /* The CREATE token that begins the statement */
90756 Token *pName1, /* The token that holds the name of the view */
90757 Token *pName2, /* The token that holds the name of the view */
90758 Select *pSelect, /* A SELECT statement that will become the new view */
90759 int isTemp, /* TRUE for a TEMPORARY view */
90760 int noErr /* Suppress error messages if VIEW already exists */
90762 Table *p;
90763 int n;
90764 const char *z;
90765 Token sEnd;
90766 DbFixer sFix;
90767 Token *pName = 0;
90768 int iDb;
90769 sqlite3 *db = pParse->db;
90771 if( pParse->nVar>0 ){
90772 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
90773 sqlite3SelectDelete(db, pSelect);
90774 return;
90776 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
90777 p = pParse->pNewTable;
90778 if( p==0 || pParse->nErr ){
90779 sqlite3SelectDelete(db, pSelect);
90780 return;
90782 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
90783 iDb = sqlite3SchemaToIndex(db, p->pSchema);
90784 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
90785 if( sqlite3FixSelect(&sFix, pSelect) ){
90786 sqlite3SelectDelete(db, pSelect);
90787 return;
90790 /* Make a copy of the entire SELECT statement that defines the view.
90791 ** This will force all the Expr.token.z values to be dynamically
90792 ** allocated rather than point to the input string - which means that
90793 ** they will persist after the current sqlite3_exec() call returns.
90795 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
90796 sqlite3SelectDelete(db, pSelect);
90797 if( db->mallocFailed ){
90798 return;
90800 if( !db->init.busy ){
90801 sqlite3ViewGetColumnNames(pParse, p);
90804 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
90805 ** the end.
90807 sEnd = pParse->sLastToken;
90808 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
90809 sEnd.z += sEnd.n;
90811 sEnd.n = 0;
90812 n = (int)(sEnd.z - pBegin->z);
90813 z = pBegin->z;
90814 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
90815 sEnd.z = &z[n-1];
90816 sEnd.n = 1;
90818 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
90819 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
90820 return;
90822 #endif /* SQLITE_OMIT_VIEW */
90824 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
90826 ** The Table structure pTable is really a VIEW. Fill in the names of
90827 ** the columns of the view in the pTable structure. Return the number
90828 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
90830 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
90831 Table *pSelTab; /* A fake table from which we get the result set */
90832 Select *pSel; /* Copy of the SELECT that implements the view */
90833 int nErr = 0; /* Number of errors encountered */
90834 int n; /* Temporarily holds the number of cursors assigned */
90835 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
90836 sqlite3_xauth xAuth; /* Saved xAuth pointer */
90838 assert( pTable );
90840 #ifndef SQLITE_OMIT_VIRTUALTABLE
90841 if( sqlite3VtabCallConnect(pParse, pTable) ){
90842 return SQLITE_ERROR;
90844 if( IsVirtual(pTable) ) return 0;
90845 #endif
90847 #ifndef SQLITE_OMIT_VIEW
90848 /* A positive nCol means the columns names for this view are
90849 ** already known.
90851 if( pTable->nCol>0 ) return 0;
90853 /* A negative nCol is a special marker meaning that we are currently
90854 ** trying to compute the column names. If we enter this routine with
90855 ** a negative nCol, it means two or more views form a loop, like this:
90857 ** CREATE VIEW one AS SELECT * FROM two;
90858 ** CREATE VIEW two AS SELECT * FROM one;
90860 ** Actually, the error above is now caught prior to reaching this point.
90861 ** But the following test is still important as it does come up
90862 ** in the following:
90864 ** CREATE TABLE main.ex1(a);
90865 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
90866 ** SELECT * FROM temp.ex1;
90868 if( pTable->nCol<0 ){
90869 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
90870 return 1;
90872 assert( pTable->nCol>=0 );
90874 /* If we get this far, it means we need to compute the table names.
90875 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
90876 ** "*" elements in the results set of the view and will assign cursors
90877 ** to the elements of the FROM clause. But we do not want these changes
90878 ** to be permanent. So the computation is done on a copy of the SELECT
90879 ** statement that defines the view.
90881 assert( pTable->pSelect );
90882 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
90883 if( pSel ){
90884 u8 enableLookaside = db->lookaside.bEnabled;
90885 n = pParse->nTab;
90886 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
90887 pTable->nCol = -1;
90888 db->lookaside.bEnabled = 0;
90889 #ifndef SQLITE_OMIT_AUTHORIZATION
90890 xAuth = db->xAuth;
90891 db->xAuth = 0;
90892 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
90893 db->xAuth = xAuth;
90894 #else
90895 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
90896 #endif
90897 db->lookaside.bEnabled = enableLookaside;
90898 pParse->nTab = n;
90899 if( pSelTab ){
90900 assert( pTable->aCol==0 );
90901 pTable->nCol = pSelTab->nCol;
90902 pTable->aCol = pSelTab->aCol;
90903 pSelTab->nCol = 0;
90904 pSelTab->aCol = 0;
90905 sqlite3DeleteTable(db, pSelTab);
90906 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
90907 pTable->pSchema->schemaFlags |= DB_UnresetViews;
90908 }else{
90909 pTable->nCol = 0;
90910 nErr++;
90912 sqlite3SelectDelete(db, pSel);
90913 } else {
90914 nErr++;
90916 #endif /* SQLITE_OMIT_VIEW */
90917 return nErr;
90919 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
90921 #ifndef SQLITE_OMIT_VIEW
90923 ** Clear the column names from every VIEW in database idx.
90925 static void sqliteViewResetAll(sqlite3 *db, int idx){
90926 HashElem *i;
90927 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
90928 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
90929 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
90930 Table *pTab = sqliteHashData(i);
90931 if( pTab->pSelect ){
90932 sqliteDeleteColumnNames(db, pTab);
90933 pTab->aCol = 0;
90934 pTab->nCol = 0;
90937 DbClearProperty(db, idx, DB_UnresetViews);
90939 #else
90940 # define sqliteViewResetAll(A,B)
90941 #endif /* SQLITE_OMIT_VIEW */
90944 ** This function is called by the VDBE to adjust the internal schema
90945 ** used by SQLite when the btree layer moves a table root page. The
90946 ** root-page of a table or index in database iDb has changed from iFrom
90947 ** to iTo.
90949 ** Ticket #1728: The symbol table might still contain information
90950 ** on tables and/or indices that are the process of being deleted.
90951 ** If you are unlucky, one of those deleted indices or tables might
90952 ** have the same rootpage number as the real table or index that is
90953 ** being moved. So we cannot stop searching after the first match
90954 ** because the first match might be for one of the deleted indices
90955 ** or tables and not the table/index that is actually being moved.
90956 ** We must continue looping until all tables and indices with
90957 ** rootpage==iFrom have been converted to have a rootpage of iTo
90958 ** in order to be certain that we got the right one.
90960 #ifndef SQLITE_OMIT_AUTOVACUUM
90961 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
90962 HashElem *pElem;
90963 Hash *pHash;
90964 Db *pDb;
90966 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
90967 pDb = &db->aDb[iDb];
90968 pHash = &pDb->pSchema->tblHash;
90969 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
90970 Table *pTab = sqliteHashData(pElem);
90971 if( pTab->tnum==iFrom ){
90972 pTab->tnum = iTo;
90975 pHash = &pDb->pSchema->idxHash;
90976 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
90977 Index *pIdx = sqliteHashData(pElem);
90978 if( pIdx->tnum==iFrom ){
90979 pIdx->tnum = iTo;
90983 #endif
90986 ** Write code to erase the table with root-page iTable from database iDb.
90987 ** Also write code to modify the sqlite_master table and internal schema
90988 ** if a root-page of another table is moved by the btree-layer whilst
90989 ** erasing iTable (this can happen with an auto-vacuum database).
90991 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
90992 Vdbe *v = sqlite3GetVdbe(pParse);
90993 int r1 = sqlite3GetTempReg(pParse);
90994 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
90995 sqlite3MayAbort(pParse);
90996 #ifndef SQLITE_OMIT_AUTOVACUUM
90997 /* OP_Destroy stores an in integer r1. If this integer
90998 ** is non-zero, then it is the root page number of a table moved to
90999 ** location iTable. The following code modifies the sqlite_master table to
91000 ** reflect this.
91002 ** The "#NNN" in the SQL is a special constant that means whatever value
91003 ** is in register NNN. See grammar rules associated with the TK_REGISTER
91004 ** token for additional information.
91006 sqlite3NestedParse(pParse,
91007 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
91008 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
91009 #endif
91010 sqlite3ReleaseTempReg(pParse, r1);
91014 ** Write VDBE code to erase table pTab and all associated indices on disk.
91015 ** Code to update the sqlite_master tables and internal schema definitions
91016 ** in case a root-page belonging to another table is moved by the btree layer
91017 ** is also added (this can happen with an auto-vacuum database).
91019 static void destroyTable(Parse *pParse, Table *pTab){
91020 #ifdef SQLITE_OMIT_AUTOVACUUM
91021 Index *pIdx;
91022 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
91023 destroyRootPage(pParse, pTab->tnum, iDb);
91024 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
91025 destroyRootPage(pParse, pIdx->tnum, iDb);
91027 #else
91028 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
91029 ** is not defined), then it is important to call OP_Destroy on the
91030 ** table and index root-pages in order, starting with the numerically
91031 ** largest root-page number. This guarantees that none of the root-pages
91032 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
91033 ** following were coded:
91035 ** OP_Destroy 4 0
91036 ** ...
91037 ** OP_Destroy 5 0
91039 ** and root page 5 happened to be the largest root-page number in the
91040 ** database, then root page 5 would be moved to page 4 by the
91041 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
91042 ** a free-list page.
91044 int iTab = pTab->tnum;
91045 int iDestroyed = 0;
91047 while( 1 ){
91048 Index *pIdx;
91049 int iLargest = 0;
91051 if( iDestroyed==0 || iTab<iDestroyed ){
91052 iLargest = iTab;
91054 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
91055 int iIdx = pIdx->tnum;
91056 assert( pIdx->pSchema==pTab->pSchema );
91057 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
91058 iLargest = iIdx;
91061 if( iLargest==0 ){
91062 return;
91063 }else{
91064 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
91065 assert( iDb>=0 && iDb<pParse->db->nDb );
91066 destroyRootPage(pParse, iLargest, iDb);
91067 iDestroyed = iLargest;
91070 #endif
91074 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
91075 ** after a DROP INDEX or DROP TABLE command.
91077 static void sqlite3ClearStatTables(
91078 Parse *pParse, /* The parsing context */
91079 int iDb, /* The database number */
91080 const char *zType, /* "idx" or "tbl" */
91081 const char *zName /* Name of index or table */
91083 int i;
91084 const char *zDbName = pParse->db->aDb[iDb].zName;
91085 for(i=1; i<=4; i++){
91086 char zTab[24];
91087 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
91088 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
91089 sqlite3NestedParse(pParse,
91090 "DELETE FROM %Q.%s WHERE %s=%Q",
91091 zDbName, zTab, zType, zName
91098 ** Generate code to drop a table.
91100 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
91101 Vdbe *v;
91102 sqlite3 *db = pParse->db;
91103 Trigger *pTrigger;
91104 Db *pDb = &db->aDb[iDb];
91106 v = sqlite3GetVdbe(pParse);
91107 assert( v!=0 );
91108 sqlite3BeginWriteOperation(pParse, 1, iDb);
91110 #ifndef SQLITE_OMIT_VIRTUALTABLE
91111 if( IsVirtual(pTab) ){
91112 sqlite3VdbeAddOp0(v, OP_VBegin);
91114 #endif
91116 /* Drop all triggers associated with the table being dropped. Code
91117 ** is generated to remove entries from sqlite_master and/or
91118 ** sqlite_temp_master if required.
91120 pTrigger = sqlite3TriggerList(pParse, pTab);
91121 while( pTrigger ){
91122 assert( pTrigger->pSchema==pTab->pSchema ||
91123 pTrigger->pSchema==db->aDb[1].pSchema );
91124 sqlite3DropTriggerPtr(pParse, pTrigger);
91125 pTrigger = pTrigger->pNext;
91128 #ifndef SQLITE_OMIT_AUTOINCREMENT
91129 /* Remove any entries of the sqlite_sequence table associated with
91130 ** the table being dropped. This is done before the table is dropped
91131 ** at the btree level, in case the sqlite_sequence table needs to
91132 ** move as a result of the drop (can happen in auto-vacuum mode).
91134 if( pTab->tabFlags & TF_Autoincrement ){
91135 sqlite3NestedParse(pParse,
91136 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
91137 pDb->zName, pTab->zName
91140 #endif
91142 /* Drop all SQLITE_MASTER table and index entries that refer to the
91143 ** table. The program name loops through the master table and deletes
91144 ** every row that refers to a table of the same name as the one being
91145 ** dropped. Triggers are handled separately because a trigger can be
91146 ** created in the temp database that refers to a table in another
91147 ** database.
91149 sqlite3NestedParse(pParse,
91150 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
91151 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
91152 if( !isView && !IsVirtual(pTab) ){
91153 destroyTable(pParse, pTab);
91156 /* Remove the table entry from SQLite's internal schema and modify
91157 ** the schema cookie.
91159 if( IsVirtual(pTab) ){
91160 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
91162 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
91163 sqlite3ChangeCookie(pParse, iDb);
91164 sqliteViewResetAll(db, iDb);
91168 ** This routine is called to do the work of a DROP TABLE statement.
91169 ** pName is the name of the table to be dropped.
91171 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
91172 Table *pTab;
91173 Vdbe *v;
91174 sqlite3 *db = pParse->db;
91175 int iDb;
91177 if( db->mallocFailed ){
91178 goto exit_drop_table;
91180 assert( pParse->nErr==0 );
91181 assert( pName->nSrc==1 );
91182 if( noErr ) db->suppressErr++;
91183 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
91184 if( noErr ) db->suppressErr--;
91186 if( pTab==0 ){
91187 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
91188 goto exit_drop_table;
91190 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
91191 assert( iDb>=0 && iDb<db->nDb );
91193 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
91194 ** it is initialized.
91196 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
91197 goto exit_drop_table;
91199 #ifndef SQLITE_OMIT_AUTHORIZATION
91201 int code;
91202 const char *zTab = SCHEMA_TABLE(iDb);
91203 const char *zDb = db->aDb[iDb].zName;
91204 const char *zArg2 = 0;
91205 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
91206 goto exit_drop_table;
91208 if( isView ){
91209 if( !OMIT_TEMPDB && iDb==1 ){
91210 code = SQLITE_DROP_TEMP_VIEW;
91211 }else{
91212 code = SQLITE_DROP_VIEW;
91214 #ifndef SQLITE_OMIT_VIRTUALTABLE
91215 }else if( IsVirtual(pTab) ){
91216 code = SQLITE_DROP_VTABLE;
91217 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
91218 #endif
91219 }else{
91220 if( !OMIT_TEMPDB && iDb==1 ){
91221 code = SQLITE_DROP_TEMP_TABLE;
91222 }else{
91223 code = SQLITE_DROP_TABLE;
91226 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
91227 goto exit_drop_table;
91229 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
91230 goto exit_drop_table;
91233 #endif
91234 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
91235 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
91236 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
91237 goto exit_drop_table;
91240 #ifndef SQLITE_OMIT_VIEW
91241 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
91242 ** on a table.
91244 if( isView && pTab->pSelect==0 ){
91245 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
91246 goto exit_drop_table;
91248 if( !isView && pTab->pSelect ){
91249 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
91250 goto exit_drop_table;
91252 #endif
91254 /* Generate code to remove the table from the master table
91255 ** on disk.
91257 v = sqlite3GetVdbe(pParse);
91258 if( v ){
91259 sqlite3BeginWriteOperation(pParse, 1, iDb);
91260 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
91261 sqlite3FkDropTable(pParse, pName, pTab);
91262 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
91265 exit_drop_table:
91266 sqlite3SrcListDelete(db, pName);
91270 ** This routine is called to create a new foreign key on the table
91271 ** currently under construction. pFromCol determines which columns
91272 ** in the current table point to the foreign key. If pFromCol==0 then
91273 ** connect the key to the last column inserted. pTo is the name of
91274 ** the table referred to (a.k.a the "parent" table). pToCol is a list
91275 ** of tables in the parent pTo table. flags contains all
91276 ** information about the conflict resolution algorithms specified
91277 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
91279 ** An FKey structure is created and added to the table currently
91280 ** under construction in the pParse->pNewTable field.
91282 ** The foreign key is set for IMMEDIATE processing. A subsequent call
91283 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
91285 SQLITE_PRIVATE void sqlite3CreateForeignKey(
91286 Parse *pParse, /* Parsing context */
91287 ExprList *pFromCol, /* Columns in this table that point to other table */
91288 Token *pTo, /* Name of the other table */
91289 ExprList *pToCol, /* Columns in the other table */
91290 int flags /* Conflict resolution algorithms. */
91292 sqlite3 *db = pParse->db;
91293 #ifndef SQLITE_OMIT_FOREIGN_KEY
91294 FKey *pFKey = 0;
91295 FKey *pNextTo;
91296 Table *p = pParse->pNewTable;
91297 int nByte;
91298 int i;
91299 int nCol;
91300 char *z;
91302 assert( pTo!=0 );
91303 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
91304 if( pFromCol==0 ){
91305 int iCol = p->nCol-1;
91306 if( NEVER(iCol<0) ) goto fk_end;
91307 if( pToCol && pToCol->nExpr!=1 ){
91308 sqlite3ErrorMsg(pParse, "foreign key on %s"
91309 " should reference only one column of table %T",
91310 p->aCol[iCol].zName, pTo);
91311 goto fk_end;
91313 nCol = 1;
91314 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
91315 sqlite3ErrorMsg(pParse,
91316 "number of columns in foreign key does not match the number of "
91317 "columns in the referenced table");
91318 goto fk_end;
91319 }else{
91320 nCol = pFromCol->nExpr;
91322 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
91323 if( pToCol ){
91324 for(i=0; i<pToCol->nExpr; i++){
91325 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
91328 pFKey = sqlite3DbMallocZero(db, nByte );
91329 if( pFKey==0 ){
91330 goto fk_end;
91332 pFKey->pFrom = p;
91333 pFKey->pNextFrom = p->pFKey;
91334 z = (char*)&pFKey->aCol[nCol];
91335 pFKey->zTo = z;
91336 memcpy(z, pTo->z, pTo->n);
91337 z[pTo->n] = 0;
91338 sqlite3Dequote(z);
91339 z += pTo->n+1;
91340 pFKey->nCol = nCol;
91341 if( pFromCol==0 ){
91342 pFKey->aCol[0].iFrom = p->nCol-1;
91343 }else{
91344 for(i=0; i<nCol; i++){
91345 int j;
91346 for(j=0; j<p->nCol; j++){
91347 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
91348 pFKey->aCol[i].iFrom = j;
91349 break;
91352 if( j>=p->nCol ){
91353 sqlite3ErrorMsg(pParse,
91354 "unknown column \"%s\" in foreign key definition",
91355 pFromCol->a[i].zName);
91356 goto fk_end;
91360 if( pToCol ){
91361 for(i=0; i<nCol; i++){
91362 int n = sqlite3Strlen30(pToCol->a[i].zName);
91363 pFKey->aCol[i].zCol = z;
91364 memcpy(z, pToCol->a[i].zName, n);
91365 z[n] = 0;
91366 z += n+1;
91369 pFKey->isDeferred = 0;
91370 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
91371 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
91373 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
91374 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
91375 pFKey->zTo, (void *)pFKey
91377 if( pNextTo==pFKey ){
91378 db->mallocFailed = 1;
91379 goto fk_end;
91381 if( pNextTo ){
91382 assert( pNextTo->pPrevTo==0 );
91383 pFKey->pNextTo = pNextTo;
91384 pNextTo->pPrevTo = pFKey;
91387 /* Link the foreign key to the table as the last step.
91389 p->pFKey = pFKey;
91390 pFKey = 0;
91392 fk_end:
91393 sqlite3DbFree(db, pFKey);
91394 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
91395 sqlite3ExprListDelete(db, pFromCol);
91396 sqlite3ExprListDelete(db, pToCol);
91400 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
91401 ** clause is seen as part of a foreign key definition. The isDeferred
91402 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
91403 ** The behavior of the most recently created foreign key is adjusted
91404 ** accordingly.
91406 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
91407 #ifndef SQLITE_OMIT_FOREIGN_KEY
91408 Table *pTab;
91409 FKey *pFKey;
91410 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
91411 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
91412 pFKey->isDeferred = (u8)isDeferred;
91413 #endif
91417 ** Generate code that will erase and refill index *pIdx. This is
91418 ** used to initialize a newly created index or to recompute the
91419 ** content of an index in response to a REINDEX command.
91421 ** if memRootPage is not negative, it means that the index is newly
91422 ** created. The register specified by memRootPage contains the
91423 ** root page number of the index. If memRootPage is negative, then
91424 ** the index already exists and must be cleared before being refilled and
91425 ** the root page number of the index is taken from pIndex->tnum.
91427 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
91428 Table *pTab = pIndex->pTable; /* The table that is indexed */
91429 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
91430 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
91431 int iSorter; /* Cursor opened by OpenSorter (if in use) */
91432 int addr1; /* Address of top of loop */
91433 int addr2; /* Address to jump to for next iteration */
91434 int tnum; /* Root page of index */
91435 int iPartIdxLabel; /* Jump to this label to skip a row */
91436 Vdbe *v; /* Generate code into this virtual machine */
91437 KeyInfo *pKey; /* KeyInfo for index */
91438 int regRecord; /* Register holding assembled index record */
91439 sqlite3 *db = pParse->db; /* The database connection */
91440 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
91442 #ifndef SQLITE_OMIT_AUTHORIZATION
91443 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
91444 db->aDb[iDb].zName ) ){
91445 return;
91447 #endif
91449 /* Require a write-lock on the table to perform this operation */
91450 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
91452 v = sqlite3GetVdbe(pParse);
91453 if( v==0 ) return;
91454 if( memRootPage>=0 ){
91455 tnum = memRootPage;
91456 }else{
91457 tnum = pIndex->tnum;
91459 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
91461 /* Open the sorter cursor if we are to use one. */
91462 iSorter = pParse->nTab++;
91463 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
91464 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
91466 /* Open the table. Loop through all rows of the table, inserting index
91467 ** records into the sorter. */
91468 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
91469 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
91470 regRecord = sqlite3GetTempReg(pParse);
91472 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
91473 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
91474 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
91475 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
91476 sqlite3VdbeJumpHere(v, addr1);
91477 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
91478 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
91479 (char *)pKey, P4_KEYINFO);
91480 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
91482 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
91483 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
91484 if( IsUniqueIndex(pIndex) && pKey!=0 ){
91485 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
91486 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
91487 addr2 = sqlite3VdbeCurrentAddr(v);
91488 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
91489 pIndex->nKeyCol); VdbeCoverage(v);
91490 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
91491 }else{
91492 addr2 = sqlite3VdbeCurrentAddr(v);
91494 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
91495 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
91496 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
91497 sqlite3ReleaseTempReg(pParse, regRecord);
91498 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
91499 sqlite3VdbeJumpHere(v, addr1);
91501 sqlite3VdbeAddOp1(v, OP_Close, iTab);
91502 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
91503 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
91507 ** Allocate heap space to hold an Index object with nCol columns.
91509 ** Increase the allocation size to provide an extra nExtra bytes
91510 ** of 8-byte aligned space after the Index object and return a
91511 ** pointer to this extra space in *ppExtra.
91513 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
91514 sqlite3 *db, /* Database connection */
91515 i16 nCol, /* Total number of columns in the index */
91516 int nExtra, /* Number of bytes of extra space to alloc */
91517 char **ppExtra /* Pointer to the "extra" space */
91519 Index *p; /* Allocated index object */
91520 int nByte; /* Bytes of space for Index object + arrays */
91522 nByte = ROUND8(sizeof(Index)) + /* Index structure */
91523 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
91524 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
91525 sizeof(i16)*nCol + /* Index.aiColumn */
91526 sizeof(u8)*nCol); /* Index.aSortOrder */
91527 p = sqlite3DbMallocZero(db, nByte + nExtra);
91528 if( p ){
91529 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
91530 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
91531 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
91532 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
91533 p->aSortOrder = (u8*)pExtra;
91534 p->nColumn = nCol;
91535 p->nKeyCol = nCol - 1;
91536 *ppExtra = ((char*)p) + nByte;
91538 return p;
91542 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
91543 ** and pTblList is the name of the table that is to be indexed. Both will
91544 ** be NULL for a primary key or an index that is created to satisfy a
91545 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
91546 ** as the table to be indexed. pParse->pNewTable is a table that is
91547 ** currently being constructed by a CREATE TABLE statement.
91549 ** pList is a list of columns to be indexed. pList will be NULL if this
91550 ** is a primary key or unique-constraint on the most recent column added
91551 ** to the table currently under construction.
91553 ** If the index is created successfully, return a pointer to the new Index
91554 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
91555 ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
91557 SQLITE_PRIVATE Index *sqlite3CreateIndex(
91558 Parse *pParse, /* All information about this parse */
91559 Token *pName1, /* First part of index name. May be NULL */
91560 Token *pName2, /* Second part of index name. May be NULL */
91561 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
91562 ExprList *pList, /* A list of columns to be indexed */
91563 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
91564 Token *pStart, /* The CREATE token that begins this statement */
91565 Expr *pPIWhere, /* WHERE clause for partial indices */
91566 int sortOrder, /* Sort order of primary key when pList==NULL */
91567 int ifNotExist /* Omit error if index already exists */
91569 Index *pRet = 0; /* Pointer to return */
91570 Table *pTab = 0; /* Table to be indexed */
91571 Index *pIndex = 0; /* The index to be created */
91572 char *zName = 0; /* Name of the index */
91573 int nName; /* Number of characters in zName */
91574 int i, j;
91575 DbFixer sFix; /* For assigning database names to pTable */
91576 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
91577 sqlite3 *db = pParse->db;
91578 Db *pDb; /* The specific table containing the indexed database */
91579 int iDb; /* Index of the database that is being written */
91580 Token *pName = 0; /* Unqualified name of the index to create */
91581 struct ExprList_item *pListItem; /* For looping over pList */
91582 const Column *pTabCol; /* A column in the table */
91583 int nExtra = 0; /* Space allocated for zExtra[] */
91584 int nExtraCol; /* Number of extra columns needed */
91585 char *zExtra = 0; /* Extra space after the Index object */
91586 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
91588 assert( pParse->nErr==0 ); /* Never called with prior errors */
91589 if( db->mallocFailed || IN_DECLARE_VTAB ){
91590 goto exit_create_index;
91592 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
91593 goto exit_create_index;
91597 ** Find the table that is to be indexed. Return early if not found.
91599 if( pTblName!=0 ){
91601 /* Use the two-part index name to determine the database
91602 ** to search for the table. 'Fix' the table name to this db
91603 ** before looking up the table.
91605 assert( pName1 && pName2 );
91606 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
91607 if( iDb<0 ) goto exit_create_index;
91608 assert( pName && pName->z );
91610 #ifndef SQLITE_OMIT_TEMPDB
91611 /* If the index name was unqualified, check if the table
91612 ** is a temp table. If so, set the database to 1. Do not do this
91613 ** if initialising a database schema.
91615 if( !db->init.busy ){
91616 pTab = sqlite3SrcListLookup(pParse, pTblName);
91617 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
91618 iDb = 1;
91621 #endif
91623 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
91624 if( sqlite3FixSrcList(&sFix, pTblName) ){
91625 /* Because the parser constructs pTblName from a single identifier,
91626 ** sqlite3FixSrcList can never fail. */
91627 assert(0);
91629 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
91630 assert( db->mallocFailed==0 || pTab==0 );
91631 if( pTab==0 ) goto exit_create_index;
91632 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
91633 sqlite3ErrorMsg(pParse,
91634 "cannot create a TEMP index on non-TEMP table \"%s\"",
91635 pTab->zName);
91636 goto exit_create_index;
91638 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
91639 }else{
91640 assert( pName==0 );
91641 assert( pStart==0 );
91642 pTab = pParse->pNewTable;
91643 if( !pTab ) goto exit_create_index;
91644 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
91646 pDb = &db->aDb[iDb];
91648 assert( pTab!=0 );
91649 assert( pParse->nErr==0 );
91650 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
91651 && db->init.busy==0
91652 #if SQLITE_USER_AUTHENTICATION
91653 && sqlite3UserAuthTable(pTab->zName)==0
91654 #endif
91655 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
91656 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
91657 goto exit_create_index;
91659 #ifndef SQLITE_OMIT_VIEW
91660 if( pTab->pSelect ){
91661 sqlite3ErrorMsg(pParse, "views may not be indexed");
91662 goto exit_create_index;
91664 #endif
91665 #ifndef SQLITE_OMIT_VIRTUALTABLE
91666 if( IsVirtual(pTab) ){
91667 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
91668 goto exit_create_index;
91670 #endif
91673 ** Find the name of the index. Make sure there is not already another
91674 ** index or table with the same name.
91676 ** Exception: If we are reading the names of permanent indices from the
91677 ** sqlite_master table (because some other process changed the schema) and
91678 ** one of the index names collides with the name of a temporary table or
91679 ** index, then we will continue to process this index.
91681 ** If pName==0 it means that we are
91682 ** dealing with a primary key or UNIQUE constraint. We have to invent our
91683 ** own name.
91685 if( pName ){
91686 zName = sqlite3NameFromToken(db, pName);
91687 if( zName==0 ) goto exit_create_index;
91688 assert( pName->z!=0 );
91689 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
91690 goto exit_create_index;
91692 if( !db->init.busy ){
91693 if( sqlite3FindTable(db, zName, 0)!=0 ){
91694 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
91695 goto exit_create_index;
91698 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
91699 if( !ifNotExist ){
91700 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
91701 }else{
91702 assert( !db->init.busy );
91703 sqlite3CodeVerifySchema(pParse, iDb);
91705 goto exit_create_index;
91707 }else{
91708 int n;
91709 Index *pLoop;
91710 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
91711 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
91712 if( zName==0 ){
91713 goto exit_create_index;
91717 /* Check for authorization to create an index.
91719 #ifndef SQLITE_OMIT_AUTHORIZATION
91721 const char *zDb = pDb->zName;
91722 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
91723 goto exit_create_index;
91725 i = SQLITE_CREATE_INDEX;
91726 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
91727 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
91728 goto exit_create_index;
91731 #endif
91733 /* If pList==0, it means this routine was called to make a primary
91734 ** key out of the last column added to the table under construction.
91735 ** So create a fake list to simulate this.
91737 if( pList==0 ){
91738 pList = sqlite3ExprListAppend(pParse, 0, 0);
91739 if( pList==0 ) goto exit_create_index;
91740 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
91741 pTab->aCol[pTab->nCol-1].zName);
91742 pList->a[0].sortOrder = (u8)sortOrder;
91745 /* Figure out how many bytes of space are required to store explicitly
91746 ** specified collation sequence names.
91748 for(i=0; i<pList->nExpr; i++){
91749 Expr *pExpr = pList->a[i].pExpr;
91750 if( pExpr ){
91751 assert( pExpr->op==TK_COLLATE );
91752 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
91757 ** Allocate the index structure.
91759 nName = sqlite3Strlen30(zName);
91760 nExtraCol = pPk ? pPk->nKeyCol : 1;
91761 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
91762 nName + nExtra + 1, &zExtra);
91763 if( db->mallocFailed ){
91764 goto exit_create_index;
91766 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
91767 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
91768 pIndex->zName = zExtra;
91769 zExtra += nName + 1;
91770 memcpy(pIndex->zName, zName, nName+1);
91771 pIndex->pTable = pTab;
91772 pIndex->onError = (u8)onError;
91773 pIndex->uniqNotNull = onError!=OE_None;
91774 pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
91775 pIndex->pSchema = db->aDb[iDb].pSchema;
91776 pIndex->nKeyCol = pList->nExpr;
91777 if( pPIWhere ){
91778 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
91779 pIndex->pPartIdxWhere = pPIWhere;
91780 pPIWhere = 0;
91782 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91784 /* Check to see if we should honor DESC requests on index columns
91786 if( pDb->pSchema->file_format>=4 ){
91787 sortOrderMask = -1; /* Honor DESC */
91788 }else{
91789 sortOrderMask = 0; /* Ignore DESC */
91792 /* Scan the names of the columns of the table to be indexed and
91793 ** load the column indices into the Index structure. Report an error
91794 ** if any column is not found.
91796 ** TODO: Add a test to make sure that the same column is not named
91797 ** more than once within the same index. Only the first instance of
91798 ** the column will ever be used by the optimizer. Note that using the
91799 ** same column more than once cannot be an error because that would
91800 ** break backwards compatibility - it needs to be a warning.
91802 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
91803 const char *zColName = pListItem->zName;
91804 int requestedSortOrder;
91805 char *zColl; /* Collation sequence name */
91807 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
91808 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
91810 if( j>=pTab->nCol ){
91811 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
91812 pTab->zName, zColName);
91813 pParse->checkSchema = 1;
91814 goto exit_create_index;
91816 assert( j<=0x7fff );
91817 pIndex->aiColumn[i] = (i16)j;
91818 if( pListItem->pExpr ){
91819 int nColl;
91820 assert( pListItem->pExpr->op==TK_COLLATE );
91821 zColl = pListItem->pExpr->u.zToken;
91822 nColl = sqlite3Strlen30(zColl) + 1;
91823 assert( nExtra>=nColl );
91824 memcpy(zExtra, zColl, nColl);
91825 zColl = zExtra;
91826 zExtra += nColl;
91827 nExtra -= nColl;
91828 }else{
91829 zColl = pTab->aCol[j].zColl;
91830 if( !zColl ) zColl = "BINARY";
91832 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
91833 goto exit_create_index;
91835 pIndex->azColl[i] = zColl;
91836 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
91837 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
91838 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
91840 if( pPk ){
91841 for(j=0; j<pPk->nKeyCol; j++){
91842 int x = pPk->aiColumn[j];
91843 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
91844 pIndex->nColumn--;
91845 }else{
91846 pIndex->aiColumn[i] = x;
91847 pIndex->azColl[i] = pPk->azColl[j];
91848 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
91849 i++;
91852 assert( i==pIndex->nColumn );
91853 }else{
91854 pIndex->aiColumn[i] = -1;
91855 pIndex->azColl[i] = "BINARY";
91857 sqlite3DefaultRowEst(pIndex);
91858 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
91860 if( pTab==pParse->pNewTable ){
91861 /* This routine has been called to create an automatic index as a
91862 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
91863 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
91864 ** i.e. one of:
91866 ** CREATE TABLE t(x PRIMARY KEY, y);
91867 ** CREATE TABLE t(x, y, UNIQUE(x, y));
91869 ** Either way, check to see if the table already has such an index. If
91870 ** so, don't bother creating this one. This only applies to
91871 ** automatically created indices. Users can do as they wish with
91872 ** explicit indices.
91874 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
91875 ** (and thus suppressing the second one) even if they have different
91876 ** sort orders.
91878 ** If there are different collating sequences or if the columns of
91879 ** the constraint occur in different orders, then the constraints are
91880 ** considered distinct and both result in separate indices.
91882 Index *pIdx;
91883 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
91884 int k;
91885 assert( IsUniqueIndex(pIdx) );
91886 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
91887 assert( IsUniqueIndex(pIndex) );
91889 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
91890 for(k=0; k<pIdx->nKeyCol; k++){
91891 const char *z1;
91892 const char *z2;
91893 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
91894 z1 = pIdx->azColl[k];
91895 z2 = pIndex->azColl[k];
91896 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
91898 if( k==pIdx->nKeyCol ){
91899 if( pIdx->onError!=pIndex->onError ){
91900 /* This constraint creates the same index as a previous
91901 ** constraint specified somewhere in the CREATE TABLE statement.
91902 ** However the ON CONFLICT clauses are different. If both this
91903 ** constraint and the previous equivalent constraint have explicit
91904 ** ON CONFLICT clauses this is an error. Otherwise, use the
91905 ** explicitly specified behavior for the index.
91907 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
91908 sqlite3ErrorMsg(pParse,
91909 "conflicting ON CONFLICT clauses specified", 0);
91911 if( pIdx->onError==OE_Default ){
91912 pIdx->onError = pIndex->onError;
91915 goto exit_create_index;
91920 /* Link the new Index structure to its table and to the other
91921 ** in-memory database structures.
91923 if( db->init.busy ){
91924 Index *p;
91925 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
91926 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
91927 pIndex->zName, pIndex);
91928 if( p ){
91929 assert( p==pIndex ); /* Malloc must have failed */
91930 db->mallocFailed = 1;
91931 goto exit_create_index;
91933 db->flags |= SQLITE_InternChanges;
91934 if( pTblName!=0 ){
91935 pIndex->tnum = db->init.newTnum;
91939 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
91940 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
91941 ** emit code to allocate the index rootpage on disk and make an entry for
91942 ** the index in the sqlite_master table and populate the index with
91943 ** content. But, do not do this if we are simply reading the sqlite_master
91944 ** table to parse the schema, or if this index is the PRIMARY KEY index
91945 ** of a WITHOUT ROWID table.
91947 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
91948 ** or UNIQUE index in a CREATE TABLE statement. Since the table
91949 ** has just been created, it contains no data and the index initialization
91950 ** step can be skipped.
91952 else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
91953 Vdbe *v;
91954 char *zStmt;
91955 int iMem = ++pParse->nMem;
91957 v = sqlite3GetVdbe(pParse);
91958 if( v==0 ) goto exit_create_index;
91961 /* Create the rootpage for the index
91963 sqlite3BeginWriteOperation(pParse, 1, iDb);
91964 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
91966 /* Gather the complete text of the CREATE INDEX statement into
91967 ** the zStmt variable
91969 if( pStart ){
91970 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
91971 if( pName->z[n-1]==';' ) n--;
91972 /* A named index with an explicit CREATE INDEX statement */
91973 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
91974 onError==OE_None ? "" : " UNIQUE", n, pName->z);
91975 }else{
91976 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
91977 /* zStmt = sqlite3MPrintf(""); */
91978 zStmt = 0;
91981 /* Add an entry in sqlite_master for this index
91983 sqlite3NestedParse(pParse,
91984 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
91985 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
91986 pIndex->zName,
91987 pTab->zName,
91988 iMem,
91989 zStmt
91991 sqlite3DbFree(db, zStmt);
91993 /* Fill the index with data and reparse the schema. Code an OP_Expire
91994 ** to invalidate all pre-compiled statements.
91996 if( pTblName ){
91997 sqlite3RefillIndex(pParse, pIndex, iMem);
91998 sqlite3ChangeCookie(pParse, iDb);
91999 sqlite3VdbeAddParseSchemaOp(v, iDb,
92000 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
92001 sqlite3VdbeAddOp1(v, OP_Expire, 0);
92005 /* When adding an index to the list of indices for a table, make
92006 ** sure all indices labeled OE_Replace come after all those labeled
92007 ** OE_Ignore. This is necessary for the correct constraint check
92008 ** processing (in sqlite3GenerateConstraintChecks()) as part of
92009 ** UPDATE and INSERT statements.
92011 if( db->init.busy || pTblName==0 ){
92012 if( onError!=OE_Replace || pTab->pIndex==0
92013 || pTab->pIndex->onError==OE_Replace){
92014 pIndex->pNext = pTab->pIndex;
92015 pTab->pIndex = pIndex;
92016 }else{
92017 Index *pOther = pTab->pIndex;
92018 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
92019 pOther = pOther->pNext;
92021 pIndex->pNext = pOther->pNext;
92022 pOther->pNext = pIndex;
92024 pRet = pIndex;
92025 pIndex = 0;
92028 /* Clean up before exiting */
92029 exit_create_index:
92030 if( pIndex ) freeIndex(db, pIndex);
92031 sqlite3ExprDelete(db, pPIWhere);
92032 sqlite3ExprListDelete(db, pList);
92033 sqlite3SrcListDelete(db, pTblName);
92034 sqlite3DbFree(db, zName);
92035 return pRet;
92039 ** Fill the Index.aiRowEst[] array with default information - information
92040 ** to be used when we have not run the ANALYZE command.
92042 ** aiRowEst[0] is supposed to contain the number of elements in the index.
92043 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
92044 ** number of rows in the table that match any particular value of the
92045 ** first column of the index. aiRowEst[2] is an estimate of the number
92046 ** of rows that match any particular combination of the first 2 columns
92047 ** of the index. And so forth. It must always be the case that
92049 ** aiRowEst[N]<=aiRowEst[N-1]
92050 ** aiRowEst[N]>=1
92052 ** Apart from that, we have little to go on besides intuition as to
92053 ** how aiRowEst[] should be initialized. The numbers generated here
92054 ** are based on typical values found in actual indices.
92056 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
92057 /* 10, 9, 8, 7, 6 */
92058 LogEst aVal[] = { 33, 32, 30, 28, 26 };
92059 LogEst *a = pIdx->aiRowLogEst;
92060 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
92061 int i;
92063 /* Set the first entry (number of rows in the index) to the estimated
92064 ** number of rows in the table. Or 10, if the estimated number of rows
92065 ** in the table is less than that. */
92066 a[0] = pIdx->pTable->nRowLogEst;
92067 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
92069 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
92070 ** 6 and each subsequent value (if any) is 5. */
92071 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
92072 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
92073 a[i] = 23; assert( 23==sqlite3LogEst(5) );
92076 assert( 0==sqlite3LogEst(1) );
92077 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
92081 ** This routine will drop an existing named index. This routine
92082 ** implements the DROP INDEX statement.
92084 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
92085 Index *pIndex;
92086 Vdbe *v;
92087 sqlite3 *db = pParse->db;
92088 int iDb;
92090 assert( pParse->nErr==0 ); /* Never called with prior errors */
92091 if( db->mallocFailed ){
92092 goto exit_drop_index;
92094 assert( pName->nSrc==1 );
92095 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
92096 goto exit_drop_index;
92098 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
92099 if( pIndex==0 ){
92100 if( !ifExists ){
92101 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
92102 }else{
92103 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
92105 pParse->checkSchema = 1;
92106 goto exit_drop_index;
92108 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
92109 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
92110 "or PRIMARY KEY constraint cannot be dropped", 0);
92111 goto exit_drop_index;
92113 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
92114 #ifndef SQLITE_OMIT_AUTHORIZATION
92116 int code = SQLITE_DROP_INDEX;
92117 Table *pTab = pIndex->pTable;
92118 const char *zDb = db->aDb[iDb].zName;
92119 const char *zTab = SCHEMA_TABLE(iDb);
92120 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
92121 goto exit_drop_index;
92123 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
92124 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
92125 goto exit_drop_index;
92128 #endif
92130 /* Generate code to remove the index and from the master table */
92131 v = sqlite3GetVdbe(pParse);
92132 if( v ){
92133 sqlite3BeginWriteOperation(pParse, 1, iDb);
92134 sqlite3NestedParse(pParse,
92135 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
92136 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
92138 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
92139 sqlite3ChangeCookie(pParse, iDb);
92140 destroyRootPage(pParse, pIndex->tnum, iDb);
92141 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
92144 exit_drop_index:
92145 sqlite3SrcListDelete(db, pName);
92149 ** pArray is a pointer to an array of objects. Each object in the
92150 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
92151 ** to extend the array so that there is space for a new object at the end.
92153 ** When this function is called, *pnEntry contains the current size of
92154 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
92155 ** in total).
92157 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
92158 ** space allocated for the new object is zeroed, *pnEntry updated to
92159 ** reflect the new size of the array and a pointer to the new allocation
92160 ** returned. *pIdx is set to the index of the new array entry in this case.
92162 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
92163 ** unchanged and a copy of pArray returned.
92165 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
92166 sqlite3 *db, /* Connection to notify of malloc failures */
92167 void *pArray, /* Array of objects. Might be reallocated */
92168 int szEntry, /* Size of each object in the array */
92169 int *pnEntry, /* Number of objects currently in use */
92170 int *pIdx /* Write the index of a new slot here */
92172 char *z;
92173 int n = *pnEntry;
92174 if( (n & (n-1))==0 ){
92175 int sz = (n==0) ? 1 : 2*n;
92176 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
92177 if( pNew==0 ){
92178 *pIdx = -1;
92179 return pArray;
92181 pArray = pNew;
92183 z = (char*)pArray;
92184 memset(&z[n * szEntry], 0, szEntry);
92185 *pIdx = n;
92186 ++*pnEntry;
92187 return pArray;
92191 ** Append a new element to the given IdList. Create a new IdList if
92192 ** need be.
92194 ** A new IdList is returned, or NULL if malloc() fails.
92196 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
92197 int i;
92198 if( pList==0 ){
92199 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
92200 if( pList==0 ) return 0;
92202 pList->a = sqlite3ArrayAllocate(
92204 pList->a,
92205 sizeof(pList->a[0]),
92206 &pList->nId,
92209 if( i<0 ){
92210 sqlite3IdListDelete(db, pList);
92211 return 0;
92213 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
92214 return pList;
92218 ** Delete an IdList.
92220 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
92221 int i;
92222 if( pList==0 ) return;
92223 for(i=0; i<pList->nId; i++){
92224 sqlite3DbFree(db, pList->a[i].zName);
92226 sqlite3DbFree(db, pList->a);
92227 sqlite3DbFree(db, pList);
92231 ** Return the index in pList of the identifier named zId. Return -1
92232 ** if not found.
92234 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
92235 int i;
92236 if( pList==0 ) return -1;
92237 for(i=0; i<pList->nId; i++){
92238 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
92240 return -1;
92244 ** Expand the space allocated for the given SrcList object by
92245 ** creating nExtra new slots beginning at iStart. iStart is zero based.
92246 ** New slots are zeroed.
92248 ** For example, suppose a SrcList initially contains two entries: A,B.
92249 ** To append 3 new entries onto the end, do this:
92251 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
92253 ** After the call above it would contain: A, B, nil, nil, nil.
92254 ** If the iStart argument had been 1 instead of 2, then the result
92255 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
92256 ** the iStart value would be 0. The result then would
92257 ** be: nil, nil, nil, A, B.
92259 ** If a memory allocation fails the SrcList is unchanged. The
92260 ** db->mallocFailed flag will be set to true.
92262 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
92263 sqlite3 *db, /* Database connection to notify of OOM errors */
92264 SrcList *pSrc, /* The SrcList to be enlarged */
92265 int nExtra, /* Number of new slots to add to pSrc->a[] */
92266 int iStart /* Index in pSrc->a[] of first new slot */
92268 int i;
92270 /* Sanity checking on calling parameters */
92271 assert( iStart>=0 );
92272 assert( nExtra>=1 );
92273 assert( pSrc!=0 );
92274 assert( iStart<=pSrc->nSrc );
92276 /* Allocate additional space if needed */
92277 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
92278 SrcList *pNew;
92279 int nAlloc = pSrc->nSrc+nExtra;
92280 int nGot;
92281 pNew = sqlite3DbRealloc(db, pSrc,
92282 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
92283 if( pNew==0 ){
92284 assert( db->mallocFailed );
92285 return pSrc;
92287 pSrc = pNew;
92288 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
92289 pSrc->nAlloc = nGot;
92292 /* Move existing slots that come after the newly inserted slots
92293 ** out of the way */
92294 for(i=pSrc->nSrc-1; i>=iStart; i--){
92295 pSrc->a[i+nExtra] = pSrc->a[i];
92297 pSrc->nSrc += nExtra;
92299 /* Zero the newly allocated slots */
92300 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
92301 for(i=iStart; i<iStart+nExtra; i++){
92302 pSrc->a[i].iCursor = -1;
92305 /* Return a pointer to the enlarged SrcList */
92306 return pSrc;
92311 ** Append a new table name to the given SrcList. Create a new SrcList if
92312 ** need be. A new entry is created in the SrcList even if pTable is NULL.
92314 ** A SrcList is returned, or NULL if there is an OOM error. The returned
92315 ** SrcList might be the same as the SrcList that was input or it might be
92316 ** a new one. If an OOM error does occurs, then the prior value of pList
92317 ** that is input to this routine is automatically freed.
92319 ** If pDatabase is not null, it means that the table has an optional
92320 ** database name prefix. Like this: "database.table". The pDatabase
92321 ** points to the table name and the pTable points to the database name.
92322 ** The SrcList.a[].zName field is filled with the table name which might
92323 ** come from pTable (if pDatabase is NULL) or from pDatabase.
92324 ** SrcList.a[].zDatabase is filled with the database name from pTable,
92325 ** or with NULL if no database is specified.
92327 ** In other words, if call like this:
92329 ** sqlite3SrcListAppend(D,A,B,0);
92331 ** Then B is a table name and the database name is unspecified. If called
92332 ** like this:
92334 ** sqlite3SrcListAppend(D,A,B,C);
92336 ** Then C is the table name and B is the database name. If C is defined
92337 ** then so is B. In other words, we never have a case where:
92339 ** sqlite3SrcListAppend(D,A,0,C);
92341 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
92342 ** before being added to the SrcList.
92344 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
92345 sqlite3 *db, /* Connection to notify of malloc failures */
92346 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
92347 Token *pTable, /* Table to append */
92348 Token *pDatabase /* Database of the table */
92350 struct SrcList_item *pItem;
92351 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
92352 if( pList==0 ){
92353 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
92354 if( pList==0 ) return 0;
92355 pList->nAlloc = 1;
92357 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
92358 if( db->mallocFailed ){
92359 sqlite3SrcListDelete(db, pList);
92360 return 0;
92362 pItem = &pList->a[pList->nSrc-1];
92363 if( pDatabase && pDatabase->z==0 ){
92364 pDatabase = 0;
92366 if( pDatabase ){
92367 Token *pTemp = pDatabase;
92368 pDatabase = pTable;
92369 pTable = pTemp;
92371 pItem->zName = sqlite3NameFromToken(db, pTable);
92372 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
92373 return pList;
92377 ** Assign VdbeCursor index numbers to all tables in a SrcList
92379 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
92380 int i;
92381 struct SrcList_item *pItem;
92382 assert(pList || pParse->db->mallocFailed );
92383 if( pList ){
92384 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
92385 if( pItem->iCursor>=0 ) break;
92386 pItem->iCursor = pParse->nTab++;
92387 if( pItem->pSelect ){
92388 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
92395 ** Delete an entire SrcList including all its substructure.
92397 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
92398 int i;
92399 struct SrcList_item *pItem;
92400 if( pList==0 ) return;
92401 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
92402 sqlite3DbFree(db, pItem->zDatabase);
92403 sqlite3DbFree(db, pItem->zName);
92404 sqlite3DbFree(db, pItem->zAlias);
92405 sqlite3DbFree(db, pItem->zIndex);
92406 sqlite3DeleteTable(db, pItem->pTab);
92407 sqlite3SelectDelete(db, pItem->pSelect);
92408 sqlite3ExprDelete(db, pItem->pOn);
92409 sqlite3IdListDelete(db, pItem->pUsing);
92411 sqlite3DbFree(db, pList);
92415 ** This routine is called by the parser to add a new term to the
92416 ** end of a growing FROM clause. The "p" parameter is the part of
92417 ** the FROM clause that has already been constructed. "p" is NULL
92418 ** if this is the first term of the FROM clause. pTable and pDatabase
92419 ** are the name of the table and database named in the FROM clause term.
92420 ** pDatabase is NULL if the database name qualifier is missing - the
92421 ** usual case. If the term has an alias, then pAlias points to the
92422 ** alias token. If the term is a subquery, then pSubquery is the
92423 ** SELECT statement that the subquery encodes. The pTable and
92424 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
92425 ** parameters are the content of the ON and USING clauses.
92427 ** Return a new SrcList which encodes is the FROM with the new
92428 ** term added.
92430 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
92431 Parse *pParse, /* Parsing context */
92432 SrcList *p, /* The left part of the FROM clause already seen */
92433 Token *pTable, /* Name of the table to add to the FROM clause */
92434 Token *pDatabase, /* Name of the database containing pTable */
92435 Token *pAlias, /* The right-hand side of the AS subexpression */
92436 Select *pSubquery, /* A subquery used in place of a table name */
92437 Expr *pOn, /* The ON clause of a join */
92438 IdList *pUsing /* The USING clause of a join */
92440 struct SrcList_item *pItem;
92441 sqlite3 *db = pParse->db;
92442 if( !p && (pOn || pUsing) ){
92443 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
92444 (pOn ? "ON" : "USING")
92446 goto append_from_error;
92448 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
92449 if( p==0 || NEVER(p->nSrc==0) ){
92450 goto append_from_error;
92452 pItem = &p->a[p->nSrc-1];
92453 assert( pAlias!=0 );
92454 if( pAlias->n ){
92455 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
92457 pItem->pSelect = pSubquery;
92458 pItem->pOn = pOn;
92459 pItem->pUsing = pUsing;
92460 return p;
92462 append_from_error:
92463 assert( p==0 );
92464 sqlite3ExprDelete(db, pOn);
92465 sqlite3IdListDelete(db, pUsing);
92466 sqlite3SelectDelete(db, pSubquery);
92467 return 0;
92471 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
92472 ** element of the source-list passed as the second argument.
92474 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
92475 assert( pIndexedBy!=0 );
92476 if( p && ALWAYS(p->nSrc>0) ){
92477 struct SrcList_item *pItem = &p->a[p->nSrc-1];
92478 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
92479 if( pIndexedBy->n==1 && !pIndexedBy->z ){
92480 /* A "NOT INDEXED" clause was supplied. See parse.y
92481 ** construct "indexed_opt" for details. */
92482 pItem->notIndexed = 1;
92483 }else{
92484 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
92490 ** When building up a FROM clause in the parser, the join operator
92491 ** is initially attached to the left operand. But the code generator
92492 ** expects the join operator to be on the right operand. This routine
92493 ** Shifts all join operators from left to right for an entire FROM
92494 ** clause.
92496 ** Example: Suppose the join is like this:
92498 ** A natural cross join B
92500 ** The operator is "natural cross join". The A and B operands are stored
92501 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
92502 ** operator with A. This routine shifts that operator over to B.
92504 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
92505 if( p ){
92506 int i;
92507 assert( p->a || p->nSrc==0 );
92508 for(i=p->nSrc-1; i>0; i--){
92509 p->a[i].jointype = p->a[i-1].jointype;
92511 p->a[0].jointype = 0;
92516 ** Begin a transaction
92518 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
92519 sqlite3 *db;
92520 Vdbe *v;
92521 int i;
92523 assert( pParse!=0 );
92524 db = pParse->db;
92525 assert( db!=0 );
92526 /* if( db->aDb[0].pBt==0 ) return; */
92527 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
92528 return;
92530 v = sqlite3GetVdbe(pParse);
92531 if( !v ) return;
92532 if( type!=TK_DEFERRED ){
92533 for(i=0; i<db->nDb; i++){
92534 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
92535 sqlite3VdbeUsesBtree(v, i);
92538 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
92542 ** Commit a transaction
92544 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
92545 Vdbe *v;
92547 assert( pParse!=0 );
92548 assert( pParse->db!=0 );
92549 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
92550 return;
92552 v = sqlite3GetVdbe(pParse);
92553 if( v ){
92554 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
92559 ** Rollback a transaction
92561 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
92562 Vdbe *v;
92564 assert( pParse!=0 );
92565 assert( pParse->db!=0 );
92566 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
92567 return;
92569 v = sqlite3GetVdbe(pParse);
92570 if( v ){
92571 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
92576 ** This function is called by the parser when it parses a command to create,
92577 ** release or rollback an SQL savepoint.
92579 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
92580 char *zName = sqlite3NameFromToken(pParse->db, pName);
92581 if( zName ){
92582 Vdbe *v = sqlite3GetVdbe(pParse);
92583 #ifndef SQLITE_OMIT_AUTHORIZATION
92584 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
92585 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
92586 #endif
92587 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
92588 sqlite3DbFree(pParse->db, zName);
92589 return;
92591 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
92596 ** Make sure the TEMP database is open and available for use. Return
92597 ** the number of errors. Leave any error messages in the pParse structure.
92599 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
92600 sqlite3 *db = pParse->db;
92601 if( db->aDb[1].pBt==0 && !pParse->explain ){
92602 int rc;
92603 Btree *pBt;
92604 static const int flags =
92605 SQLITE_OPEN_READWRITE |
92606 SQLITE_OPEN_CREATE |
92607 SQLITE_OPEN_EXCLUSIVE |
92608 SQLITE_OPEN_DELETEONCLOSE |
92609 SQLITE_OPEN_TEMP_DB;
92611 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
92612 if( rc!=SQLITE_OK ){
92613 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
92614 "file for storing temporary tables");
92615 pParse->rc = rc;
92616 return 1;
92618 db->aDb[1].pBt = pBt;
92619 assert( db->aDb[1].pSchema );
92620 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
92621 db->mallocFailed = 1;
92622 return 1;
92625 return 0;
92629 ** Record the fact that the schema cookie will need to be verified
92630 ** for database iDb. The code to actually verify the schema cookie
92631 ** will occur at the end of the top-level VDBE and will be generated
92632 ** later, by sqlite3FinishCoding().
92634 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
92635 Parse *pToplevel = sqlite3ParseToplevel(pParse);
92636 sqlite3 *db = pToplevel->db;
92638 assert( iDb>=0 && iDb<db->nDb );
92639 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
92640 assert( iDb<SQLITE_MAX_ATTACHED+2 );
92641 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92642 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
92643 DbMaskSet(pToplevel->cookieMask, iDb);
92644 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
92645 if( !OMIT_TEMPDB && iDb==1 ){
92646 sqlite3OpenTempDatabase(pToplevel);
92652 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
92653 ** attached database. Otherwise, invoke it for the database named zDb only.
92655 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
92656 sqlite3 *db = pParse->db;
92657 int i;
92658 for(i=0; i<db->nDb; i++){
92659 Db *pDb = &db->aDb[i];
92660 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
92661 sqlite3CodeVerifySchema(pParse, i);
92667 ** Generate VDBE code that prepares for doing an operation that
92668 ** might change the database.
92670 ** This routine starts a new transaction if we are not already within
92671 ** a transaction. If we are already within a transaction, then a checkpoint
92672 ** is set if the setStatement parameter is true. A checkpoint should
92673 ** be set for operations that might fail (due to a constraint) part of
92674 ** the way through and which will need to undo some writes without having to
92675 ** rollback the whole transaction. For operations where all constraints
92676 ** can be checked before any changes are made to the database, it is never
92677 ** necessary to undo a write and the checkpoint should not be set.
92679 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
92680 Parse *pToplevel = sqlite3ParseToplevel(pParse);
92681 sqlite3CodeVerifySchema(pParse, iDb);
92682 DbMaskSet(pToplevel->writeMask, iDb);
92683 pToplevel->isMultiWrite |= setStatement;
92687 ** Indicate that the statement currently under construction might write
92688 ** more than one entry (example: deleting one row then inserting another,
92689 ** inserting multiple rows in a table, or inserting a row and index entries.)
92690 ** If an abort occurs after some of these writes have completed, then it will
92691 ** be necessary to undo the completed writes.
92693 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
92694 Parse *pToplevel = sqlite3ParseToplevel(pParse);
92695 pToplevel->isMultiWrite = 1;
92699 ** The code generator calls this routine if is discovers that it is
92700 ** possible to abort a statement prior to completion. In order to
92701 ** perform this abort without corrupting the database, we need to make
92702 ** sure that the statement is protected by a statement transaction.
92704 ** Technically, we only need to set the mayAbort flag if the
92705 ** isMultiWrite flag was previously set. There is a time dependency
92706 ** such that the abort must occur after the multiwrite. This makes
92707 ** some statements involving the REPLACE conflict resolution algorithm
92708 ** go a little faster. But taking advantage of this time dependency
92709 ** makes it more difficult to prove that the code is correct (in
92710 ** particular, it prevents us from writing an effective
92711 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
92712 ** to take the safe route and skip the optimization.
92714 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
92715 Parse *pToplevel = sqlite3ParseToplevel(pParse);
92716 pToplevel->mayAbort = 1;
92720 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
92721 ** error. The onError parameter determines which (if any) of the statement
92722 ** and/or current transaction is rolled back.
92724 SQLITE_PRIVATE void sqlite3HaltConstraint(
92725 Parse *pParse, /* Parsing context */
92726 int errCode, /* extended error code */
92727 int onError, /* Constraint type */
92728 char *p4, /* Error message */
92729 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
92730 u8 p5Errmsg /* P5_ErrMsg type */
92732 Vdbe *v = sqlite3GetVdbe(pParse);
92733 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
92734 if( onError==OE_Abort ){
92735 sqlite3MayAbort(pParse);
92737 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
92738 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
92742 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
92744 SQLITE_PRIVATE void sqlite3UniqueConstraint(
92745 Parse *pParse, /* Parsing context */
92746 int onError, /* Constraint type */
92747 Index *pIdx /* The index that triggers the constraint */
92749 char *zErr;
92750 int j;
92751 StrAccum errMsg;
92752 Table *pTab = pIdx->pTable;
92754 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
92755 errMsg.db = pParse->db;
92756 for(j=0; j<pIdx->nKeyCol; j++){
92757 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
92758 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
92759 sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
92760 sqlite3StrAccumAppend(&errMsg, ".", 1);
92761 sqlite3StrAccumAppendAll(&errMsg, zCol);
92763 zErr = sqlite3StrAccumFinish(&errMsg);
92764 sqlite3HaltConstraint(pParse,
92765 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
92766 : SQLITE_CONSTRAINT_UNIQUE,
92767 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
92772 ** Code an OP_Halt due to non-unique rowid.
92774 SQLITE_PRIVATE void sqlite3RowidConstraint(
92775 Parse *pParse, /* Parsing context */
92776 int onError, /* Conflict resolution algorithm */
92777 Table *pTab /* The table with the non-unique rowid */
92779 char *zMsg;
92780 int rc;
92781 if( pTab->iPKey>=0 ){
92782 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
92783 pTab->aCol[pTab->iPKey].zName);
92784 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
92785 }else{
92786 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
92787 rc = SQLITE_CONSTRAINT_ROWID;
92789 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
92790 P5_ConstraintUnique);
92794 ** Check to see if pIndex uses the collating sequence pColl. Return
92795 ** true if it does and false if it does not.
92797 #ifndef SQLITE_OMIT_REINDEX
92798 static int collationMatch(const char *zColl, Index *pIndex){
92799 int i;
92800 assert( zColl!=0 );
92801 for(i=0; i<pIndex->nColumn; i++){
92802 const char *z = pIndex->azColl[i];
92803 assert( z!=0 || pIndex->aiColumn[i]<0 );
92804 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
92805 return 1;
92808 return 0;
92810 #endif
92813 ** Recompute all indices of pTab that use the collating sequence pColl.
92814 ** If pColl==0 then recompute all indices of pTab.
92816 #ifndef SQLITE_OMIT_REINDEX
92817 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
92818 Index *pIndex; /* An index associated with pTab */
92820 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
92821 if( zColl==0 || collationMatch(zColl, pIndex) ){
92822 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
92823 sqlite3BeginWriteOperation(pParse, 0, iDb);
92824 sqlite3RefillIndex(pParse, pIndex, -1);
92828 #endif
92831 ** Recompute all indices of all tables in all databases where the
92832 ** indices use the collating sequence pColl. If pColl==0 then recompute
92833 ** all indices everywhere.
92835 #ifndef SQLITE_OMIT_REINDEX
92836 static void reindexDatabases(Parse *pParse, char const *zColl){
92837 Db *pDb; /* A single database */
92838 int iDb; /* The database index number */
92839 sqlite3 *db = pParse->db; /* The database connection */
92840 HashElem *k; /* For looping over tables in pDb */
92841 Table *pTab; /* A table in the database */
92843 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
92844 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
92845 assert( pDb!=0 );
92846 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
92847 pTab = (Table*)sqliteHashData(k);
92848 reindexTable(pParse, pTab, zColl);
92852 #endif
92855 ** Generate code for the REINDEX command.
92857 ** REINDEX -- 1
92858 ** REINDEX <collation> -- 2
92859 ** REINDEX ?<database>.?<tablename> -- 3
92860 ** REINDEX ?<database>.?<indexname> -- 4
92862 ** Form 1 causes all indices in all attached databases to be rebuilt.
92863 ** Form 2 rebuilds all indices in all databases that use the named
92864 ** collating function. Forms 3 and 4 rebuild the named index or all
92865 ** indices associated with the named table.
92867 #ifndef SQLITE_OMIT_REINDEX
92868 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
92869 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
92870 char *z; /* Name of a table or index */
92871 const char *zDb; /* Name of the database */
92872 Table *pTab; /* A table in the database */
92873 Index *pIndex; /* An index associated with pTab */
92874 int iDb; /* The database index number */
92875 sqlite3 *db = pParse->db; /* The database connection */
92876 Token *pObjName; /* Name of the table or index to be reindexed */
92878 /* Read the database schema. If an error occurs, leave an error message
92879 ** and code in pParse and return NULL. */
92880 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
92881 return;
92884 if( pName1==0 ){
92885 reindexDatabases(pParse, 0);
92886 return;
92887 }else if( NEVER(pName2==0) || pName2->z==0 ){
92888 char *zColl;
92889 assert( pName1->z );
92890 zColl = sqlite3NameFromToken(pParse->db, pName1);
92891 if( !zColl ) return;
92892 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
92893 if( pColl ){
92894 reindexDatabases(pParse, zColl);
92895 sqlite3DbFree(db, zColl);
92896 return;
92898 sqlite3DbFree(db, zColl);
92900 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
92901 if( iDb<0 ) return;
92902 z = sqlite3NameFromToken(db, pObjName);
92903 if( z==0 ) return;
92904 zDb = db->aDb[iDb].zName;
92905 pTab = sqlite3FindTable(db, z, zDb);
92906 if( pTab ){
92907 reindexTable(pParse, pTab, 0);
92908 sqlite3DbFree(db, z);
92909 return;
92911 pIndex = sqlite3FindIndex(db, z, zDb);
92912 sqlite3DbFree(db, z);
92913 if( pIndex ){
92914 sqlite3BeginWriteOperation(pParse, 0, iDb);
92915 sqlite3RefillIndex(pParse, pIndex, -1);
92916 return;
92918 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
92920 #endif
92923 ** Return a KeyInfo structure that is appropriate for the given Index.
92925 ** The KeyInfo structure for an index is cached in the Index object.
92926 ** So there might be multiple references to the returned pointer. The
92927 ** caller should not try to modify the KeyInfo object.
92929 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
92930 ** when it has finished using it.
92932 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
92933 if( pParse->nErr ) return 0;
92934 #ifndef SQLITE_OMIT_SHARED_CACHE
92935 if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
92936 sqlite3KeyInfoUnref(pIdx->pKeyInfo);
92937 pIdx->pKeyInfo = 0;
92939 #endif
92940 if( pIdx->pKeyInfo==0 ){
92941 int i;
92942 int nCol = pIdx->nColumn;
92943 int nKey = pIdx->nKeyCol;
92944 KeyInfo *pKey;
92945 if( pIdx->uniqNotNull ){
92946 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
92947 }else{
92948 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
92950 if( pKey ){
92951 assert( sqlite3KeyInfoIsWriteable(pKey) );
92952 for(i=0; i<nCol; i++){
92953 char *zColl = pIdx->azColl[i];
92954 assert( zColl!=0 );
92955 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
92956 sqlite3LocateCollSeq(pParse, zColl);
92957 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
92959 if( pParse->nErr ){
92960 sqlite3KeyInfoUnref(pKey);
92961 }else{
92962 pIdx->pKeyInfo = pKey;
92966 return sqlite3KeyInfoRef(pIdx->pKeyInfo);
92969 #ifndef SQLITE_OMIT_CTE
92971 ** This routine is invoked once per CTE by the parser while parsing a
92972 ** WITH clause.
92974 SQLITE_PRIVATE With *sqlite3WithAdd(
92975 Parse *pParse, /* Parsing context */
92976 With *pWith, /* Existing WITH clause, or NULL */
92977 Token *pName, /* Name of the common-table */
92978 ExprList *pArglist, /* Optional column name list for the table */
92979 Select *pQuery /* Query used to initialize the table */
92981 sqlite3 *db = pParse->db;
92982 With *pNew;
92983 char *zName;
92985 /* Check that the CTE name is unique within this WITH clause. If
92986 ** not, store an error in the Parse structure. */
92987 zName = sqlite3NameFromToken(pParse->db, pName);
92988 if( zName && pWith ){
92989 int i;
92990 for(i=0; i<pWith->nCte; i++){
92991 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
92992 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
92997 if( pWith ){
92998 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
92999 pNew = sqlite3DbRealloc(db, pWith, nByte);
93000 }else{
93001 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
93003 assert( zName!=0 || pNew==0 );
93004 assert( db->mallocFailed==0 || pNew==0 );
93006 if( pNew==0 ){
93007 sqlite3ExprListDelete(db, pArglist);
93008 sqlite3SelectDelete(db, pQuery);
93009 sqlite3DbFree(db, zName);
93010 pNew = pWith;
93011 }else{
93012 pNew->a[pNew->nCte].pSelect = pQuery;
93013 pNew->a[pNew->nCte].pCols = pArglist;
93014 pNew->a[pNew->nCte].zName = zName;
93015 pNew->a[pNew->nCte].zErr = 0;
93016 pNew->nCte++;
93019 return pNew;
93023 ** Free the contents of the With object passed as the second argument.
93025 SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
93026 if( pWith ){
93027 int i;
93028 for(i=0; i<pWith->nCte; i++){
93029 struct Cte *pCte = &pWith->a[i];
93030 sqlite3ExprListDelete(db, pCte->pCols);
93031 sqlite3SelectDelete(db, pCte->pSelect);
93032 sqlite3DbFree(db, pCte->zName);
93034 sqlite3DbFree(db, pWith);
93037 #endif /* !defined(SQLITE_OMIT_CTE) */
93039 /************** End of build.c ***********************************************/
93040 /************** Begin file callback.c ****************************************/
93042 ** 2005 May 23
93044 ** The author disclaims copyright to this source code. In place of
93045 ** a legal notice, here is a blessing:
93047 ** May you do good and not evil.
93048 ** May you find forgiveness for yourself and forgive others.
93049 ** May you share freely, never taking more than you give.
93051 *************************************************************************
93053 ** This file contains functions used to access the internal hash tables
93054 ** of user defined functions and collation sequences.
93059 ** Invoke the 'collation needed' callback to request a collation sequence
93060 ** in the encoding enc of name zName, length nName.
93062 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
93063 assert( !db->xCollNeeded || !db->xCollNeeded16 );
93064 if( db->xCollNeeded ){
93065 char *zExternal = sqlite3DbStrDup(db, zName);
93066 if( !zExternal ) return;
93067 db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
93068 sqlite3DbFree(db, zExternal);
93070 #ifndef SQLITE_OMIT_UTF16
93071 if( db->xCollNeeded16 ){
93072 char const *zExternal;
93073 sqlite3_value *pTmp = sqlite3ValueNew(db);
93074 sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
93075 zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
93076 if( zExternal ){
93077 db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
93079 sqlite3ValueFree(pTmp);
93081 #endif
93085 ** This routine is called if the collation factory fails to deliver a
93086 ** collation function in the best encoding but there may be other versions
93087 ** of this collation function (for other text encodings) available. Use one
93088 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
93089 ** possible.
93091 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
93092 CollSeq *pColl2;
93093 char *z = pColl->zName;
93094 int i;
93095 static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
93096 for(i=0; i<3; i++){
93097 pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
93098 if( pColl2->xCmp!=0 ){
93099 memcpy(pColl, pColl2, sizeof(CollSeq));
93100 pColl->xDel = 0; /* Do not copy the destructor */
93101 return SQLITE_OK;
93104 return SQLITE_ERROR;
93108 ** This function is responsible for invoking the collation factory callback
93109 ** or substituting a collation sequence of a different encoding when the
93110 ** requested collation sequence is not available in the desired encoding.
93112 ** If it is not NULL, then pColl must point to the database native encoding
93113 ** collation sequence with name zName, length nName.
93115 ** The return value is either the collation sequence to be used in database
93116 ** db for collation type name zName, length nName, or NULL, if no collation
93117 ** sequence can be found. If no collation is found, leave an error message.
93119 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
93121 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
93122 Parse *pParse, /* Parsing context */
93123 u8 enc, /* The desired encoding for the collating sequence */
93124 CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
93125 const char *zName /* Collating sequence name */
93127 CollSeq *p;
93128 sqlite3 *db = pParse->db;
93130 p = pColl;
93131 if( !p ){
93132 p = sqlite3FindCollSeq(db, enc, zName, 0);
93134 if( !p || !p->xCmp ){
93135 /* No collation sequence of this type for this encoding is registered.
93136 ** Call the collation factory to see if it can supply us with one.
93138 callCollNeeded(db, enc, zName);
93139 p = sqlite3FindCollSeq(db, enc, zName, 0);
93141 if( p && !p->xCmp && synthCollSeq(db, p) ){
93142 p = 0;
93144 assert( !p || p->xCmp );
93145 if( p==0 ){
93146 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
93148 return p;
93152 ** This routine is called on a collation sequence before it is used to
93153 ** check that it is defined. An undefined collation sequence exists when
93154 ** a database is loaded that contains references to collation sequences
93155 ** that have not been defined by sqlite3_create_collation() etc.
93157 ** If required, this routine calls the 'collation needed' callback to
93158 ** request a definition of the collating sequence. If this doesn't work,
93159 ** an equivalent collating sequence that uses a text encoding different
93160 ** from the main database is substituted, if one is available.
93162 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
93163 if( pColl ){
93164 const char *zName = pColl->zName;
93165 sqlite3 *db = pParse->db;
93166 CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
93167 if( !p ){
93168 return SQLITE_ERROR;
93170 assert( p==pColl );
93172 return SQLITE_OK;
93178 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
93179 ** specified by zName and nName is not found and parameter 'create' is
93180 ** true, then create a new entry. Otherwise return NULL.
93182 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
93183 ** array of three CollSeq structures. The first is the collation sequence
93184 ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
93186 ** Stored immediately after the three collation sequences is a copy of
93187 ** the collation sequence name. A pointer to this string is stored in
93188 ** each collation sequence structure.
93190 static CollSeq *findCollSeqEntry(
93191 sqlite3 *db, /* Database connection */
93192 const char *zName, /* Name of the collating sequence */
93193 int create /* Create a new entry if true */
93195 CollSeq *pColl;
93196 pColl = sqlite3HashFind(&db->aCollSeq, zName);
93198 if( 0==pColl && create ){
93199 int nName = sqlite3Strlen30(zName);
93200 pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
93201 if( pColl ){
93202 CollSeq *pDel = 0;
93203 pColl[0].zName = (char*)&pColl[3];
93204 pColl[0].enc = SQLITE_UTF8;
93205 pColl[1].zName = (char*)&pColl[3];
93206 pColl[1].enc = SQLITE_UTF16LE;
93207 pColl[2].zName = (char*)&pColl[3];
93208 pColl[2].enc = SQLITE_UTF16BE;
93209 memcpy(pColl[0].zName, zName, nName);
93210 pColl[0].zName[nName] = 0;
93211 pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
93213 /* If a malloc() failure occurred in sqlite3HashInsert(), it will
93214 ** return the pColl pointer to be deleted (because it wasn't added
93215 ** to the hash table).
93217 assert( pDel==0 || pDel==pColl );
93218 if( pDel!=0 ){
93219 db->mallocFailed = 1;
93220 sqlite3DbFree(db, pDel);
93221 pColl = 0;
93225 return pColl;
93229 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
93230 ** Return the CollSeq* pointer for the collation sequence named zName
93231 ** for the encoding 'enc' from the database 'db'.
93233 ** If the entry specified is not found and 'create' is true, then create a
93234 ** new entry. Otherwise return NULL.
93236 ** A separate function sqlite3LocateCollSeq() is a wrapper around
93237 ** this routine. sqlite3LocateCollSeq() invokes the collation factory
93238 ** if necessary and generates an error message if the collating sequence
93239 ** cannot be found.
93241 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
93243 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
93244 sqlite3 *db,
93245 u8 enc,
93246 const char *zName,
93247 int create
93249 CollSeq *pColl;
93250 if( zName ){
93251 pColl = findCollSeqEntry(db, zName, create);
93252 }else{
93253 pColl = db->pDfltColl;
93255 assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
93256 assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
93257 if( pColl ) pColl += enc-1;
93258 return pColl;
93261 /* During the search for the best function definition, this procedure
93262 ** is called to test how well the function passed as the first argument
93263 ** matches the request for a function with nArg arguments in a system
93264 ** that uses encoding enc. The value returned indicates how well the
93265 ** request is matched. A higher value indicates a better match.
93267 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
93268 ** is also -1. In other words, we are searching for a function that
93269 ** takes a variable number of arguments.
93271 ** If nArg is -2 that means that we are searching for any function
93272 ** regardless of the number of arguments it uses, so return a positive
93273 ** match score for any
93275 ** The returned value is always between 0 and 6, as follows:
93277 ** 0: Not a match.
93278 ** 1: UTF8/16 conversion required and function takes any number of arguments.
93279 ** 2: UTF16 byte order change required and function takes any number of args.
93280 ** 3: encoding matches and function takes any number of arguments
93281 ** 4: UTF8/16 conversion required - argument count matches exactly
93282 ** 5: UTF16 byte order conversion required - argument count matches exactly
93283 ** 6: Perfect match: encoding and argument count match exactly.
93285 ** If nArg==(-2) then any function with a non-null xStep or xFunc is
93286 ** a perfect match and any function with both xStep and xFunc NULL is
93287 ** a non-match.
93289 #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
93290 static int matchQuality(
93291 FuncDef *p, /* The function we are evaluating for match quality */
93292 int nArg, /* Desired number of arguments. (-1)==any */
93293 u8 enc /* Desired text encoding */
93295 int match;
93297 /* nArg of -2 is a special case */
93298 if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
93300 /* Wrong number of arguments means "no match" */
93301 if( p->nArg!=nArg && p->nArg>=0 ) return 0;
93303 /* Give a better score to a function with a specific number of arguments
93304 ** than to function that accepts any number of arguments. */
93305 if( p->nArg==nArg ){
93306 match = 4;
93307 }else{
93308 match = 1;
93311 /* Bonus points if the text encoding matches */
93312 if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
93313 match += 2; /* Exact encoding match */
93314 }else if( (enc & p->funcFlags & 2)!=0 ){
93315 match += 1; /* Both are UTF16, but with different byte orders */
93318 return match;
93322 ** Search a FuncDefHash for a function with the given name. Return
93323 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
93325 static FuncDef *functionSearch(
93326 FuncDefHash *pHash, /* Hash table to search */
93327 int h, /* Hash of the name */
93328 const char *zFunc, /* Name of function */
93329 int nFunc /* Number of bytes in zFunc */
93331 FuncDef *p;
93332 for(p=pHash->a[h]; p; p=p->pHash){
93333 if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
93334 return p;
93337 return 0;
93341 ** Insert a new FuncDef into a FuncDefHash hash table.
93343 SQLITE_PRIVATE void sqlite3FuncDefInsert(
93344 FuncDefHash *pHash, /* The hash table into which to insert */
93345 FuncDef *pDef /* The function definition to insert */
93347 FuncDef *pOther;
93348 int nName = sqlite3Strlen30(pDef->zName);
93349 u8 c1 = (u8)pDef->zName[0];
93350 int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
93351 pOther = functionSearch(pHash, h, pDef->zName, nName);
93352 if( pOther ){
93353 assert( pOther!=pDef && pOther->pNext!=pDef );
93354 pDef->pNext = pOther->pNext;
93355 pOther->pNext = pDef;
93356 }else{
93357 pDef->pNext = 0;
93358 pDef->pHash = pHash->a[h];
93359 pHash->a[h] = pDef;
93366 ** Locate a user function given a name, a number of arguments and a flag
93367 ** indicating whether the function prefers UTF-16 over UTF-8. Return a
93368 ** pointer to the FuncDef structure that defines that function, or return
93369 ** NULL if the function does not exist.
93371 ** If the createFlag argument is true, then a new (blank) FuncDef
93372 ** structure is created and liked into the "db" structure if a
93373 ** no matching function previously existed.
93375 ** If nArg is -2, then the first valid function found is returned. A
93376 ** function is valid if either xFunc or xStep is non-zero. The nArg==(-2)
93377 ** case is used to see if zName is a valid function name for some number
93378 ** of arguments. If nArg is -2, then createFlag must be 0.
93380 ** If createFlag is false, then a function with the required name and
93381 ** number of arguments may be returned even if the eTextRep flag does not
93382 ** match that requested.
93384 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
93385 sqlite3 *db, /* An open database */
93386 const char *zName, /* Name of the function. Not null-terminated */
93387 int nName, /* Number of characters in the name */
93388 int nArg, /* Number of arguments. -1 means any number */
93389 u8 enc, /* Preferred text encoding */
93390 u8 createFlag /* Create new entry if true and does not otherwise exist */
93392 FuncDef *p; /* Iterator variable */
93393 FuncDef *pBest = 0; /* Best match found so far */
93394 int bestScore = 0; /* Score of best match */
93395 int h; /* Hash value */
93397 assert( nArg>=(-2) );
93398 assert( nArg>=(-1) || createFlag==0 );
93399 h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
93401 /* First search for a match amongst the application-defined functions.
93403 p = functionSearch(&db->aFunc, h, zName, nName);
93404 while( p ){
93405 int score = matchQuality(p, nArg, enc);
93406 if( score>bestScore ){
93407 pBest = p;
93408 bestScore = score;
93410 p = p->pNext;
93413 /* If no match is found, search the built-in functions.
93415 ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
93416 ** functions even if a prior app-defined function was found. And give
93417 ** priority to built-in functions.
93419 ** Except, if createFlag is true, that means that we are trying to
93420 ** install a new function. Whatever FuncDef structure is returned it will
93421 ** have fields overwritten with new information appropriate for the
93422 ** new function. But the FuncDefs for built-in functions are read-only.
93423 ** So we must not search for built-ins when creating a new function.
93425 if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
93426 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
93427 bestScore = 0;
93428 p = functionSearch(pHash, h, zName, nName);
93429 while( p ){
93430 int score = matchQuality(p, nArg, enc);
93431 if( score>bestScore ){
93432 pBest = p;
93433 bestScore = score;
93435 p = p->pNext;
93439 /* If the createFlag parameter is true and the search did not reveal an
93440 ** exact match for the name, number of arguments and encoding, then add a
93441 ** new entry to the hash table and return it.
93443 if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
93444 (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
93445 pBest->zName = (char *)&pBest[1];
93446 pBest->nArg = (u16)nArg;
93447 pBest->funcFlags = enc;
93448 memcpy(pBest->zName, zName, nName);
93449 pBest->zName[nName] = 0;
93450 sqlite3FuncDefInsert(&db->aFunc, pBest);
93453 if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
93454 return pBest;
93456 return 0;
93460 ** Free all resources held by the schema structure. The void* argument points
93461 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
93462 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
93463 ** of the schema hash tables).
93465 ** The Schema.cache_size variable is not cleared.
93467 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
93468 Hash temp1;
93469 Hash temp2;
93470 HashElem *pElem;
93471 Schema *pSchema = (Schema *)p;
93473 temp1 = pSchema->tblHash;
93474 temp2 = pSchema->trigHash;
93475 sqlite3HashInit(&pSchema->trigHash);
93476 sqlite3HashClear(&pSchema->idxHash);
93477 for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
93478 sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
93480 sqlite3HashClear(&temp2);
93481 sqlite3HashInit(&pSchema->tblHash);
93482 for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
93483 Table *pTab = sqliteHashData(pElem);
93484 sqlite3DeleteTable(0, pTab);
93486 sqlite3HashClear(&temp1);
93487 sqlite3HashClear(&pSchema->fkeyHash);
93488 pSchema->pSeqTab = 0;
93489 if( pSchema->schemaFlags & DB_SchemaLoaded ){
93490 pSchema->iGeneration++;
93491 pSchema->schemaFlags &= ~DB_SchemaLoaded;
93496 ** Find and return the schema associated with a BTree. Create
93497 ** a new one if necessary.
93499 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
93500 Schema * p;
93501 if( pBt ){
93502 p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
93503 }else{
93504 p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
93506 if( !p ){
93507 db->mallocFailed = 1;
93508 }else if ( 0==p->file_format ){
93509 sqlite3HashInit(&p->tblHash);
93510 sqlite3HashInit(&p->idxHash);
93511 sqlite3HashInit(&p->trigHash);
93512 sqlite3HashInit(&p->fkeyHash);
93513 p->enc = SQLITE_UTF8;
93515 return p;
93518 /************** End of callback.c ********************************************/
93519 /************** Begin file delete.c ******************************************/
93521 ** 2001 September 15
93523 ** The author disclaims copyright to this source code. In place of
93524 ** a legal notice, here is a blessing:
93526 ** May you do good and not evil.
93527 ** May you find forgiveness for yourself and forgive others.
93528 ** May you share freely, never taking more than you give.
93530 *************************************************************************
93531 ** This file contains C code routines that are called by the parser
93532 ** in order to generate code for DELETE FROM statements.
93536 ** While a SrcList can in general represent multiple tables and subqueries
93537 ** (as in the FROM clause of a SELECT statement) in this case it contains
93538 ** the name of a single table, as one might find in an INSERT, DELETE,
93539 ** or UPDATE statement. Look up that table in the symbol table and
93540 ** return a pointer. Set an error message and return NULL if the table
93541 ** name is not found or if any other error occurs.
93543 ** The following fields are initialized appropriate in pSrc:
93545 ** pSrc->a[0].pTab Pointer to the Table object
93546 ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
93549 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
93550 struct SrcList_item *pItem = pSrc->a;
93551 Table *pTab;
93552 assert( pItem && pSrc->nSrc==1 );
93553 pTab = sqlite3LocateTableItem(pParse, 0, pItem);
93554 sqlite3DeleteTable(pParse->db, pItem->pTab);
93555 pItem->pTab = pTab;
93556 if( pTab ){
93557 pTab->nRef++;
93559 if( sqlite3IndexedByLookup(pParse, pItem) ){
93560 pTab = 0;
93562 return pTab;
93566 ** Check to make sure the given table is writable. If it is not
93567 ** writable, generate an error message and return 1. If it is
93568 ** writable return 0;
93570 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
93571 /* A table is not writable under the following circumstances:
93573 ** 1) It is a virtual table and no implementation of the xUpdate method
93574 ** has been provided, or
93575 ** 2) It is a system table (i.e. sqlite_master), this call is not
93576 ** part of a nested parse and writable_schema pragma has not
93577 ** been specified.
93579 ** In either case leave an error message in pParse and return non-zero.
93581 if( ( IsVirtual(pTab)
93582 && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
93583 || ( (pTab->tabFlags & TF_Readonly)!=0
93584 && (pParse->db->flags & SQLITE_WriteSchema)==0
93585 && pParse->nested==0 )
93587 sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
93588 return 1;
93591 #ifndef SQLITE_OMIT_VIEW
93592 if( !viewOk && pTab->pSelect ){
93593 sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
93594 return 1;
93596 #endif
93597 return 0;
93601 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
93603 ** Evaluate a view and store its result in an ephemeral table. The
93604 ** pWhere argument is an optional WHERE clause that restricts the
93605 ** set of rows in the view that are to be added to the ephemeral table.
93607 SQLITE_PRIVATE void sqlite3MaterializeView(
93608 Parse *pParse, /* Parsing context */
93609 Table *pView, /* View definition */
93610 Expr *pWhere, /* Optional WHERE clause to be added */
93611 int iCur /* Cursor number for ephemeral table */
93613 SelectDest dest;
93614 Select *pSel;
93615 SrcList *pFrom;
93616 sqlite3 *db = pParse->db;
93617 int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
93618 pWhere = sqlite3ExprDup(db, pWhere, 0);
93619 pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
93620 if( pFrom ){
93621 assert( pFrom->nSrc==1 );
93622 pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
93623 pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
93624 assert( pFrom->a[0].pOn==0 );
93625 assert( pFrom->a[0].pUsing==0 );
93627 pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
93628 sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
93629 sqlite3Select(pParse, pSel, &dest);
93630 sqlite3SelectDelete(db, pSel);
93632 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
93634 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
93636 ** Generate an expression tree to implement the WHERE, ORDER BY,
93637 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
93639 ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
93640 ** \__________________________/
93641 ** pLimitWhere (pInClause)
93643 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
93644 Parse *pParse, /* The parser context */
93645 SrcList *pSrc, /* the FROM clause -- which tables to scan */
93646 Expr *pWhere, /* The WHERE clause. May be null */
93647 ExprList *pOrderBy, /* The ORDER BY clause. May be null */
93648 Expr *pLimit, /* The LIMIT clause. May be null */
93649 Expr *pOffset, /* The OFFSET clause. May be null */
93650 char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
93652 Expr *pWhereRowid = NULL; /* WHERE rowid .. */
93653 Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
93654 Expr *pSelectRowid = NULL; /* SELECT rowid ... */
93655 ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
93656 SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
93657 Select *pSelect = NULL; /* Complete SELECT tree */
93659 /* Check that there isn't an ORDER BY without a LIMIT clause.
93661 if( pOrderBy && (pLimit == 0) ) {
93662 sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
93663 goto limit_where_cleanup_2;
93666 /* We only need to generate a select expression if there
93667 ** is a limit/offset term to enforce.
93669 if( pLimit == 0 ) {
93670 /* if pLimit is null, pOffset will always be null as well. */
93671 assert( pOffset == 0 );
93672 return pWhere;
93675 /* Generate a select expression tree to enforce the limit/offset
93676 ** term for the DELETE or UPDATE statement. For example:
93677 ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
93678 ** becomes:
93679 ** DELETE FROM table_a WHERE rowid IN (
93680 ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
93681 ** );
93684 pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
93685 if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
93686 pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
93687 if( pEList == 0 ) goto limit_where_cleanup_2;
93689 /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
93690 ** and the SELECT subtree. */
93691 pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
93692 if( pSelectSrc == 0 ) {
93693 sqlite3ExprListDelete(pParse->db, pEList);
93694 goto limit_where_cleanup_2;
93697 /* generate the SELECT expression tree. */
93698 pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
93699 pOrderBy,0,pLimit,pOffset);
93700 if( pSelect == 0 ) return 0;
93702 /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
93703 pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
93704 if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
93705 pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
93706 if( pInClause == 0 ) goto limit_where_cleanup_1;
93708 pInClause->x.pSelect = pSelect;
93709 pInClause->flags |= EP_xIsSelect;
93710 sqlite3ExprSetHeight(pParse, pInClause);
93711 return pInClause;
93713 /* something went wrong. clean up anything allocated. */
93714 limit_where_cleanup_1:
93715 sqlite3SelectDelete(pParse->db, pSelect);
93716 return 0;
93718 limit_where_cleanup_2:
93719 sqlite3ExprDelete(pParse->db, pWhere);
93720 sqlite3ExprListDelete(pParse->db, pOrderBy);
93721 sqlite3ExprDelete(pParse->db, pLimit);
93722 sqlite3ExprDelete(pParse->db, pOffset);
93723 return 0;
93725 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
93726 /* && !defined(SQLITE_OMIT_SUBQUERY) */
93729 ** Generate code for a DELETE FROM statement.
93731 ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
93732 ** \________/ \________________/
93733 ** pTabList pWhere
93735 SQLITE_PRIVATE void sqlite3DeleteFrom(
93736 Parse *pParse, /* The parser context */
93737 SrcList *pTabList, /* The table from which we should delete things */
93738 Expr *pWhere /* The WHERE clause. May be null */
93740 Vdbe *v; /* The virtual database engine */
93741 Table *pTab; /* The table from which records will be deleted */
93742 const char *zDb; /* Name of database holding pTab */
93743 int i; /* Loop counter */
93744 WhereInfo *pWInfo; /* Information about the WHERE clause */
93745 Index *pIdx; /* For looping over indices of the table */
93746 int iTabCur; /* Cursor number for the table */
93747 int iDataCur; /* VDBE cursor for the canonical data source */
93748 int iIdxCur; /* Cursor number of the first index */
93749 int nIdx; /* Number of indices */
93750 sqlite3 *db; /* Main database structure */
93751 AuthContext sContext; /* Authorization context */
93752 NameContext sNC; /* Name context to resolve expressions in */
93753 int iDb; /* Database number */
93754 int memCnt = -1; /* Memory cell used for change counting */
93755 int rcauth; /* Value returned by authorization callback */
93756 int okOnePass; /* True for one-pass algorithm without the FIFO */
93757 int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
93758 u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
93759 Index *pPk; /* The PRIMARY KEY index on the table */
93760 int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
93761 i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
93762 int iKey; /* Memory cell holding key of row to be deleted */
93763 i16 nKey; /* Number of memory cells in the row key */
93764 int iEphCur = 0; /* Ephemeral table holding all primary key values */
93765 int iRowSet = 0; /* Register for rowset of rows to delete */
93766 int addrBypass = 0; /* Address of jump over the delete logic */
93767 int addrLoop = 0; /* Top of the delete loop */
93768 int addrDelete = 0; /* Jump directly to the delete logic */
93769 int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
93771 #ifndef SQLITE_OMIT_TRIGGER
93772 int isView; /* True if attempting to delete from a view */
93773 Trigger *pTrigger; /* List of table triggers, if required */
93774 #endif
93776 memset(&sContext, 0, sizeof(sContext));
93777 db = pParse->db;
93778 if( pParse->nErr || db->mallocFailed ){
93779 goto delete_from_cleanup;
93781 assert( pTabList->nSrc==1 );
93783 /* Locate the table which we want to delete. This table has to be
93784 ** put in an SrcList structure because some of the subroutines we
93785 ** will be calling are designed to work with multiple tables and expect
93786 ** an SrcList* parameter instead of just a Table* parameter.
93788 pTab = sqlite3SrcListLookup(pParse, pTabList);
93789 if( pTab==0 ) goto delete_from_cleanup;
93791 /* Figure out if we have any triggers and if the table being
93792 ** deleted from is a view
93794 #ifndef SQLITE_OMIT_TRIGGER
93795 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
93796 isView = pTab->pSelect!=0;
93797 #else
93798 # define pTrigger 0
93799 # define isView 0
93800 #endif
93801 #ifdef SQLITE_OMIT_VIEW
93802 # undef isView
93803 # define isView 0
93804 #endif
93806 /* If pTab is really a view, make sure it has been initialized.
93808 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
93809 goto delete_from_cleanup;
93812 if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
93813 goto delete_from_cleanup;
93815 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
93816 assert( iDb<db->nDb );
93817 zDb = db->aDb[iDb].zName;
93818 rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
93819 assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
93820 if( rcauth==SQLITE_DENY ){
93821 goto delete_from_cleanup;
93823 assert(!isView || pTrigger);
93825 /* Assign cursor numbers to the table and all its indices.
93827 assert( pTabList->nSrc==1 );
93828 iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
93829 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
93830 pParse->nTab++;
93833 /* Start the view context
93835 if( isView ){
93836 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
93839 /* Begin generating code.
93841 v = sqlite3GetVdbe(pParse);
93842 if( v==0 ){
93843 goto delete_from_cleanup;
93845 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
93846 sqlite3BeginWriteOperation(pParse, 1, iDb);
93848 /* If we are trying to delete from a view, realize that view into
93849 ** an ephemeral table.
93851 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
93852 if( isView ){
93853 sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
93854 iDataCur = iIdxCur = iTabCur;
93856 #endif
93858 /* Resolve the column names in the WHERE clause.
93860 memset(&sNC, 0, sizeof(sNC));
93861 sNC.pParse = pParse;
93862 sNC.pSrcList = pTabList;
93863 if( sqlite3ResolveExprNames(&sNC, pWhere) ){
93864 goto delete_from_cleanup;
93867 /* Initialize the counter of the number of rows deleted, if
93868 ** we are counting rows.
93870 if( db->flags & SQLITE_CountRows ){
93871 memCnt = ++pParse->nMem;
93872 sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
93875 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
93876 /* Special case: A DELETE without a WHERE clause deletes everything.
93877 ** It is easier just to erase the whole table. Prior to version 3.6.5,
93878 ** this optimization caused the row change count (the value returned by
93879 ** API function sqlite3_count_changes) to be set incorrectly. */
93880 if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
93881 && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
93883 assert( !isView );
93884 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
93885 if( HasRowid(pTab) ){
93886 sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
93887 pTab->zName, P4_STATIC);
93889 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
93890 assert( pIdx->pSchema==pTab->pSchema );
93891 sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
93893 }else
93894 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
93896 if( HasRowid(pTab) ){
93897 /* For a rowid table, initialize the RowSet to an empty set */
93898 pPk = 0;
93899 nPk = 1;
93900 iRowSet = ++pParse->nMem;
93901 sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
93902 }else{
93903 /* For a WITHOUT ROWID table, create an ephemeral table used to
93904 ** hold all primary keys for rows to be deleted. */
93905 pPk = sqlite3PrimaryKeyIndex(pTab);
93906 assert( pPk!=0 );
93907 nPk = pPk->nKeyCol;
93908 iPk = pParse->nMem+1;
93909 pParse->nMem += nPk;
93910 iEphCur = pParse->nTab++;
93911 addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
93912 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
93915 /* Construct a query to find the rowid or primary key for every row
93916 ** to be deleted, based on the WHERE clause.
93918 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
93919 WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK,
93920 iTabCur+1);
93921 if( pWInfo==0 ) goto delete_from_cleanup;
93922 okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
93924 /* Keep track of the number of rows to be deleted */
93925 if( db->flags & SQLITE_CountRows ){
93926 sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
93929 /* Extract the rowid or primary key for the current row */
93930 if( pPk ){
93931 for(i=0; i<nPk; i++){
93932 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
93933 pPk->aiColumn[i], iPk+i);
93935 iKey = iPk;
93936 }else{
93937 iKey = pParse->nMem + 1;
93938 iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
93939 if( iKey>pParse->nMem ) pParse->nMem = iKey;
93942 if( okOnePass ){
93943 /* For ONEPASS, no need to store the rowid/primary-key. There is only
93944 ** one, so just keep it in its register(s) and fall through to the
93945 ** delete code.
93947 nKey = nPk; /* OP_Found will use an unpacked key */
93948 aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
93949 if( aToOpen==0 ){
93950 sqlite3WhereEnd(pWInfo);
93951 goto delete_from_cleanup;
93953 memset(aToOpen, 1, nIdx+1);
93954 aToOpen[nIdx+1] = 0;
93955 if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
93956 if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
93957 if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
93958 addrDelete = sqlite3VdbeAddOp0(v, OP_Goto); /* Jump to DELETE logic */
93959 }else if( pPk ){
93960 /* Construct a composite key for the row to be deleted and remember it */
93961 iKey = ++pParse->nMem;
93962 nKey = 0; /* Zero tells OP_Found to use a composite key */
93963 sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
93964 sqlite3IndexAffinityStr(v, pPk), nPk);
93965 sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
93966 }else{
93967 /* Get the rowid of the row to be deleted and remember it in the RowSet */
93968 nKey = 1; /* OP_Seek always uses a single rowid */
93969 sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
93972 /* End of the WHERE loop */
93973 sqlite3WhereEnd(pWInfo);
93974 if( okOnePass ){
93975 /* Bypass the delete logic below if the WHERE loop found zero rows */
93976 addrBypass = sqlite3VdbeMakeLabel(v);
93977 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBypass);
93978 sqlite3VdbeJumpHere(v, addrDelete);
93981 /* Unless this is a view, open cursors for the table we are
93982 ** deleting from and all its indices. If this is a view, then the
93983 ** only effect this statement has is to fire the INSTEAD OF
93984 ** triggers.
93986 if( !isView ){
93987 testcase( IsVirtual(pTab) );
93988 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iTabCur, aToOpen,
93989 &iDataCur, &iIdxCur);
93990 assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
93991 assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
93994 /* Set up a loop over the rowids/primary-keys that were found in the
93995 ** where-clause loop above.
93997 if( okOnePass ){
93998 /* Just one row. Hence the top-of-loop is a no-op */
93999 assert( nKey==nPk ); /* OP_Found will use an unpacked key */
94000 assert( !IsVirtual(pTab) );
94001 if( aToOpen[iDataCur-iTabCur] ){
94002 assert( pPk!=0 || pTab->pSelect!=0 );
94003 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
94004 VdbeCoverage(v);
94006 }else if( pPk ){
94007 addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
94008 sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
94009 assert( nKey==0 ); /* OP_Found will use a composite key */
94010 }else{
94011 addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
94012 VdbeCoverage(v);
94013 assert( nKey==1 );
94016 /* Delete the row */
94017 #ifndef SQLITE_OMIT_VIRTUALTABLE
94018 if( IsVirtual(pTab) ){
94019 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
94020 sqlite3VtabMakeWritable(pParse, pTab);
94021 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
94022 sqlite3VdbeChangeP5(v, OE_Abort);
94023 sqlite3MayAbort(pParse);
94024 }else
94025 #endif
94027 int count = (pParse->nested==0); /* True to count changes */
94028 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
94029 iKey, nKey, count, OE_Default, okOnePass);
94032 /* End of the loop over all rowids/primary-keys. */
94033 if( okOnePass ){
94034 sqlite3VdbeResolveLabel(v, addrBypass);
94035 }else if( pPk ){
94036 sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
94037 sqlite3VdbeJumpHere(v, addrLoop);
94038 }else{
94039 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrLoop);
94040 sqlite3VdbeJumpHere(v, addrLoop);
94043 /* Close the cursors open on the table and its indexes. */
94044 if( !isView && !IsVirtual(pTab) ){
94045 if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
94046 for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
94047 sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
94050 } /* End non-truncate path */
94052 /* Update the sqlite_sequence table by storing the content of the
94053 ** maximum rowid counter values recorded while inserting into
94054 ** autoincrement tables.
94056 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
94057 sqlite3AutoincrementEnd(pParse);
94060 /* Return the number of rows that were deleted. If this routine is
94061 ** generating code because of a call to sqlite3NestedParse(), do not
94062 ** invoke the callback function.
94064 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
94065 sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
94066 sqlite3VdbeSetNumCols(v, 1);
94067 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
94070 delete_from_cleanup:
94071 sqlite3AuthContextPop(&sContext);
94072 sqlite3SrcListDelete(db, pTabList);
94073 sqlite3ExprDelete(db, pWhere);
94074 sqlite3DbFree(db, aToOpen);
94075 return;
94077 /* Make sure "isView" and other macros defined above are undefined. Otherwise
94078 ** they may interfere with compilation of other functions in this file
94079 ** (or in another file, if this file becomes part of the amalgamation). */
94080 #ifdef isView
94081 #undef isView
94082 #endif
94083 #ifdef pTrigger
94084 #undef pTrigger
94085 #endif
94088 ** This routine generates VDBE code that causes a single row of a
94089 ** single table to be deleted. Both the original table entry and
94090 ** all indices are removed.
94092 ** Preconditions:
94094 ** 1. iDataCur is an open cursor on the btree that is the canonical data
94095 ** store for the table. (This will be either the table itself,
94096 ** in the case of a rowid table, or the PRIMARY KEY index in the case
94097 ** of a WITHOUT ROWID table.)
94099 ** 2. Read/write cursors for all indices of pTab must be open as
94100 ** cursor number iIdxCur+i for the i-th index.
94102 ** 3. The primary key for the row to be deleted must be stored in a
94103 ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
94104 ** that a search record formed from OP_MakeRecord is contained in the
94105 ** single memory location iPk.
94107 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
94108 Parse *pParse, /* Parsing context */
94109 Table *pTab, /* Table containing the row to be deleted */
94110 Trigger *pTrigger, /* List of triggers to (potentially) fire */
94111 int iDataCur, /* Cursor from which column data is extracted */
94112 int iIdxCur, /* First index cursor */
94113 int iPk, /* First memory cell containing the PRIMARY KEY */
94114 i16 nPk, /* Number of PRIMARY KEY memory cells */
94115 u8 count, /* If non-zero, increment the row change counter */
94116 u8 onconf, /* Default ON CONFLICT policy for triggers */
94117 u8 bNoSeek /* iDataCur is already pointing to the row to delete */
94119 Vdbe *v = pParse->pVdbe; /* Vdbe */
94120 int iOld = 0; /* First register in OLD.* array */
94121 int iLabel; /* Label resolved to end of generated code */
94122 u8 opSeek; /* Seek opcode */
94124 /* Vdbe is guaranteed to have been allocated by this stage. */
94125 assert( v );
94126 VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
94127 iDataCur, iIdxCur, iPk, (int)nPk));
94129 /* Seek cursor iCur to the row to delete. If this row no longer exists
94130 ** (this can happen if a trigger program has already deleted it), do
94131 ** not attempt to delete it or fire any DELETE triggers. */
94132 iLabel = sqlite3VdbeMakeLabel(v);
94133 opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
94134 if( !bNoSeek ){
94135 sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
94136 VdbeCoverageIf(v, opSeek==OP_NotExists);
94137 VdbeCoverageIf(v, opSeek==OP_NotFound);
94140 /* If there are any triggers to fire, allocate a range of registers to
94141 ** use for the old.* references in the triggers. */
94142 if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
94143 u32 mask; /* Mask of OLD.* columns in use */
94144 int iCol; /* Iterator used while populating OLD.* */
94145 int addrStart; /* Start of BEFORE trigger programs */
94147 /* TODO: Could use temporary registers here. Also could attempt to
94148 ** avoid copying the contents of the rowid register. */
94149 mask = sqlite3TriggerColmask(
94150 pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
94152 mask |= sqlite3FkOldmask(pParse, pTab);
94153 iOld = pParse->nMem+1;
94154 pParse->nMem += (1 + pTab->nCol);
94156 /* Populate the OLD.* pseudo-table register array. These values will be
94157 ** used by any BEFORE and AFTER triggers that exist. */
94158 sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
94159 for(iCol=0; iCol<pTab->nCol; iCol++){
94160 testcase( mask!=0xffffffff && iCol==31 );
94161 testcase( mask!=0xffffffff && iCol==32 );
94162 if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
94163 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
94167 /* Invoke BEFORE DELETE trigger programs. */
94168 addrStart = sqlite3VdbeCurrentAddr(v);
94169 sqlite3CodeRowTrigger(pParse, pTrigger,
94170 TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
94173 /* If any BEFORE triggers were coded, then seek the cursor to the
94174 ** row to be deleted again. It may be that the BEFORE triggers moved
94175 ** the cursor or of already deleted the row that the cursor was
94176 ** pointing to.
94178 if( addrStart<sqlite3VdbeCurrentAddr(v) ){
94179 sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
94180 VdbeCoverageIf(v, opSeek==OP_NotExists);
94181 VdbeCoverageIf(v, opSeek==OP_NotFound);
94184 /* Do FK processing. This call checks that any FK constraints that
94185 ** refer to this table (i.e. constraints attached to other tables)
94186 ** are not violated by deleting this row. */
94187 sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
94190 /* Delete the index and table entries. Skip this step if pTab is really
94191 ** a view (in which case the only effect of the DELETE statement is to
94192 ** fire the INSTEAD OF triggers). */
94193 if( pTab->pSelect==0 ){
94194 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
94195 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
94196 if( count ){
94197 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
94201 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
94202 ** handle rows (possibly in other tables) that refer via a foreign key
94203 ** to the row just deleted. */
94204 sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
94206 /* Invoke AFTER DELETE trigger programs. */
94207 sqlite3CodeRowTrigger(pParse, pTrigger,
94208 TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
94211 /* Jump here if the row had already been deleted before any BEFORE
94212 ** trigger programs were invoked. Or if a trigger program throws a
94213 ** RAISE(IGNORE) exception. */
94214 sqlite3VdbeResolveLabel(v, iLabel);
94215 VdbeModuleComment((v, "END: GenRowDel()"));
94219 ** This routine generates VDBE code that causes the deletion of all
94220 ** index entries associated with a single row of a single table, pTab
94222 ** Preconditions:
94224 ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
94225 ** btree for the table pTab. (This will be either the table itself
94226 ** for rowid tables or to the primary key index for WITHOUT ROWID
94227 ** tables.)
94229 ** 2. Read/write cursors for all indices of pTab must be open as
94230 ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
94231 ** index is the 0-th index.)
94233 ** 3. The "iDataCur" cursor must be already be positioned on the row
94234 ** that is to be deleted.
94236 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
94237 Parse *pParse, /* Parsing and code generating context */
94238 Table *pTab, /* Table containing the row to be deleted */
94239 int iDataCur, /* Cursor of table holding data. */
94240 int iIdxCur, /* First index cursor */
94241 int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
94243 int i; /* Index loop counter */
94244 int r1 = -1; /* Register holding an index key */
94245 int iPartIdxLabel; /* Jump destination for skipping partial index entries */
94246 Index *pIdx; /* Current index */
94247 Index *pPrior = 0; /* Prior index */
94248 Vdbe *v; /* The prepared statement under construction */
94249 Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
94251 v = pParse->pVdbe;
94252 pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
94253 for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
94254 assert( iIdxCur+i!=iDataCur || pPk==pIdx );
94255 if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
94256 if( pIdx==pPk ) continue;
94257 VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
94258 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
94259 &iPartIdxLabel, pPrior, r1);
94260 sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
94261 pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
94262 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
94263 pPrior = pIdx;
94268 ** Generate code that will assemble an index key and stores it in register
94269 ** regOut. The key with be for index pIdx which is an index on pTab.
94270 ** iCur is the index of a cursor open on the pTab table and pointing to
94271 ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
94272 ** iCur must be the cursor of the PRIMARY KEY index.
94274 ** Return a register number which is the first in a block of
94275 ** registers that holds the elements of the index key. The
94276 ** block of registers has already been deallocated by the time
94277 ** this routine returns.
94279 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
94280 ** to that label if pIdx is a partial index that should be skipped.
94281 ** The label should be resolved using sqlite3ResolvePartIdxLabel().
94282 ** A partial index should be skipped if its WHERE clause evaluates
94283 ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
94284 ** will be set to zero which is an empty label that is ignored by
94285 ** sqlite3ResolvePartIdxLabel().
94287 ** The pPrior and regPrior parameters are used to implement a cache to
94288 ** avoid unnecessary register loads. If pPrior is not NULL, then it is
94289 ** a pointer to a different index for which an index key has just been
94290 ** computed into register regPrior. If the current pIdx index is generating
94291 ** its key into the same sequence of registers and if pPrior and pIdx share
94292 ** a column in common, then the register corresponding to that column already
94293 ** holds the correct value and the loading of that register is skipped.
94294 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
94295 ** on a table with multiple indices, and especially with the ROWID or
94296 ** PRIMARY KEY columns of the index.
94298 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
94299 Parse *pParse, /* Parsing context */
94300 Index *pIdx, /* The index for which to generate a key */
94301 int iDataCur, /* Cursor number from which to take column data */
94302 int regOut, /* Put the new key into this register if not 0 */
94303 int prefixOnly, /* Compute only a unique prefix of the key */
94304 int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
94305 Index *pPrior, /* Previously generated index key */
94306 int regPrior /* Register holding previous generated key */
94308 Vdbe *v = pParse->pVdbe;
94309 int j;
94310 Table *pTab = pIdx->pTable;
94311 int regBase;
94312 int nCol;
94314 if( piPartIdxLabel ){
94315 if( pIdx->pPartIdxWhere ){
94316 *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
94317 pParse->iPartIdxTab = iDataCur;
94318 sqlite3ExprCachePush(pParse);
94319 sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
94320 SQLITE_JUMPIFNULL);
94321 }else{
94322 *piPartIdxLabel = 0;
94325 nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
94326 regBase = sqlite3GetTempRange(pParse, nCol);
94327 if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
94328 for(j=0; j<nCol; j++){
94329 if( pPrior && pPrior->aiColumn[j]==pIdx->aiColumn[j] ) continue;
94330 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pIdx->aiColumn[j],
94331 regBase+j);
94332 /* If the column affinity is REAL but the number is an integer, then it
94333 ** might be stored in the table as an integer (using a compact
94334 ** representation) then converted to REAL by an OP_RealAffinity opcode.
94335 ** But we are getting ready to store this value back into an index, where
94336 ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
94337 ** opcode if it is present */
94338 sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
94340 if( regOut ){
94341 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
94343 sqlite3ReleaseTempRange(pParse, regBase, nCol);
94344 return regBase;
94348 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
94349 ** because it was a partial index, then this routine should be called to
94350 ** resolve that label.
94352 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
94353 if( iLabel ){
94354 sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
94355 sqlite3ExprCachePop(pParse);
94359 /************** End of delete.c **********************************************/
94360 /************** Begin file func.c ********************************************/
94362 ** 2002 February 23
94364 ** The author disclaims copyright to this source code. In place of
94365 ** a legal notice, here is a blessing:
94367 ** May you do good and not evil.
94368 ** May you find forgiveness for yourself and forgive others.
94369 ** May you share freely, never taking more than you give.
94371 *************************************************************************
94372 ** This file contains the C-language implementations for many of the SQL
94373 ** functions of SQLite. (Some function, and in particular the date and
94374 ** time functions, are implemented separately.)
94376 /* #include <stdlib.h> */
94377 /* #include <assert.h> */
94380 ** Return the collating function associated with a function.
94382 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
94383 VdbeOp *pOp = &context->pVdbe->aOp[context->iOp-1];
94384 assert( pOp->opcode==OP_CollSeq );
94385 assert( pOp->p4type==P4_COLLSEQ );
94386 return pOp->p4.pColl;
94390 ** Indicate that the accumulator load should be skipped on this
94391 ** iteration of the aggregate loop.
94393 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
94394 context->skipFlag = 1;
94398 ** Implementation of the non-aggregate min() and max() functions
94400 static void minmaxFunc(
94401 sqlite3_context *context,
94402 int argc,
94403 sqlite3_value **argv
94405 int i;
94406 int mask; /* 0 for min() or 0xffffffff for max() */
94407 int iBest;
94408 CollSeq *pColl;
94410 assert( argc>1 );
94411 mask = sqlite3_user_data(context)==0 ? 0 : -1;
94412 pColl = sqlite3GetFuncCollSeq(context);
94413 assert( pColl );
94414 assert( mask==-1 || mask==0 );
94415 iBest = 0;
94416 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
94417 for(i=1; i<argc; i++){
94418 if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
94419 if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
94420 testcase( mask==0 );
94421 iBest = i;
94424 sqlite3_result_value(context, argv[iBest]);
94428 ** Return the type of the argument.
94430 static void typeofFunc(
94431 sqlite3_context *context,
94432 int NotUsed,
94433 sqlite3_value **argv
94435 const char *z = 0;
94436 UNUSED_PARAMETER(NotUsed);
94437 switch( sqlite3_value_type(argv[0]) ){
94438 case SQLITE_INTEGER: z = "integer"; break;
94439 case SQLITE_TEXT: z = "text"; break;
94440 case SQLITE_FLOAT: z = "real"; break;
94441 case SQLITE_BLOB: z = "blob"; break;
94442 default: z = "null"; break;
94444 sqlite3_result_text(context, z, -1, SQLITE_STATIC);
94449 ** Implementation of the length() function
94451 static void lengthFunc(
94452 sqlite3_context *context,
94453 int argc,
94454 sqlite3_value **argv
94456 int len;
94458 assert( argc==1 );
94459 UNUSED_PARAMETER(argc);
94460 switch( sqlite3_value_type(argv[0]) ){
94461 case SQLITE_BLOB:
94462 case SQLITE_INTEGER:
94463 case SQLITE_FLOAT: {
94464 sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
94465 break;
94467 case SQLITE_TEXT: {
94468 const unsigned char *z = sqlite3_value_text(argv[0]);
94469 if( z==0 ) return;
94470 len = 0;
94471 while( *z ){
94472 len++;
94473 SQLITE_SKIP_UTF8(z);
94475 sqlite3_result_int(context, len);
94476 break;
94478 default: {
94479 sqlite3_result_null(context);
94480 break;
94486 ** Implementation of the abs() function.
94488 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
94489 ** the numeric argument X.
94491 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
94492 assert( argc==1 );
94493 UNUSED_PARAMETER(argc);
94494 switch( sqlite3_value_type(argv[0]) ){
94495 case SQLITE_INTEGER: {
94496 i64 iVal = sqlite3_value_int64(argv[0]);
94497 if( iVal<0 ){
94498 if( iVal==SMALLEST_INT64 ){
94499 /* IMP: R-31676-45509 If X is the integer -9223372036854775808
94500 ** then abs(X) throws an integer overflow error since there is no
94501 ** equivalent positive 64-bit two complement value. */
94502 sqlite3_result_error(context, "integer overflow", -1);
94503 return;
94505 iVal = -iVal;
94507 sqlite3_result_int64(context, iVal);
94508 break;
94510 case SQLITE_NULL: {
94511 /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
94512 sqlite3_result_null(context);
94513 break;
94515 default: {
94516 /* Because sqlite3_value_double() returns 0.0 if the argument is not
94517 ** something that can be converted into a number, we have:
94518 ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
94519 ** cannot be converted to a numeric value.
94521 double rVal = sqlite3_value_double(argv[0]);
94522 if( rVal<0 ) rVal = -rVal;
94523 sqlite3_result_double(context, rVal);
94524 break;
94530 ** Implementation of the instr() function.
94532 ** instr(haystack,needle) finds the first occurrence of needle
94533 ** in haystack and returns the number of previous characters plus 1,
94534 ** or 0 if needle does not occur within haystack.
94536 ** If both haystack and needle are BLOBs, then the result is one more than
94537 ** the number of bytes in haystack prior to the first occurrence of needle,
94538 ** or 0 if needle never occurs in haystack.
94540 static void instrFunc(
94541 sqlite3_context *context,
94542 int argc,
94543 sqlite3_value **argv
94545 const unsigned char *zHaystack;
94546 const unsigned char *zNeedle;
94547 int nHaystack;
94548 int nNeedle;
94549 int typeHaystack, typeNeedle;
94550 int N = 1;
94551 int isText;
94553 UNUSED_PARAMETER(argc);
94554 typeHaystack = sqlite3_value_type(argv[0]);
94555 typeNeedle = sqlite3_value_type(argv[1]);
94556 if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
94557 nHaystack = sqlite3_value_bytes(argv[0]);
94558 nNeedle = sqlite3_value_bytes(argv[1]);
94559 if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
94560 zHaystack = sqlite3_value_blob(argv[0]);
94561 zNeedle = sqlite3_value_blob(argv[1]);
94562 isText = 0;
94563 }else{
94564 zHaystack = sqlite3_value_text(argv[0]);
94565 zNeedle = sqlite3_value_text(argv[1]);
94566 isText = 1;
94568 while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
94569 N++;
94571 nHaystack--;
94572 zHaystack++;
94573 }while( isText && (zHaystack[0]&0xc0)==0x80 );
94575 if( nNeedle>nHaystack ) N = 0;
94576 sqlite3_result_int(context, N);
94580 ** Implementation of the printf() function.
94582 static void printfFunc(
94583 sqlite3_context *context,
94584 int argc,
94585 sqlite3_value **argv
94587 PrintfArguments x;
94588 StrAccum str;
94589 const char *zFormat;
94590 int n;
94592 if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
94593 x.nArg = argc-1;
94594 x.nUsed = 0;
94595 x.apArg = argv+1;
94596 sqlite3StrAccumInit(&str, 0, 0, SQLITE_MAX_LENGTH);
94597 str.db = sqlite3_context_db_handle(context);
94598 sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
94599 n = str.nChar;
94600 sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
94601 SQLITE_DYNAMIC);
94606 ** Implementation of the substr() function.
94608 ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
94609 ** p1 is 1-indexed. So substr(x,1,1) returns the first character
94610 ** of x. If x is text, then we actually count UTF-8 characters.
94611 ** If x is a blob, then we count bytes.
94613 ** If p1 is negative, then we begin abs(p1) from the end of x[].
94615 ** If p2 is negative, return the p2 characters preceding p1.
94617 static void substrFunc(
94618 sqlite3_context *context,
94619 int argc,
94620 sqlite3_value **argv
94622 const unsigned char *z;
94623 const unsigned char *z2;
94624 int len;
94625 int p0type;
94626 i64 p1, p2;
94627 int negP2 = 0;
94629 assert( argc==3 || argc==2 );
94630 if( sqlite3_value_type(argv[1])==SQLITE_NULL
94631 || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
94633 return;
94635 p0type = sqlite3_value_type(argv[0]);
94636 p1 = sqlite3_value_int(argv[1]);
94637 if( p0type==SQLITE_BLOB ){
94638 len = sqlite3_value_bytes(argv[0]);
94639 z = sqlite3_value_blob(argv[0]);
94640 if( z==0 ) return;
94641 assert( len==sqlite3_value_bytes(argv[0]) );
94642 }else{
94643 z = sqlite3_value_text(argv[0]);
94644 if( z==0 ) return;
94645 len = 0;
94646 if( p1<0 ){
94647 for(z2=z; *z2; len++){
94648 SQLITE_SKIP_UTF8(z2);
94652 if( argc==3 ){
94653 p2 = sqlite3_value_int(argv[2]);
94654 if( p2<0 ){
94655 p2 = -p2;
94656 negP2 = 1;
94658 }else{
94659 p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
94661 if( p1<0 ){
94662 p1 += len;
94663 if( p1<0 ){
94664 p2 += p1;
94665 if( p2<0 ) p2 = 0;
94666 p1 = 0;
94668 }else if( p1>0 ){
94669 p1--;
94670 }else if( p2>0 ){
94671 p2--;
94673 if( negP2 ){
94674 p1 -= p2;
94675 if( p1<0 ){
94676 p2 += p1;
94677 p1 = 0;
94680 assert( p1>=0 && p2>=0 );
94681 if( p0type!=SQLITE_BLOB ){
94682 while( *z && p1 ){
94683 SQLITE_SKIP_UTF8(z);
94684 p1--;
94686 for(z2=z; *z2 && p2; p2--){
94687 SQLITE_SKIP_UTF8(z2);
94689 sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
94690 SQLITE_UTF8);
94691 }else{
94692 if( p1+p2>len ){
94693 p2 = len-p1;
94694 if( p2<0 ) p2 = 0;
94696 sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
94701 ** Implementation of the round() function
94703 #ifndef SQLITE_OMIT_FLOATING_POINT
94704 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
94705 int n = 0;
94706 double r;
94707 char *zBuf;
94708 assert( argc==1 || argc==2 );
94709 if( argc==2 ){
94710 if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
94711 n = sqlite3_value_int(argv[1]);
94712 if( n>30 ) n = 30;
94713 if( n<0 ) n = 0;
94715 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
94716 r = sqlite3_value_double(argv[0]);
94717 /* If Y==0 and X will fit in a 64-bit int,
94718 ** handle the rounding directly,
94719 ** otherwise use printf.
94721 if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
94722 r = (double)((sqlite_int64)(r+0.5));
94723 }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
94724 r = -(double)((sqlite_int64)((-r)+0.5));
94725 }else{
94726 zBuf = sqlite3_mprintf("%.*f",n,r);
94727 if( zBuf==0 ){
94728 sqlite3_result_error_nomem(context);
94729 return;
94731 sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
94732 sqlite3_free(zBuf);
94734 sqlite3_result_double(context, r);
94736 #endif
94739 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
94740 ** allocation fails, call sqlite3_result_error_nomem() to notify
94741 ** the database handle that malloc() has failed and return NULL.
94742 ** If nByte is larger than the maximum string or blob length, then
94743 ** raise an SQLITE_TOOBIG exception and return NULL.
94745 static void *contextMalloc(sqlite3_context *context, i64 nByte){
94746 char *z;
94747 sqlite3 *db = sqlite3_context_db_handle(context);
94748 assert( nByte>0 );
94749 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
94750 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
94751 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
94752 sqlite3_result_error_toobig(context);
94753 z = 0;
94754 }else{
94755 z = sqlite3Malloc(nByte);
94756 if( !z ){
94757 sqlite3_result_error_nomem(context);
94760 return z;
94764 ** Implementation of the upper() and lower() SQL functions.
94766 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
94767 char *z1;
94768 const char *z2;
94769 int i, n;
94770 UNUSED_PARAMETER(argc);
94771 z2 = (char*)sqlite3_value_text(argv[0]);
94772 n = sqlite3_value_bytes(argv[0]);
94773 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
94774 assert( z2==(char*)sqlite3_value_text(argv[0]) );
94775 if( z2 ){
94776 z1 = contextMalloc(context, ((i64)n)+1);
94777 if( z1 ){
94778 for(i=0; i<n; i++){
94779 z1[i] = (char)sqlite3Toupper(z2[i]);
94781 sqlite3_result_text(context, z1, n, sqlite3_free);
94785 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
94786 char *z1;
94787 const char *z2;
94788 int i, n;
94789 UNUSED_PARAMETER(argc);
94790 z2 = (char*)sqlite3_value_text(argv[0]);
94791 n = sqlite3_value_bytes(argv[0]);
94792 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
94793 assert( z2==(char*)sqlite3_value_text(argv[0]) );
94794 if( z2 ){
94795 z1 = contextMalloc(context, ((i64)n)+1);
94796 if( z1 ){
94797 for(i=0; i<n; i++){
94798 z1[i] = sqlite3Tolower(z2[i]);
94800 sqlite3_result_text(context, z1, n, sqlite3_free);
94806 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
94807 ** as VDBE code so that unused argument values do not have to be computed.
94808 ** However, we still need some kind of function implementation for this
94809 ** routines in the function table. The noopFunc macro provides this.
94810 ** noopFunc will never be called so it doesn't matter what the implementation
94811 ** is. We might as well use the "version()" function as a substitute.
94813 #define noopFunc versionFunc /* Substitute function - never called */
94816 ** Implementation of random(). Return a random integer.
94818 static void randomFunc(
94819 sqlite3_context *context,
94820 int NotUsed,
94821 sqlite3_value **NotUsed2
94823 sqlite_int64 r;
94824 UNUSED_PARAMETER2(NotUsed, NotUsed2);
94825 sqlite3_randomness(sizeof(r), &r);
94826 if( r<0 ){
94827 /* We need to prevent a random number of 0x8000000000000000
94828 ** (or -9223372036854775808) since when you do abs() of that
94829 ** number of you get the same value back again. To do this
94830 ** in a way that is testable, mask the sign bit off of negative
94831 ** values, resulting in a positive value. Then take the
94832 ** 2s complement of that positive value. The end result can
94833 ** therefore be no less than -9223372036854775807.
94835 r = -(r & LARGEST_INT64);
94837 sqlite3_result_int64(context, r);
94841 ** Implementation of randomblob(N). Return a random blob
94842 ** that is N bytes long.
94844 static void randomBlob(
94845 sqlite3_context *context,
94846 int argc,
94847 sqlite3_value **argv
94849 int n;
94850 unsigned char *p;
94851 assert( argc==1 );
94852 UNUSED_PARAMETER(argc);
94853 n = sqlite3_value_int(argv[0]);
94854 if( n<1 ){
94855 n = 1;
94857 p = contextMalloc(context, n);
94858 if( p ){
94859 sqlite3_randomness(n, p);
94860 sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
94865 ** Implementation of the last_insert_rowid() SQL function. The return
94866 ** value is the same as the sqlite3_last_insert_rowid() API function.
94868 static void last_insert_rowid(
94869 sqlite3_context *context,
94870 int NotUsed,
94871 sqlite3_value **NotUsed2
94873 sqlite3 *db = sqlite3_context_db_handle(context);
94874 UNUSED_PARAMETER2(NotUsed, NotUsed2);
94875 /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
94876 ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
94877 ** function. */
94878 sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
94882 ** Implementation of the changes() SQL function.
94884 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
94885 ** around the sqlite3_changes() C/C++ function and hence follows the same
94886 ** rules for counting changes.
94888 static void changes(
94889 sqlite3_context *context,
94890 int NotUsed,
94891 sqlite3_value **NotUsed2
94893 sqlite3 *db = sqlite3_context_db_handle(context);
94894 UNUSED_PARAMETER2(NotUsed, NotUsed2);
94895 sqlite3_result_int(context, sqlite3_changes(db));
94899 ** Implementation of the total_changes() SQL function. The return value is
94900 ** the same as the sqlite3_total_changes() API function.
94902 static void total_changes(
94903 sqlite3_context *context,
94904 int NotUsed,
94905 sqlite3_value **NotUsed2
94907 sqlite3 *db = sqlite3_context_db_handle(context);
94908 UNUSED_PARAMETER2(NotUsed, NotUsed2);
94909 /* IMP: R-52756-41993 This function is a wrapper around the
94910 ** sqlite3_total_changes() C/C++ interface. */
94911 sqlite3_result_int(context, sqlite3_total_changes(db));
94915 ** A structure defining how to do GLOB-style comparisons.
94917 struct compareInfo {
94918 u8 matchAll;
94919 u8 matchOne;
94920 u8 matchSet;
94921 u8 noCase;
94925 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
94926 ** character is exactly one byte in size. Also, all characters are
94927 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
94928 ** whereas only characters less than 0x80 do in ASCII.
94930 #if defined(SQLITE_EBCDIC)
94931 # define sqlite3Utf8Read(A) (*((*A)++))
94932 # define GlobUpperToLower(A) A = sqlite3UpperToLower[A]
94933 # define GlobUpperToLowerAscii(A) A = sqlite3UpperToLower[A]
94934 #else
94935 # define GlobUpperToLower(A) if( A<=0x7f ){ A = sqlite3UpperToLower[A]; }
94936 # define GlobUpperToLowerAscii(A) A = sqlite3UpperToLower[A]
94937 #endif
94939 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
94940 /* The correct SQL-92 behavior is for the LIKE operator to ignore
94941 ** case. Thus 'a' LIKE 'A' would be true. */
94942 static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
94943 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
94944 ** is case sensitive causing 'a' LIKE 'A' to be false */
94945 static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
94948 ** Compare two UTF-8 strings for equality where the first string can
94949 ** potentially be a "glob" or "like" expression. Return true (1) if they
94950 ** are the same and false (0) if they are different.
94952 ** Globbing rules:
94954 ** '*' Matches any sequence of zero or more characters.
94956 ** '?' Matches exactly one character.
94958 ** [...] Matches one character from the enclosed list of
94959 ** characters.
94961 ** [^...] Matches one character not in the enclosed list.
94963 ** With the [...] and [^...] matching, a ']' character can be included
94964 ** in the list by making it the first character after '[' or '^'. A
94965 ** range of characters can be specified using '-'. Example:
94966 ** "[a-z]" matches any single lower-case letter. To match a '-', make
94967 ** it the last character in the list.
94969 ** Like matching rules:
94971 ** '%' Matches any sequence of zero or more characters
94973 *** '_' Matches any one character
94975 ** Ec Where E is the "esc" character and c is any other
94976 ** character, including '%', '_', and esc, match exactly c.
94978 ** The comments through this routine usually assume glob matching.
94980 ** This routine is usually quick, but can be N**2 in the worst case.
94982 static int patternCompare(
94983 const u8 *zPattern, /* The glob pattern */
94984 const u8 *zString, /* The string to compare against the glob */
94985 const struct compareInfo *pInfo, /* Information about how to do the compare */
94986 u32 esc /* The escape character */
94988 u32 c, c2; /* Next pattern and input string chars */
94989 u32 matchOne = pInfo->matchOne; /* "?" or "_" */
94990 u32 matchAll = pInfo->matchAll; /* "*" or "%" */
94991 u32 matchOther; /* "[" or the escape character */
94992 u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
94993 const u8 *zEscaped = 0; /* One past the last escaped input char */
94995 /* The GLOB operator does not have an ESCAPE clause. And LIKE does not
94996 ** have the matchSet operator. So we either have to look for one or
94997 ** the other, never both. Hence the single variable matchOther is used
94998 ** to store the one we have to look for.
95000 matchOther = esc ? esc : pInfo->matchSet;
95002 while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
95003 if( c==matchAll ){ /* Match "*" */
95004 /* Skip over multiple "*" characters in the pattern. If there
95005 ** are also "?" characters, skip those as well, but consume a
95006 ** single character of the input string for each "?" skipped */
95007 while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
95008 || c == matchOne ){
95009 if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
95010 return 0;
95013 if( c==0 ){
95014 return 1; /* "*" at the end of the pattern matches */
95015 }else if( c==matchOther ){
95016 if( esc ){
95017 c = sqlite3Utf8Read(&zPattern);
95018 if( c==0 ) return 0;
95019 }else{
95020 /* "[...]" immediately follows the "*". We have to do a slow
95021 ** recursive search in this case, but it is an unusual case. */
95022 assert( matchOther<0x80 ); /* '[' is a single-byte character */
95023 while( *zString
95024 && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
95025 SQLITE_SKIP_UTF8(zString);
95027 return *zString!=0;
95031 /* At this point variable c contains the first character of the
95032 ** pattern string past the "*". Search in the input string for the
95033 ** first matching character and recursively contine the match from
95034 ** that point.
95036 ** For a case-insensitive search, set variable cx to be the same as
95037 ** c but in the other case and search the input string for either
95038 ** c or cx.
95040 if( c<=0x80 ){
95041 u32 cx;
95042 if( noCase ){
95043 cx = sqlite3Toupper(c);
95044 c = sqlite3Tolower(c);
95045 }else{
95046 cx = c;
95048 while( (c2 = *(zString++))!=0 ){
95049 if( c2!=c && c2!=cx ) continue;
95050 if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
95052 }else{
95053 while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
95054 if( c2!=c ) continue;
95055 if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
95058 return 0;
95060 if( c==matchOther ){
95061 if( esc ){
95062 c = sqlite3Utf8Read(&zPattern);
95063 if( c==0 ) return 0;
95064 zEscaped = zPattern;
95065 }else{
95066 u32 prior_c = 0;
95067 int seen = 0;
95068 int invert = 0;
95069 c = sqlite3Utf8Read(&zString);
95070 if( c==0 ) return 0;
95071 c2 = sqlite3Utf8Read(&zPattern);
95072 if( c2=='^' ){
95073 invert = 1;
95074 c2 = sqlite3Utf8Read(&zPattern);
95076 if( c2==']' ){
95077 if( c==']' ) seen = 1;
95078 c2 = sqlite3Utf8Read(&zPattern);
95080 while( c2 && c2!=']' ){
95081 if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
95082 c2 = sqlite3Utf8Read(&zPattern);
95083 if( c>=prior_c && c<=c2 ) seen = 1;
95084 prior_c = 0;
95085 }else{
95086 if( c==c2 ){
95087 seen = 1;
95089 prior_c = c2;
95091 c2 = sqlite3Utf8Read(&zPattern);
95093 if( c2==0 || (seen ^ invert)==0 ){
95094 return 0;
95096 continue;
95099 c2 = sqlite3Utf8Read(&zString);
95100 if( c==c2 ) continue;
95101 if( noCase && c<0x80 && c2<0x80 && sqlite3Tolower(c)==sqlite3Tolower(c2) ){
95102 continue;
95104 if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
95105 return 0;
95107 return *zString==0;
95111 ** The sqlite3_strglob() interface.
95113 SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
95114 return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
95118 ** Count the number of times that the LIKE operator (or GLOB which is
95119 ** just a variation of LIKE) gets called. This is used for testing
95120 ** only.
95122 #ifdef SQLITE_TEST
95123 SQLITE_API int sqlite3_like_count = 0;
95124 #endif
95128 ** Implementation of the like() SQL function. This function implements
95129 ** the build-in LIKE operator. The first argument to the function is the
95130 ** pattern and the second argument is the string. So, the SQL statements:
95132 ** A LIKE B
95134 ** is implemented as like(B,A).
95136 ** This same function (with a different compareInfo structure) computes
95137 ** the GLOB operator.
95139 static void likeFunc(
95140 sqlite3_context *context,
95141 int argc,
95142 sqlite3_value **argv
95144 const unsigned char *zA, *zB;
95145 u32 escape = 0;
95146 int nPat;
95147 sqlite3 *db = sqlite3_context_db_handle(context);
95149 zB = sqlite3_value_text(argv[0]);
95150 zA = sqlite3_value_text(argv[1]);
95152 /* Limit the length of the LIKE or GLOB pattern to avoid problems
95153 ** of deep recursion and N*N behavior in patternCompare().
95155 nPat = sqlite3_value_bytes(argv[0]);
95156 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
95157 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
95158 if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
95159 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
95160 return;
95162 assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
95164 if( argc==3 ){
95165 /* The escape character string must consist of a single UTF-8 character.
95166 ** Otherwise, return an error.
95168 const unsigned char *zEsc = sqlite3_value_text(argv[2]);
95169 if( zEsc==0 ) return;
95170 if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
95171 sqlite3_result_error(context,
95172 "ESCAPE expression must be a single character", -1);
95173 return;
95175 escape = sqlite3Utf8Read(&zEsc);
95177 if( zA && zB ){
95178 struct compareInfo *pInfo = sqlite3_user_data(context);
95179 #ifdef SQLITE_TEST
95180 sqlite3_like_count++;
95181 #endif
95183 sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
95188 ** Implementation of the NULLIF(x,y) function. The result is the first
95189 ** argument if the arguments are different. The result is NULL if the
95190 ** arguments are equal to each other.
95192 static void nullifFunc(
95193 sqlite3_context *context,
95194 int NotUsed,
95195 sqlite3_value **argv
95197 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
95198 UNUSED_PARAMETER(NotUsed);
95199 if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
95200 sqlite3_result_value(context, argv[0]);
95205 ** Implementation of the sqlite_version() function. The result is the version
95206 ** of the SQLite library that is running.
95208 static void versionFunc(
95209 sqlite3_context *context,
95210 int NotUsed,
95211 sqlite3_value **NotUsed2
95213 UNUSED_PARAMETER2(NotUsed, NotUsed2);
95214 /* IMP: R-48699-48617 This function is an SQL wrapper around the
95215 ** sqlite3_libversion() C-interface. */
95216 sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
95220 ** Implementation of the sqlite_source_id() function. The result is a string
95221 ** that identifies the particular version of the source code used to build
95222 ** SQLite.
95224 static void sourceidFunc(
95225 sqlite3_context *context,
95226 int NotUsed,
95227 sqlite3_value **NotUsed2
95229 UNUSED_PARAMETER2(NotUsed, NotUsed2);
95230 /* IMP: R-24470-31136 This function is an SQL wrapper around the
95231 ** sqlite3_sourceid() C interface. */
95232 sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
95236 ** Implementation of the sqlite_log() function. This is a wrapper around
95237 ** sqlite3_log(). The return value is NULL. The function exists purely for
95238 ** its side-effects.
95240 static void errlogFunc(
95241 sqlite3_context *context,
95242 int argc,
95243 sqlite3_value **argv
95245 UNUSED_PARAMETER(argc);
95246 UNUSED_PARAMETER(context);
95247 sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
95251 ** Implementation of the sqlite_compileoption_used() function.
95252 ** The result is an integer that identifies if the compiler option
95253 ** was used to build SQLite.
95255 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
95256 static void compileoptionusedFunc(
95257 sqlite3_context *context,
95258 int argc,
95259 sqlite3_value **argv
95261 const char *zOptName;
95262 assert( argc==1 );
95263 UNUSED_PARAMETER(argc);
95264 /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
95265 ** function is a wrapper around the sqlite3_compileoption_used() C/C++
95266 ** function.
95268 if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
95269 sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
95272 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
95275 ** Implementation of the sqlite_compileoption_get() function.
95276 ** The result is a string that identifies the compiler options
95277 ** used to build SQLite.
95279 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
95280 static void compileoptiongetFunc(
95281 sqlite3_context *context,
95282 int argc,
95283 sqlite3_value **argv
95285 int n;
95286 assert( argc==1 );
95287 UNUSED_PARAMETER(argc);
95288 /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
95289 ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
95291 n = sqlite3_value_int(argv[0]);
95292 sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
95294 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
95296 /* Array for converting from half-bytes (nybbles) into ASCII hex
95297 ** digits. */
95298 static const char hexdigits[] = {
95299 '0', '1', '2', '3', '4', '5', '6', '7',
95300 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
95304 ** Implementation of the QUOTE() function. This function takes a single
95305 ** argument. If the argument is numeric, the return value is the same as
95306 ** the argument. If the argument is NULL, the return value is the string
95307 ** "NULL". Otherwise, the argument is enclosed in single quotes with
95308 ** single-quote escapes.
95310 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
95311 assert( argc==1 );
95312 UNUSED_PARAMETER(argc);
95313 switch( sqlite3_value_type(argv[0]) ){
95314 case SQLITE_FLOAT: {
95315 double r1, r2;
95316 char zBuf[50];
95317 r1 = sqlite3_value_double(argv[0]);
95318 sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
95319 sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
95320 if( r1!=r2 ){
95321 sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
95323 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
95324 break;
95326 case SQLITE_INTEGER: {
95327 sqlite3_result_value(context, argv[0]);
95328 break;
95330 case SQLITE_BLOB: {
95331 char *zText = 0;
95332 char const *zBlob = sqlite3_value_blob(argv[0]);
95333 int nBlob = sqlite3_value_bytes(argv[0]);
95334 assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
95335 zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
95336 if( zText ){
95337 int i;
95338 for(i=0; i<nBlob; i++){
95339 zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
95340 zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
95342 zText[(nBlob*2)+2] = '\'';
95343 zText[(nBlob*2)+3] = '\0';
95344 zText[0] = 'X';
95345 zText[1] = '\'';
95346 sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
95347 sqlite3_free(zText);
95349 break;
95351 case SQLITE_TEXT: {
95352 int i,j;
95353 u64 n;
95354 const unsigned char *zArg = sqlite3_value_text(argv[0]);
95355 char *z;
95357 if( zArg==0 ) return;
95358 for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
95359 z = contextMalloc(context, ((i64)i)+((i64)n)+3);
95360 if( z ){
95361 z[0] = '\'';
95362 for(i=0, j=1; zArg[i]; i++){
95363 z[j++] = zArg[i];
95364 if( zArg[i]=='\'' ){
95365 z[j++] = '\'';
95368 z[j++] = '\'';
95369 z[j] = 0;
95370 sqlite3_result_text(context, z, j, sqlite3_free);
95372 break;
95374 default: {
95375 assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
95376 sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
95377 break;
95383 ** The unicode() function. Return the integer unicode code-point value
95384 ** for the first character of the input string.
95386 static void unicodeFunc(
95387 sqlite3_context *context,
95388 int argc,
95389 sqlite3_value **argv
95391 const unsigned char *z = sqlite3_value_text(argv[0]);
95392 (void)argc;
95393 if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
95397 ** The char() function takes zero or more arguments, each of which is
95398 ** an integer. It constructs a string where each character of the string
95399 ** is the unicode character for the corresponding integer argument.
95401 static void charFunc(
95402 sqlite3_context *context,
95403 int argc,
95404 sqlite3_value **argv
95406 unsigned char *z, *zOut;
95407 int i;
95408 zOut = z = sqlite3_malloc( argc*4+1 );
95409 if( z==0 ){
95410 sqlite3_result_error_nomem(context);
95411 return;
95413 for(i=0; i<argc; i++){
95414 sqlite3_int64 x;
95415 unsigned c;
95416 x = sqlite3_value_int64(argv[i]);
95417 if( x<0 || x>0x10ffff ) x = 0xfffd;
95418 c = (unsigned)(x & 0x1fffff);
95419 if( c<0x00080 ){
95420 *zOut++ = (u8)(c&0xFF);
95421 }else if( c<0x00800 ){
95422 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
95423 *zOut++ = 0x80 + (u8)(c & 0x3F);
95424 }else if( c<0x10000 ){
95425 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
95426 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
95427 *zOut++ = 0x80 + (u8)(c & 0x3F);
95428 }else{
95429 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
95430 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
95431 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
95432 *zOut++ = 0x80 + (u8)(c & 0x3F);
95435 sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
95439 ** The hex() function. Interpret the argument as a blob. Return
95440 ** a hexadecimal rendering as text.
95442 static void hexFunc(
95443 sqlite3_context *context,
95444 int argc,
95445 sqlite3_value **argv
95447 int i, n;
95448 const unsigned char *pBlob;
95449 char *zHex, *z;
95450 assert( argc==1 );
95451 UNUSED_PARAMETER(argc);
95452 pBlob = sqlite3_value_blob(argv[0]);
95453 n = sqlite3_value_bytes(argv[0]);
95454 assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
95455 z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
95456 if( zHex ){
95457 for(i=0; i<n; i++, pBlob++){
95458 unsigned char c = *pBlob;
95459 *(z++) = hexdigits[(c>>4)&0xf];
95460 *(z++) = hexdigits[c&0xf];
95462 *z = 0;
95463 sqlite3_result_text(context, zHex, n*2, sqlite3_free);
95468 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
95470 static void zeroblobFunc(
95471 sqlite3_context *context,
95472 int argc,
95473 sqlite3_value **argv
95475 i64 n;
95476 sqlite3 *db = sqlite3_context_db_handle(context);
95477 assert( argc==1 );
95478 UNUSED_PARAMETER(argc);
95479 n = sqlite3_value_int64(argv[0]);
95480 testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
95481 testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
95482 if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
95483 sqlite3_result_error_toobig(context);
95484 }else{
95485 sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
95490 ** The replace() function. Three arguments are all strings: call
95491 ** them A, B, and C. The result is also a string which is derived
95492 ** from A by replacing every occurrence of B with C. The match
95493 ** must be exact. Collating sequences are not used.
95495 static void replaceFunc(
95496 sqlite3_context *context,
95497 int argc,
95498 sqlite3_value **argv
95500 const unsigned char *zStr; /* The input string A */
95501 const unsigned char *zPattern; /* The pattern string B */
95502 const unsigned char *zRep; /* The replacement string C */
95503 unsigned char *zOut; /* The output */
95504 int nStr; /* Size of zStr */
95505 int nPattern; /* Size of zPattern */
95506 int nRep; /* Size of zRep */
95507 i64 nOut; /* Maximum size of zOut */
95508 int loopLimit; /* Last zStr[] that might match zPattern[] */
95509 int i, j; /* Loop counters */
95511 assert( argc==3 );
95512 UNUSED_PARAMETER(argc);
95513 zStr = sqlite3_value_text(argv[0]);
95514 if( zStr==0 ) return;
95515 nStr = sqlite3_value_bytes(argv[0]);
95516 assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
95517 zPattern = sqlite3_value_text(argv[1]);
95518 if( zPattern==0 ){
95519 assert( sqlite3_value_type(argv[1])==SQLITE_NULL
95520 || sqlite3_context_db_handle(context)->mallocFailed );
95521 return;
95523 if( zPattern[0]==0 ){
95524 assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
95525 sqlite3_result_value(context, argv[0]);
95526 return;
95528 nPattern = sqlite3_value_bytes(argv[1]);
95529 assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
95530 zRep = sqlite3_value_text(argv[2]);
95531 if( zRep==0 ) return;
95532 nRep = sqlite3_value_bytes(argv[2]);
95533 assert( zRep==sqlite3_value_text(argv[2]) );
95534 nOut = nStr + 1;
95535 assert( nOut<SQLITE_MAX_LENGTH );
95536 zOut = contextMalloc(context, (i64)nOut);
95537 if( zOut==0 ){
95538 return;
95540 loopLimit = nStr - nPattern;
95541 for(i=j=0; i<=loopLimit; i++){
95542 if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
95543 zOut[j++] = zStr[i];
95544 }else{
95545 u8 *zOld;
95546 sqlite3 *db = sqlite3_context_db_handle(context);
95547 nOut += nRep - nPattern;
95548 testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
95549 testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
95550 if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
95551 sqlite3_result_error_toobig(context);
95552 sqlite3_free(zOut);
95553 return;
95555 zOld = zOut;
95556 zOut = sqlite3_realloc(zOut, (int)nOut);
95557 if( zOut==0 ){
95558 sqlite3_result_error_nomem(context);
95559 sqlite3_free(zOld);
95560 return;
95562 memcpy(&zOut[j], zRep, nRep);
95563 j += nRep;
95564 i += nPattern-1;
95567 assert( j+nStr-i+1==nOut );
95568 memcpy(&zOut[j], &zStr[i], nStr-i);
95569 j += nStr - i;
95570 assert( j<=nOut );
95571 zOut[j] = 0;
95572 sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
95576 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
95577 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
95579 static void trimFunc(
95580 sqlite3_context *context,
95581 int argc,
95582 sqlite3_value **argv
95584 const unsigned char *zIn; /* Input string */
95585 const unsigned char *zCharSet; /* Set of characters to trim */
95586 int nIn; /* Number of bytes in input */
95587 int flags; /* 1: trimleft 2: trimright 3: trim */
95588 int i; /* Loop counter */
95589 unsigned char *aLen = 0; /* Length of each character in zCharSet */
95590 unsigned char **azChar = 0; /* Individual characters in zCharSet */
95591 int nChar; /* Number of characters in zCharSet */
95593 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
95594 return;
95596 zIn = sqlite3_value_text(argv[0]);
95597 if( zIn==0 ) return;
95598 nIn = sqlite3_value_bytes(argv[0]);
95599 assert( zIn==sqlite3_value_text(argv[0]) );
95600 if( argc==1 ){
95601 static const unsigned char lenOne[] = { 1 };
95602 static unsigned char * const azOne[] = { (u8*)" " };
95603 nChar = 1;
95604 aLen = (u8*)lenOne;
95605 azChar = (unsigned char **)azOne;
95606 zCharSet = 0;
95607 }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
95608 return;
95609 }else{
95610 const unsigned char *z;
95611 for(z=zCharSet, nChar=0; *z; nChar++){
95612 SQLITE_SKIP_UTF8(z);
95614 if( nChar>0 ){
95615 azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
95616 if( azChar==0 ){
95617 return;
95619 aLen = (unsigned char*)&azChar[nChar];
95620 for(z=zCharSet, nChar=0; *z; nChar++){
95621 azChar[nChar] = (unsigned char *)z;
95622 SQLITE_SKIP_UTF8(z);
95623 aLen[nChar] = (u8)(z - azChar[nChar]);
95627 if( nChar>0 ){
95628 flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
95629 if( flags & 1 ){
95630 while( nIn>0 ){
95631 int len = 0;
95632 for(i=0; i<nChar; i++){
95633 len = aLen[i];
95634 if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
95636 if( i>=nChar ) break;
95637 zIn += len;
95638 nIn -= len;
95641 if( flags & 2 ){
95642 while( nIn>0 ){
95643 int len = 0;
95644 for(i=0; i<nChar; i++){
95645 len = aLen[i];
95646 if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
95648 if( i>=nChar ) break;
95649 nIn -= len;
95652 if( zCharSet ){
95653 sqlite3_free(azChar);
95656 sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
95660 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
95661 ** is only available if the SQLITE_SOUNDEX compile-time option is used
95662 ** when SQLite is built.
95664 #ifdef SQLITE_SOUNDEX
95666 ** Compute the soundex encoding of a word.
95668 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
95669 ** soundex encoding of the string X.
95671 static void soundexFunc(
95672 sqlite3_context *context,
95673 int argc,
95674 sqlite3_value **argv
95676 char zResult[8];
95677 const u8 *zIn;
95678 int i, j;
95679 static const unsigned char iCode[] = {
95680 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
95681 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
95682 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
95683 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
95684 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
95685 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
95686 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
95687 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
95689 assert( argc==1 );
95690 zIn = (u8*)sqlite3_value_text(argv[0]);
95691 if( zIn==0 ) zIn = (u8*)"";
95692 for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
95693 if( zIn[i] ){
95694 u8 prevcode = iCode[zIn[i]&0x7f];
95695 zResult[0] = sqlite3Toupper(zIn[i]);
95696 for(j=1; j<4 && zIn[i]; i++){
95697 int code = iCode[zIn[i]&0x7f];
95698 if( code>0 ){
95699 if( code!=prevcode ){
95700 prevcode = code;
95701 zResult[j++] = code + '0';
95703 }else{
95704 prevcode = 0;
95707 while( j<4 ){
95708 zResult[j++] = '0';
95710 zResult[j] = 0;
95711 sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
95712 }else{
95713 /* IMP: R-64894-50321 The string "?000" is returned if the argument
95714 ** is NULL or contains no ASCII alphabetic characters. */
95715 sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
95718 #endif /* SQLITE_SOUNDEX */
95720 #ifndef SQLITE_OMIT_LOAD_EXTENSION
95722 ** A function that loads a shared-library extension then returns NULL.
95724 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
95725 const char *zFile = (const char *)sqlite3_value_text(argv[0]);
95726 const char *zProc;
95727 sqlite3 *db = sqlite3_context_db_handle(context);
95728 char *zErrMsg = 0;
95730 if( argc==2 ){
95731 zProc = (const char *)sqlite3_value_text(argv[1]);
95732 }else{
95733 zProc = 0;
95735 if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
95736 sqlite3_result_error(context, zErrMsg, -1);
95737 sqlite3_free(zErrMsg);
95740 #endif
95744 ** An instance of the following structure holds the context of a
95745 ** sum() or avg() aggregate computation.
95747 typedef struct SumCtx SumCtx;
95748 struct SumCtx {
95749 double rSum; /* Floating point sum */
95750 i64 iSum; /* Integer sum */
95751 i64 cnt; /* Number of elements summed */
95752 u8 overflow; /* True if integer overflow seen */
95753 u8 approx; /* True if non-integer value was input to the sum */
95757 ** Routines used to compute the sum, average, and total.
95759 ** The SUM() function follows the (broken) SQL standard which means
95760 ** that it returns NULL if it sums over no inputs. TOTAL returns
95761 ** 0.0 in that case. In addition, TOTAL always returns a float where
95762 ** SUM might return an integer if it never encounters a floating point
95763 ** value. TOTAL never fails, but SUM might through an exception if
95764 ** it overflows an integer.
95766 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
95767 SumCtx *p;
95768 int type;
95769 assert( argc==1 );
95770 UNUSED_PARAMETER(argc);
95771 p = sqlite3_aggregate_context(context, sizeof(*p));
95772 type = sqlite3_value_numeric_type(argv[0]);
95773 if( p && type!=SQLITE_NULL ){
95774 p->cnt++;
95775 if( type==SQLITE_INTEGER ){
95776 i64 v = sqlite3_value_int64(argv[0]);
95777 p->rSum += v;
95778 if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
95779 p->overflow = 1;
95781 }else{
95782 p->rSum += sqlite3_value_double(argv[0]);
95783 p->approx = 1;
95787 static void sumFinalize(sqlite3_context *context){
95788 SumCtx *p;
95789 p = sqlite3_aggregate_context(context, 0);
95790 if( p && p->cnt>0 ){
95791 if( p->overflow ){
95792 sqlite3_result_error(context,"integer overflow",-1);
95793 }else if( p->approx ){
95794 sqlite3_result_double(context, p->rSum);
95795 }else{
95796 sqlite3_result_int64(context, p->iSum);
95800 static void avgFinalize(sqlite3_context *context){
95801 SumCtx *p;
95802 p = sqlite3_aggregate_context(context, 0);
95803 if( p && p->cnt>0 ){
95804 sqlite3_result_double(context, p->rSum/(double)p->cnt);
95807 static void totalFinalize(sqlite3_context *context){
95808 SumCtx *p;
95809 p = sqlite3_aggregate_context(context, 0);
95810 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
95811 sqlite3_result_double(context, p ? p->rSum : (double)0);
95815 ** The following structure keeps track of state information for the
95816 ** count() aggregate function.
95818 typedef struct CountCtx CountCtx;
95819 struct CountCtx {
95820 i64 n;
95824 ** Routines to implement the count() aggregate function.
95826 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
95827 CountCtx *p;
95828 p = sqlite3_aggregate_context(context, sizeof(*p));
95829 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
95830 p->n++;
95833 #ifndef SQLITE_OMIT_DEPRECATED
95834 /* The sqlite3_aggregate_count() function is deprecated. But just to make
95835 ** sure it still operates correctly, verify that its count agrees with our
95836 ** internal count when using count(*) and when the total count can be
95837 ** expressed as a 32-bit integer. */
95838 assert( argc==1 || p==0 || p->n>0x7fffffff
95839 || p->n==sqlite3_aggregate_count(context) );
95840 #endif
95842 static void countFinalize(sqlite3_context *context){
95843 CountCtx *p;
95844 p = sqlite3_aggregate_context(context, 0);
95845 sqlite3_result_int64(context, p ? p->n : 0);
95849 ** Routines to implement min() and max() aggregate functions.
95851 static void minmaxStep(
95852 sqlite3_context *context,
95853 int NotUsed,
95854 sqlite3_value **argv
95856 Mem *pArg = (Mem *)argv[0];
95857 Mem *pBest;
95858 UNUSED_PARAMETER(NotUsed);
95860 pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
95861 if( !pBest ) return;
95863 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
95864 if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
95865 }else if( pBest->flags ){
95866 int max;
95867 int cmp;
95868 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
95869 /* This step function is used for both the min() and max() aggregates,
95870 ** the only difference between the two being that the sense of the
95871 ** comparison is inverted. For the max() aggregate, the
95872 ** sqlite3_user_data() function returns (void *)-1. For min() it
95873 ** returns (void *)db, where db is the sqlite3* database pointer.
95874 ** Therefore the next statement sets variable 'max' to 1 for the max()
95875 ** aggregate, or 0 for min().
95877 max = sqlite3_user_data(context)!=0;
95878 cmp = sqlite3MemCompare(pBest, pArg, pColl);
95879 if( (max && cmp<0) || (!max && cmp>0) ){
95880 sqlite3VdbeMemCopy(pBest, pArg);
95881 }else{
95882 sqlite3SkipAccumulatorLoad(context);
95884 }else{
95885 pBest->db = sqlite3_context_db_handle(context);
95886 sqlite3VdbeMemCopy(pBest, pArg);
95889 static void minMaxFinalize(sqlite3_context *context){
95890 sqlite3_value *pRes;
95891 pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
95892 if( pRes ){
95893 if( pRes->flags ){
95894 sqlite3_result_value(context, pRes);
95896 sqlite3VdbeMemRelease(pRes);
95901 ** group_concat(EXPR, ?SEPARATOR?)
95903 static void groupConcatStep(
95904 sqlite3_context *context,
95905 int argc,
95906 sqlite3_value **argv
95908 const char *zVal;
95909 StrAccum *pAccum;
95910 const char *zSep;
95911 int nVal, nSep;
95912 assert( argc==1 || argc==2 );
95913 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
95914 pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
95916 if( pAccum ){
95917 sqlite3 *db = sqlite3_context_db_handle(context);
95918 int firstTerm = pAccum->useMalloc==0;
95919 pAccum->useMalloc = 2;
95920 pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
95921 if( !firstTerm ){
95922 if( argc==2 ){
95923 zSep = (char*)sqlite3_value_text(argv[1]);
95924 nSep = sqlite3_value_bytes(argv[1]);
95925 }else{
95926 zSep = ",";
95927 nSep = 1;
95929 if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
95931 zVal = (char*)sqlite3_value_text(argv[0]);
95932 nVal = sqlite3_value_bytes(argv[0]);
95933 if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
95936 static void groupConcatFinalize(sqlite3_context *context){
95937 StrAccum *pAccum;
95938 pAccum = sqlite3_aggregate_context(context, 0);
95939 if( pAccum ){
95940 if( pAccum->accError==STRACCUM_TOOBIG ){
95941 sqlite3_result_error_toobig(context);
95942 }else if( pAccum->accError==STRACCUM_NOMEM ){
95943 sqlite3_result_error_nomem(context);
95944 }else{
95945 sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
95946 sqlite3_free);
95952 ** This routine does per-connection function registration. Most
95953 ** of the built-in functions above are part of the global function set.
95954 ** This routine only deals with those that are not global.
95956 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
95957 int rc = sqlite3_overload_function(db, "MATCH", 2);
95958 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
95959 if( rc==SQLITE_NOMEM ){
95960 db->mallocFailed = 1;
95965 ** Set the LIKEOPT flag on the 2-argument function with the given name.
95967 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
95968 FuncDef *pDef;
95969 pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
95970 2, SQLITE_UTF8, 0);
95971 if( ALWAYS(pDef) ){
95972 pDef->funcFlags |= flagVal;
95977 ** Register the built-in LIKE and GLOB functions. The caseSensitive
95978 ** parameter determines whether or not the LIKE operator is case
95979 ** sensitive. GLOB is always case sensitive.
95981 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
95982 struct compareInfo *pInfo;
95983 if( caseSensitive ){
95984 pInfo = (struct compareInfo*)&likeInfoAlt;
95985 }else{
95986 pInfo = (struct compareInfo*)&likeInfoNorm;
95988 sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
95989 sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
95990 sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
95991 (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
95992 setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
95993 setLikeOptFlag(db, "like",
95994 caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
95998 ** pExpr points to an expression which implements a function. If
95999 ** it is appropriate to apply the LIKE optimization to that function
96000 ** then set aWc[0] through aWc[2] to the wildcard characters and
96001 ** return TRUE. If the function is not a LIKE-style function then
96002 ** return FALSE.
96004 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
96005 FuncDef *pDef;
96006 if( pExpr->op!=TK_FUNCTION
96007 || !pExpr->x.pList
96008 || pExpr->x.pList->nExpr!=2
96010 return 0;
96012 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
96013 pDef = sqlite3FindFunction(db, pExpr->u.zToken,
96014 sqlite3Strlen30(pExpr->u.zToken),
96015 2, SQLITE_UTF8, 0);
96016 if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
96017 return 0;
96020 /* The memcpy() statement assumes that the wildcard characters are
96021 ** the first three statements in the compareInfo structure. The
96022 ** asserts() that follow verify that assumption
96024 memcpy(aWc, pDef->pUserData, 3);
96025 assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
96026 assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
96027 assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
96028 *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
96029 return 1;
96033 ** All of the FuncDef structures in the aBuiltinFunc[] array above
96034 ** to the global function hash table. This occurs at start-time (as
96035 ** a consequence of calling sqlite3_initialize()).
96037 ** After this routine runs
96039 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
96041 ** The following array holds FuncDef structures for all of the functions
96042 ** defined in this file.
96044 ** The array cannot be constant since changes are made to the
96045 ** FuncDef.pHash elements at start-time. The elements of this array
96046 ** are read-only after initialization is complete.
96048 static SQLITE_WSD FuncDef aBuiltinFunc[] = {
96049 FUNCTION(ltrim, 1, 1, 0, trimFunc ),
96050 FUNCTION(ltrim, 2, 1, 0, trimFunc ),
96051 FUNCTION(rtrim, 1, 2, 0, trimFunc ),
96052 FUNCTION(rtrim, 2, 2, 0, trimFunc ),
96053 FUNCTION(trim, 1, 3, 0, trimFunc ),
96054 FUNCTION(trim, 2, 3, 0, trimFunc ),
96055 FUNCTION(min, -1, 0, 1, minmaxFunc ),
96056 FUNCTION(min, 0, 0, 1, 0 ),
96057 AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize,
96058 SQLITE_FUNC_MINMAX ),
96059 FUNCTION(max, -1, 1, 1, minmaxFunc ),
96060 FUNCTION(max, 0, 1, 1, 0 ),
96061 AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize,
96062 SQLITE_FUNC_MINMAX ),
96063 FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
96064 FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
96065 FUNCTION(instr, 2, 0, 0, instrFunc ),
96066 FUNCTION(substr, 2, 0, 0, substrFunc ),
96067 FUNCTION(substr, 3, 0, 0, substrFunc ),
96068 FUNCTION(printf, -1, 0, 0, printfFunc ),
96069 FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
96070 FUNCTION(char, -1, 0, 0, charFunc ),
96071 FUNCTION(abs, 1, 0, 0, absFunc ),
96072 #ifndef SQLITE_OMIT_FLOATING_POINT
96073 FUNCTION(round, 1, 0, 0, roundFunc ),
96074 FUNCTION(round, 2, 0, 0, roundFunc ),
96075 #endif
96076 FUNCTION(upper, 1, 0, 0, upperFunc ),
96077 FUNCTION(lower, 1, 0, 0, lowerFunc ),
96078 FUNCTION(coalesce, 1, 0, 0, 0 ),
96079 FUNCTION(coalesce, 0, 0, 0, 0 ),
96080 FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
96081 FUNCTION(hex, 1, 0, 0, hexFunc ),
96082 FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
96083 FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
96084 FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
96085 FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
96086 VFUNCTION(random, 0, 0, 0, randomFunc ),
96087 VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
96088 FUNCTION(nullif, 2, 0, 1, nullifFunc ),
96089 FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
96090 FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
96091 FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
96092 #if SQLITE_USER_AUTHENTICATION
96093 FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
96094 #endif
96095 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
96096 FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
96097 FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
96098 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
96099 FUNCTION(quote, 1, 0, 0, quoteFunc ),
96100 VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
96101 VFUNCTION(changes, 0, 0, 0, changes ),
96102 VFUNCTION(total_changes, 0, 0, 0, total_changes ),
96103 FUNCTION(replace, 3, 0, 0, replaceFunc ),
96104 FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
96105 #ifdef SQLITE_SOUNDEX
96106 FUNCTION(soundex, 1, 0, 0, soundexFunc ),
96107 #endif
96108 #ifndef SQLITE_OMIT_LOAD_EXTENSION
96109 FUNCTION(load_extension, 1, 0, 0, loadExt ),
96110 FUNCTION(load_extension, 2, 0, 0, loadExt ),
96111 #endif
96112 AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
96113 AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
96114 AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
96115 AGGREGATE2(count, 0, 0, 0, countStep, countFinalize,
96116 SQLITE_FUNC_COUNT ),
96117 AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
96118 AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
96119 AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
96121 LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
96122 #ifdef SQLITE_CASE_SENSITIVE_LIKE
96123 LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
96124 LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
96125 #else
96126 LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
96127 LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
96128 #endif
96131 int i;
96132 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
96133 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
96135 for(i=0; i<ArraySize(aBuiltinFunc); i++){
96136 sqlite3FuncDefInsert(pHash, &aFunc[i]);
96138 sqlite3RegisterDateTimeFunctions();
96139 #ifndef SQLITE_OMIT_ALTERTABLE
96140 sqlite3AlterFunctions();
96141 #endif
96142 #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
96143 sqlite3AnalyzeFunctions();
96144 #endif
96147 /************** End of func.c ************************************************/
96148 /************** Begin file fkey.c ********************************************/
96151 ** The author disclaims copyright to this source code. In place of
96152 ** a legal notice, here is a blessing:
96154 ** May you do good and not evil.
96155 ** May you find forgiveness for yourself and forgive others.
96156 ** May you share freely, never taking more than you give.
96158 *************************************************************************
96159 ** This file contains code used by the compiler to add foreign key
96160 ** support to compiled SQL statements.
96163 #ifndef SQLITE_OMIT_FOREIGN_KEY
96164 #ifndef SQLITE_OMIT_TRIGGER
96167 ** Deferred and Immediate FKs
96168 ** --------------------------
96170 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
96171 ** If an immediate foreign key constraint is violated,
96172 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
96173 ** statement transaction rolled back. If a
96174 ** deferred foreign key constraint is violated, no action is taken
96175 ** immediately. However if the application attempts to commit the
96176 ** transaction before fixing the constraint violation, the attempt fails.
96178 ** Deferred constraints are implemented using a simple counter associated
96179 ** with the database handle. The counter is set to zero each time a
96180 ** database transaction is opened. Each time a statement is executed
96181 ** that causes a foreign key violation, the counter is incremented. Each
96182 ** time a statement is executed that removes an existing violation from
96183 ** the database, the counter is decremented. When the transaction is
96184 ** committed, the commit fails if the current value of the counter is
96185 ** greater than zero. This scheme has two big drawbacks:
96187 ** * When a commit fails due to a deferred foreign key constraint,
96188 ** there is no way to tell which foreign constraint is not satisfied,
96189 ** or which row it is not satisfied for.
96191 ** * If the database contains foreign key violations when the
96192 ** transaction is opened, this may cause the mechanism to malfunction.
96194 ** Despite these problems, this approach is adopted as it seems simpler
96195 ** than the alternatives.
96197 ** INSERT operations:
96199 ** I.1) For each FK for which the table is the child table, search
96200 ** the parent table for a match. If none is found increment the
96201 ** constraint counter.
96203 ** I.2) For each FK for which the table is the parent table,
96204 ** search the child table for rows that correspond to the new
96205 ** row in the parent table. Decrement the counter for each row
96206 ** found (as the constraint is now satisfied).
96208 ** DELETE operations:
96210 ** D.1) For each FK for which the table is the child table,
96211 ** search the parent table for a row that corresponds to the
96212 ** deleted row in the child table. If such a row is not found,
96213 ** decrement the counter.
96215 ** D.2) For each FK for which the table is the parent table, search
96216 ** the child table for rows that correspond to the deleted row
96217 ** in the parent table. For each found increment the counter.
96219 ** UPDATE operations:
96221 ** An UPDATE command requires that all 4 steps above are taken, but only
96222 ** for FK constraints for which the affected columns are actually
96223 ** modified (values must be compared at runtime).
96225 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
96226 ** This simplifies the implementation a bit.
96228 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
96229 ** resolution is considered to delete rows before the new row is inserted.
96230 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
96231 ** is thrown, even if the FK constraint would be satisfied after the new
96232 ** row is inserted.
96234 ** Immediate constraints are usually handled similarly. The only difference
96235 ** is that the counter used is stored as part of each individual statement
96236 ** object (struct Vdbe). If, after the statement has run, its immediate
96237 ** constraint counter is greater than zero,
96238 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
96239 ** and the statement transaction is rolled back. An exception is an INSERT
96240 ** statement that inserts a single row only (no triggers). In this case,
96241 ** instead of using a counter, an exception is thrown immediately if the
96242 ** INSERT violates a foreign key constraint. This is necessary as such
96243 ** an INSERT does not open a statement transaction.
96245 ** TODO: How should dropping a table be handled? How should renaming a
96246 ** table be handled?
96249 ** Query API Notes
96250 ** ---------------
96252 ** Before coding an UPDATE or DELETE row operation, the code-generator
96253 ** for those two operations needs to know whether or not the operation
96254 ** requires any FK processing and, if so, which columns of the original
96255 ** row are required by the FK processing VDBE code (i.e. if FKs were
96256 ** implemented using triggers, which of the old.* columns would be
96257 ** accessed). No information is required by the code-generator before
96258 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
96259 ** generation code to query for this information are:
96261 ** sqlite3FkRequired() - Test to see if FK processing is required.
96262 ** sqlite3FkOldmask() - Query for the set of required old.* columns.
96265 ** Externally accessible module functions
96266 ** --------------------------------------
96268 ** sqlite3FkCheck() - Check for foreign key violations.
96269 ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
96270 ** sqlite3FkDelete() - Delete an FKey structure.
96274 ** VDBE Calling Convention
96275 ** -----------------------
96277 ** Example:
96279 ** For the following INSERT statement:
96281 ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
96282 ** INSERT INTO t1 VALUES(1, 2, 3.1);
96284 ** Register (x): 2 (type integer)
96285 ** Register (x+1): 1 (type integer)
96286 ** Register (x+2): NULL (type NULL)
96287 ** Register (x+3): 3.1 (type real)
96291 ** A foreign key constraint requires that the key columns in the parent
96292 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
96293 ** Given that pParent is the parent table for foreign key constraint pFKey,
96294 ** search the schema for a unique index on the parent key columns.
96296 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
96297 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
96298 ** is set to point to the unique index.
96300 ** If the parent key consists of a single column (the foreign key constraint
96301 ** is not a composite foreign key), output variable *paiCol is set to NULL.
96302 ** Otherwise, it is set to point to an allocated array of size N, where
96303 ** N is the number of columns in the parent key. The first element of the
96304 ** array is the index of the child table column that is mapped by the FK
96305 ** constraint to the parent table column stored in the left-most column
96306 ** of index *ppIdx. The second element of the array is the index of the
96307 ** child table column that corresponds to the second left-most column of
96308 ** *ppIdx, and so on.
96310 ** If the required index cannot be found, either because:
96312 ** 1) The named parent key columns do not exist, or
96314 ** 2) The named parent key columns do exist, but are not subject to a
96315 ** UNIQUE or PRIMARY KEY constraint, or
96317 ** 3) No parent key columns were provided explicitly as part of the
96318 ** foreign key definition, and the parent table does not have a
96319 ** PRIMARY KEY, or
96321 ** 4) No parent key columns were provided explicitly as part of the
96322 ** foreign key definition, and the PRIMARY KEY of the parent table
96323 ** consists of a different number of columns to the child key in
96324 ** the child table.
96326 ** then non-zero is returned, and a "foreign key mismatch" error loaded
96327 ** into pParse. If an OOM error occurs, non-zero is returned and the
96328 ** pParse->db->mallocFailed flag is set.
96330 SQLITE_PRIVATE int sqlite3FkLocateIndex(
96331 Parse *pParse, /* Parse context to store any error in */
96332 Table *pParent, /* Parent table of FK constraint pFKey */
96333 FKey *pFKey, /* Foreign key to find index for */
96334 Index **ppIdx, /* OUT: Unique index on parent table */
96335 int **paiCol /* OUT: Map of index columns in pFKey */
96337 Index *pIdx = 0; /* Value to return via *ppIdx */
96338 int *aiCol = 0; /* Value to return via *paiCol */
96339 int nCol = pFKey->nCol; /* Number of columns in parent key */
96340 char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
96342 /* The caller is responsible for zeroing output parameters. */
96343 assert( ppIdx && *ppIdx==0 );
96344 assert( !paiCol || *paiCol==0 );
96345 assert( pParse );
96347 /* If this is a non-composite (single column) foreign key, check if it
96348 ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
96349 ** and *paiCol set to zero and return early.
96351 ** Otherwise, for a composite foreign key (more than one column), allocate
96352 ** space for the aiCol array (returned via output parameter *paiCol).
96353 ** Non-composite foreign keys do not require the aiCol array.
96355 if( nCol==1 ){
96356 /* The FK maps to the IPK if any of the following are true:
96358 ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
96359 ** mapped to the primary key of table pParent, or
96360 ** 2) The FK is explicitly mapped to a column declared as INTEGER
96361 ** PRIMARY KEY.
96363 if( pParent->iPKey>=0 ){
96364 if( !zKey ) return 0;
96365 if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
96367 }else if( paiCol ){
96368 assert( nCol>1 );
96369 aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
96370 if( !aiCol ) return 1;
96371 *paiCol = aiCol;
96374 for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
96375 if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
96376 /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
96377 ** of columns. If each indexed column corresponds to a foreign key
96378 ** column of pFKey, then this index is a winner. */
96380 if( zKey==0 ){
96381 /* If zKey is NULL, then this foreign key is implicitly mapped to
96382 ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
96383 ** identified by the test. */
96384 if( IsPrimaryKeyIndex(pIdx) ){
96385 if( aiCol ){
96386 int i;
96387 for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
96389 break;
96391 }else{
96392 /* If zKey is non-NULL, then this foreign key was declared to
96393 ** map to an explicit list of columns in table pParent. Check if this
96394 ** index matches those columns. Also, check that the index uses
96395 ** the default collation sequences for each column. */
96396 int i, j;
96397 for(i=0; i<nCol; i++){
96398 i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
96399 char *zDfltColl; /* Def. collation for column */
96400 char *zIdxCol; /* Name of indexed column */
96402 /* If the index uses a collation sequence that is different from
96403 ** the default collation sequence for the column, this index is
96404 ** unusable. Bail out early in this case. */
96405 zDfltColl = pParent->aCol[iCol].zColl;
96406 if( !zDfltColl ){
96407 zDfltColl = "BINARY";
96409 if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
96411 zIdxCol = pParent->aCol[iCol].zName;
96412 for(j=0; j<nCol; j++){
96413 if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
96414 if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
96415 break;
96418 if( j==nCol ) break;
96420 if( i==nCol ) break; /* pIdx is usable */
96425 if( !pIdx ){
96426 if( !pParse->disableTriggers ){
96427 sqlite3ErrorMsg(pParse,
96428 "foreign key mismatch - \"%w\" referencing \"%w\"",
96429 pFKey->pFrom->zName, pFKey->zTo);
96431 sqlite3DbFree(pParse->db, aiCol);
96432 return 1;
96435 *ppIdx = pIdx;
96436 return 0;
96440 ** This function is called when a row is inserted into or deleted from the
96441 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
96442 ** on the child table of pFKey, this function is invoked twice for each row
96443 ** affected - once to "delete" the old row, and then again to "insert" the
96444 ** new row.
96446 ** Each time it is called, this function generates VDBE code to locate the
96447 ** row in the parent table that corresponds to the row being inserted into
96448 ** or deleted from the child table. If the parent row can be found, no
96449 ** special action is taken. Otherwise, if the parent row can *not* be
96450 ** found in the parent table:
96452 ** Operation | FK type | Action taken
96453 ** --------------------------------------------------------------------------
96454 ** INSERT immediate Increment the "immediate constraint counter".
96456 ** DELETE immediate Decrement the "immediate constraint counter".
96458 ** INSERT deferred Increment the "deferred constraint counter".
96460 ** DELETE deferred Decrement the "deferred constraint counter".
96462 ** These operations are identified in the comment at the top of this file
96463 ** (fkey.c) as "I.1" and "D.1".
96465 static void fkLookupParent(
96466 Parse *pParse, /* Parse context */
96467 int iDb, /* Index of database housing pTab */
96468 Table *pTab, /* Parent table of FK pFKey */
96469 Index *pIdx, /* Unique index on parent key columns in pTab */
96470 FKey *pFKey, /* Foreign key constraint */
96471 int *aiCol, /* Map from parent key columns to child table columns */
96472 int regData, /* Address of array containing child table row */
96473 int nIncr, /* Increment constraint counter by this */
96474 int isIgnore /* If true, pretend pTab contains all NULL values */
96476 int i; /* Iterator variable */
96477 Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
96478 int iCur = pParse->nTab - 1; /* Cursor number to use */
96479 int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
96481 /* If nIncr is less than zero, then check at runtime if there are any
96482 ** outstanding constraints to resolve. If there are not, there is no need
96483 ** to check if deleting this row resolves any outstanding violations.
96485 ** Check if any of the key columns in the child table row are NULL. If
96486 ** any are, then the constraint is considered satisfied. No need to
96487 ** search for a matching row in the parent table. */
96488 if( nIncr<0 ){
96489 sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
96490 VdbeCoverage(v);
96492 for(i=0; i<pFKey->nCol; i++){
96493 int iReg = aiCol[i] + regData + 1;
96494 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
96497 if( isIgnore==0 ){
96498 if( pIdx==0 ){
96499 /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
96500 ** column of the parent table (table pTab). */
96501 int iMustBeInt; /* Address of MustBeInt instruction */
96502 int regTemp = sqlite3GetTempReg(pParse);
96504 /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
96505 ** apply the affinity of the parent key). If this fails, then there
96506 ** is no matching parent key. Before using MustBeInt, make a copy of
96507 ** the value. Otherwise, the value inserted into the child key column
96508 ** will have INTEGER affinity applied to it, which may not be correct. */
96509 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
96510 iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
96511 VdbeCoverage(v);
96513 /* If the parent table is the same as the child table, and we are about
96514 ** to increment the constraint-counter (i.e. this is an INSERT operation),
96515 ** then check if the row being inserted matches itself. If so, do not
96516 ** increment the constraint-counter. */
96517 if( pTab==pFKey->pFrom && nIncr==1 ){
96518 sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
96519 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
96522 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
96523 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
96524 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
96525 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
96526 sqlite3VdbeJumpHere(v, iMustBeInt);
96527 sqlite3ReleaseTempReg(pParse, regTemp);
96528 }else{
96529 int nCol = pFKey->nCol;
96530 int regTemp = sqlite3GetTempRange(pParse, nCol);
96531 int regRec = sqlite3GetTempReg(pParse);
96533 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
96534 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
96535 for(i=0; i<nCol; i++){
96536 sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
96539 /* If the parent table is the same as the child table, and we are about
96540 ** to increment the constraint-counter (i.e. this is an INSERT operation),
96541 ** then check if the row being inserted matches itself. If so, do not
96542 ** increment the constraint-counter.
96544 ** If any of the parent-key values are NULL, then the row cannot match
96545 ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
96546 ** of the parent-key values are NULL (at this point it is known that
96547 ** none of the child key values are).
96549 if( pTab==pFKey->pFrom && nIncr==1 ){
96550 int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
96551 for(i=0; i<nCol; i++){
96552 int iChild = aiCol[i]+1+regData;
96553 int iParent = pIdx->aiColumn[i]+1+regData;
96554 assert( aiCol[i]!=pTab->iPKey );
96555 if( pIdx->aiColumn[i]==pTab->iPKey ){
96556 /* The parent key is a composite key that includes the IPK column */
96557 iParent = regData;
96559 sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
96560 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
96562 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
96565 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
96566 sqlite3IndexAffinityStr(v,pIdx), nCol);
96567 sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
96569 sqlite3ReleaseTempReg(pParse, regRec);
96570 sqlite3ReleaseTempRange(pParse, regTemp, nCol);
96574 if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
96575 && !pParse->pToplevel
96576 && !pParse->isMultiWrite
96578 /* Special case: If this is an INSERT statement that will insert exactly
96579 ** one row into the table, raise a constraint immediately instead of
96580 ** incrementing a counter. This is necessary as the VM code is being
96581 ** generated for will not open a statement transaction. */
96582 assert( nIncr==1 );
96583 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
96584 OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
96585 }else{
96586 if( nIncr>0 && pFKey->isDeferred==0 ){
96587 sqlite3ParseToplevel(pParse)->mayAbort = 1;
96589 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
96592 sqlite3VdbeResolveLabel(v, iOk);
96593 sqlite3VdbeAddOp1(v, OP_Close, iCur);
96598 ** Return an Expr object that refers to a memory register corresponding
96599 ** to column iCol of table pTab.
96601 ** regBase is the first of an array of register that contains the data
96602 ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
96603 ** column. regBase+2 holds the second column, and so forth.
96605 static Expr *exprTableRegister(
96606 Parse *pParse, /* Parsing and code generating context */
96607 Table *pTab, /* The table whose content is at r[regBase]... */
96608 int regBase, /* Contents of table pTab */
96609 i16 iCol /* Which column of pTab is desired */
96611 Expr *pExpr;
96612 Column *pCol;
96613 const char *zColl;
96614 sqlite3 *db = pParse->db;
96616 pExpr = sqlite3Expr(db, TK_REGISTER, 0);
96617 if( pExpr ){
96618 if( iCol>=0 && iCol!=pTab->iPKey ){
96619 pCol = &pTab->aCol[iCol];
96620 pExpr->iTable = regBase + iCol + 1;
96621 pExpr->affinity = pCol->affinity;
96622 zColl = pCol->zColl;
96623 if( zColl==0 ) zColl = db->pDfltColl->zName;
96624 pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
96625 }else{
96626 pExpr->iTable = regBase;
96627 pExpr->affinity = SQLITE_AFF_INTEGER;
96630 return pExpr;
96634 ** Return an Expr object that refers to column iCol of table pTab which
96635 ** has cursor iCur.
96637 static Expr *exprTableColumn(
96638 sqlite3 *db, /* The database connection */
96639 Table *pTab, /* The table whose column is desired */
96640 int iCursor, /* The open cursor on the table */
96641 i16 iCol /* The column that is wanted */
96643 Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
96644 if( pExpr ){
96645 pExpr->pTab = pTab;
96646 pExpr->iTable = iCursor;
96647 pExpr->iColumn = iCol;
96649 return pExpr;
96653 ** This function is called to generate code executed when a row is deleted
96654 ** from the parent table of foreign key constraint pFKey and, if pFKey is
96655 ** deferred, when a row is inserted into the same table. When generating
96656 ** code for an SQL UPDATE operation, this function may be called twice -
96657 ** once to "delete" the old row and once to "insert" the new row.
96659 ** The code generated by this function scans through the rows in the child
96660 ** table that correspond to the parent table row being deleted or inserted.
96661 ** For each child row found, one of the following actions is taken:
96663 ** Operation | FK type | Action taken
96664 ** --------------------------------------------------------------------------
96665 ** DELETE immediate Increment the "immediate constraint counter".
96666 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
96667 ** throw a "FOREIGN KEY constraint failed" exception.
96669 ** INSERT immediate Decrement the "immediate constraint counter".
96671 ** DELETE deferred Increment the "deferred constraint counter".
96672 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
96673 ** throw a "FOREIGN KEY constraint failed" exception.
96675 ** INSERT deferred Decrement the "deferred constraint counter".
96677 ** These operations are identified in the comment at the top of this file
96678 ** (fkey.c) as "I.2" and "D.2".
96680 static void fkScanChildren(
96681 Parse *pParse, /* Parse context */
96682 SrcList *pSrc, /* The child table to be scanned */
96683 Table *pTab, /* The parent table */
96684 Index *pIdx, /* Index on parent covering the foreign key */
96685 FKey *pFKey, /* The foreign key linking pSrc to pTab */
96686 int *aiCol, /* Map from pIdx cols to child table cols */
96687 int regData, /* Parent row data starts here */
96688 int nIncr /* Amount to increment deferred counter by */
96690 sqlite3 *db = pParse->db; /* Database handle */
96691 int i; /* Iterator variable */
96692 Expr *pWhere = 0; /* WHERE clause to scan with */
96693 NameContext sNameContext; /* Context used to resolve WHERE clause */
96694 WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
96695 int iFkIfZero = 0; /* Address of OP_FkIfZero */
96696 Vdbe *v = sqlite3GetVdbe(pParse);
96698 assert( pIdx==0 || pIdx->pTable==pTab );
96699 assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
96700 assert( pIdx!=0 || pFKey->nCol==1 );
96701 assert( pIdx!=0 || HasRowid(pTab) );
96703 if( nIncr<0 ){
96704 iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
96705 VdbeCoverage(v);
96708 /* Create an Expr object representing an SQL expression like:
96710 ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
96712 ** The collation sequence used for the comparison should be that of
96713 ** the parent key columns. The affinity of the parent key column should
96714 ** be applied to each child key value before the comparison takes place.
96716 for(i=0; i<pFKey->nCol; i++){
96717 Expr *pLeft; /* Value from parent table row */
96718 Expr *pRight; /* Column ref to child table */
96719 Expr *pEq; /* Expression (pLeft = pRight) */
96720 i16 iCol; /* Index of column in child table */
96721 const char *zCol; /* Name of column in child table */
96723 iCol = pIdx ? pIdx->aiColumn[i] : -1;
96724 pLeft = exprTableRegister(pParse, pTab, regData, iCol);
96725 iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
96726 assert( iCol>=0 );
96727 zCol = pFKey->pFrom->aCol[iCol].zName;
96728 pRight = sqlite3Expr(db, TK_ID, zCol);
96729 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
96730 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
96733 /* If the child table is the same as the parent table, then add terms
96734 ** to the WHERE clause that prevent this entry from being scanned.
96735 ** The added WHERE clause terms are like this:
96737 ** $current_rowid!=rowid
96738 ** NOT( $current_a==a AND $current_b==b AND ... )
96740 ** The first form is used for rowid tables. The second form is used
96741 ** for WITHOUT ROWID tables. In the second form, the primary key is
96742 ** (a,b,...)
96744 if( pTab==pFKey->pFrom && nIncr>0 ){
96745 Expr *pNe; /* Expression (pLeft != pRight) */
96746 Expr *pLeft; /* Value from parent table row */
96747 Expr *pRight; /* Column ref to child table */
96748 if( HasRowid(pTab) ){
96749 pLeft = exprTableRegister(pParse, pTab, regData, -1);
96750 pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
96751 pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
96752 }else{
96753 Expr *pEq, *pAll = 0;
96754 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
96755 assert( pIdx!=0 );
96756 for(i=0; i<pPk->nKeyCol; i++){
96757 i16 iCol = pIdx->aiColumn[i];
96758 pLeft = exprTableRegister(pParse, pTab, regData, iCol);
96759 pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
96760 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
96761 pAll = sqlite3ExprAnd(db, pAll, pEq);
96763 pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
96765 pWhere = sqlite3ExprAnd(db, pWhere, pNe);
96768 /* Resolve the references in the WHERE clause. */
96769 memset(&sNameContext, 0, sizeof(NameContext));
96770 sNameContext.pSrcList = pSrc;
96771 sNameContext.pParse = pParse;
96772 sqlite3ResolveExprNames(&sNameContext, pWhere);
96774 /* Create VDBE to loop through the entries in pSrc that match the WHERE
96775 ** clause. If the constraint is not deferred, throw an exception for
96776 ** each row found. Otherwise, for deferred constraints, increment the
96777 ** deferred constraint counter by nIncr for each row selected. */
96778 pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
96779 if( nIncr>0 && pFKey->isDeferred==0 ){
96780 sqlite3ParseToplevel(pParse)->mayAbort = 1;
96782 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
96783 if( pWInfo ){
96784 sqlite3WhereEnd(pWInfo);
96787 /* Clean up the WHERE clause constructed above. */
96788 sqlite3ExprDelete(db, pWhere);
96789 if( iFkIfZero ){
96790 sqlite3VdbeJumpHere(v, iFkIfZero);
96795 ** This function returns a linked list of FKey objects (connected by
96796 ** FKey.pNextTo) holding all children of table pTab. For example,
96797 ** given the following schema:
96799 ** CREATE TABLE t1(a PRIMARY KEY);
96800 ** CREATE TABLE t2(b REFERENCES t1(a);
96802 ** Calling this function with table "t1" as an argument returns a pointer
96803 ** to the FKey structure representing the foreign key constraint on table
96804 ** "t2". Calling this function with "t2" as the argument would return a
96805 ** NULL pointer (as there are no FK constraints for which t2 is the parent
96806 ** table).
96808 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
96809 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
96813 ** The second argument is a Trigger structure allocated by the
96814 ** fkActionTrigger() routine. This function deletes the Trigger structure
96815 ** and all of its sub-components.
96817 ** The Trigger structure or any of its sub-components may be allocated from
96818 ** the lookaside buffer belonging to database handle dbMem.
96820 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
96821 if( p ){
96822 TriggerStep *pStep = p->step_list;
96823 sqlite3ExprDelete(dbMem, pStep->pWhere);
96824 sqlite3ExprListDelete(dbMem, pStep->pExprList);
96825 sqlite3SelectDelete(dbMem, pStep->pSelect);
96826 sqlite3ExprDelete(dbMem, p->pWhen);
96827 sqlite3DbFree(dbMem, p);
96832 ** This function is called to generate code that runs when table pTab is
96833 ** being dropped from the database. The SrcList passed as the second argument
96834 ** to this function contains a single entry guaranteed to resolve to
96835 ** table pTab.
96837 ** Normally, no code is required. However, if either
96839 ** (a) The table is the parent table of a FK constraint, or
96840 ** (b) The table is the child table of a deferred FK constraint and it is
96841 ** determined at runtime that there are outstanding deferred FK
96842 ** constraint violations in the database,
96844 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
96845 ** the table from the database. Triggers are disabled while running this
96846 ** DELETE, but foreign key actions are not.
96848 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
96849 sqlite3 *db = pParse->db;
96850 if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
96851 int iSkip = 0;
96852 Vdbe *v = sqlite3GetVdbe(pParse);
96854 assert( v ); /* VDBE has already been allocated */
96855 if( sqlite3FkReferences(pTab)==0 ){
96856 /* Search for a deferred foreign key constraint for which this table
96857 ** is the child table. If one cannot be found, return without
96858 ** generating any VDBE code. If one can be found, then jump over
96859 ** the entire DELETE if there are no outstanding deferred constraints
96860 ** when this statement is run. */
96861 FKey *p;
96862 for(p=pTab->pFKey; p; p=p->pNextFrom){
96863 if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
96865 if( !p ) return;
96866 iSkip = sqlite3VdbeMakeLabel(v);
96867 sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
96870 pParse->disableTriggers = 1;
96871 sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
96872 pParse->disableTriggers = 0;
96874 /* If the DELETE has generated immediate foreign key constraint
96875 ** violations, halt the VDBE and return an error at this point, before
96876 ** any modifications to the schema are made. This is because statement
96877 ** transactions are not able to rollback schema changes.
96879 ** If the SQLITE_DeferFKs flag is set, then this is not required, as
96880 ** the statement transaction will not be rolled back even if FK
96881 ** constraints are violated.
96883 if( (db->flags & SQLITE_DeferFKs)==0 ){
96884 sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
96885 VdbeCoverage(v);
96886 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
96887 OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
96890 if( iSkip ){
96891 sqlite3VdbeResolveLabel(v, iSkip);
96898 ** The second argument points to an FKey object representing a foreign key
96899 ** for which pTab is the child table. An UPDATE statement against pTab
96900 ** is currently being processed. For each column of the table that is
96901 ** actually updated, the corresponding element in the aChange[] array
96902 ** is zero or greater (if a column is unmodified the corresponding element
96903 ** is set to -1). If the rowid column is modified by the UPDATE statement
96904 ** the bChngRowid argument is non-zero.
96906 ** This function returns true if any of the columns that are part of the
96907 ** child key for FK constraint *p are modified.
96909 static int fkChildIsModified(
96910 Table *pTab, /* Table being updated */
96911 FKey *p, /* Foreign key for which pTab is the child */
96912 int *aChange, /* Array indicating modified columns */
96913 int bChngRowid /* True if rowid is modified by this update */
96915 int i;
96916 for(i=0; i<p->nCol; i++){
96917 int iChildKey = p->aCol[i].iFrom;
96918 if( aChange[iChildKey]>=0 ) return 1;
96919 if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
96921 return 0;
96925 ** The second argument points to an FKey object representing a foreign key
96926 ** for which pTab is the parent table. An UPDATE statement against pTab
96927 ** is currently being processed. For each column of the table that is
96928 ** actually updated, the corresponding element in the aChange[] array
96929 ** is zero or greater (if a column is unmodified the corresponding element
96930 ** is set to -1). If the rowid column is modified by the UPDATE statement
96931 ** the bChngRowid argument is non-zero.
96933 ** This function returns true if any of the columns that are part of the
96934 ** parent key for FK constraint *p are modified.
96936 static int fkParentIsModified(
96937 Table *pTab,
96938 FKey *p,
96939 int *aChange,
96940 int bChngRowid
96942 int i;
96943 for(i=0; i<p->nCol; i++){
96944 char *zKey = p->aCol[i].zCol;
96945 int iKey;
96946 for(iKey=0; iKey<pTab->nCol; iKey++){
96947 if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
96948 Column *pCol = &pTab->aCol[iKey];
96949 if( zKey ){
96950 if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
96951 }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
96952 return 1;
96957 return 0;
96961 ** This function is called when inserting, deleting or updating a row of
96962 ** table pTab to generate VDBE code to perform foreign key constraint
96963 ** processing for the operation.
96965 ** For a DELETE operation, parameter regOld is passed the index of the
96966 ** first register in an array of (pTab->nCol+1) registers containing the
96967 ** rowid of the row being deleted, followed by each of the column values
96968 ** of the row being deleted, from left to right. Parameter regNew is passed
96969 ** zero in this case.
96971 ** For an INSERT operation, regOld is passed zero and regNew is passed the
96972 ** first register of an array of (pTab->nCol+1) registers containing the new
96973 ** row data.
96975 ** For an UPDATE operation, this function is called twice. Once before
96976 ** the original record is deleted from the table using the calling convention
96977 ** described for DELETE. Then again after the original record is deleted
96978 ** but before the new record is inserted using the INSERT convention.
96980 SQLITE_PRIVATE void sqlite3FkCheck(
96981 Parse *pParse, /* Parse context */
96982 Table *pTab, /* Row is being deleted from this table */
96983 int regOld, /* Previous row data is stored here */
96984 int regNew, /* New row data is stored here */
96985 int *aChange, /* Array indicating UPDATEd columns (or 0) */
96986 int bChngRowid /* True if rowid is UPDATEd */
96988 sqlite3 *db = pParse->db; /* Database handle */
96989 FKey *pFKey; /* Used to iterate through FKs */
96990 int iDb; /* Index of database containing pTab */
96991 const char *zDb; /* Name of database containing pTab */
96992 int isIgnoreErrors = pParse->disableTriggers;
96994 /* Exactly one of regOld and regNew should be non-zero. */
96995 assert( (regOld==0)!=(regNew==0) );
96997 /* If foreign-keys are disabled, this function is a no-op. */
96998 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
97000 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
97001 zDb = db->aDb[iDb].zName;
97003 /* Loop through all the foreign key constraints for which pTab is the
97004 ** child table (the table that the foreign key definition is part of). */
97005 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
97006 Table *pTo; /* Parent table of foreign key pFKey */
97007 Index *pIdx = 0; /* Index on key columns in pTo */
97008 int *aiFree = 0;
97009 int *aiCol;
97010 int iCol;
97011 int i;
97012 int isIgnore = 0;
97014 if( aChange
97015 && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
97016 && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
97018 continue;
97021 /* Find the parent table of this foreign key. Also find a unique index
97022 ** on the parent key columns in the parent table. If either of these
97023 ** schema items cannot be located, set an error in pParse and return
97024 ** early. */
97025 if( pParse->disableTriggers ){
97026 pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
97027 }else{
97028 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
97030 if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
97031 assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
97032 if( !isIgnoreErrors || db->mallocFailed ) return;
97033 if( pTo==0 ){
97034 /* If isIgnoreErrors is true, then a table is being dropped. In this
97035 ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
97036 ** before actually dropping it in order to check FK constraints.
97037 ** If the parent table of an FK constraint on the current table is
97038 ** missing, behave as if it is empty. i.e. decrement the relevant
97039 ** FK counter for each row of the current table with non-NULL keys.
97041 Vdbe *v = sqlite3GetVdbe(pParse);
97042 int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
97043 for(i=0; i<pFKey->nCol; i++){
97044 int iReg = pFKey->aCol[i].iFrom + regOld + 1;
97045 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
97047 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
97049 continue;
97051 assert( pFKey->nCol==1 || (aiFree && pIdx) );
97053 if( aiFree ){
97054 aiCol = aiFree;
97055 }else{
97056 iCol = pFKey->aCol[0].iFrom;
97057 aiCol = &iCol;
97059 for(i=0; i<pFKey->nCol; i++){
97060 if( aiCol[i]==pTab->iPKey ){
97061 aiCol[i] = -1;
97063 #ifndef SQLITE_OMIT_AUTHORIZATION
97064 /* Request permission to read the parent key columns. If the
97065 ** authorization callback returns SQLITE_IGNORE, behave as if any
97066 ** values read from the parent table are NULL. */
97067 if( db->xAuth ){
97068 int rcauth;
97069 char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
97070 rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
97071 isIgnore = (rcauth==SQLITE_IGNORE);
97073 #endif
97076 /* Take a shared-cache advisory read-lock on the parent table. Allocate
97077 ** a cursor to use to search the unique index on the parent key columns
97078 ** in the parent table. */
97079 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
97080 pParse->nTab++;
97082 if( regOld!=0 ){
97083 /* A row is being removed from the child table. Search for the parent.
97084 ** If the parent does not exist, removing the child row resolves an
97085 ** outstanding foreign key constraint violation. */
97086 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
97088 if( regNew!=0 ){
97089 /* A row is being added to the child table. If a parent row cannot
97090 ** be found, adding the child row has violated the FK constraint. */
97091 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
97094 sqlite3DbFree(db, aiFree);
97097 /* Loop through all the foreign key constraints that refer to this table.
97098 ** (the "child" constraints) */
97099 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
97100 Index *pIdx = 0; /* Foreign key index for pFKey */
97101 SrcList *pSrc;
97102 int *aiCol = 0;
97104 if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
97105 continue;
97108 if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
97109 && !pParse->pToplevel && !pParse->isMultiWrite
97111 assert( regOld==0 && regNew!=0 );
97112 /* Inserting a single row into a parent table cannot cause an immediate
97113 ** foreign key violation. So do nothing in this case. */
97114 continue;
97117 if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
97118 if( !isIgnoreErrors || db->mallocFailed ) return;
97119 continue;
97121 assert( aiCol || pFKey->nCol==1 );
97123 /* Create a SrcList structure containing the child table. We need the
97124 ** child table as a SrcList for sqlite3WhereBegin() */
97125 pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
97126 if( pSrc ){
97127 struct SrcList_item *pItem = pSrc->a;
97128 pItem->pTab = pFKey->pFrom;
97129 pItem->zName = pFKey->pFrom->zName;
97130 pItem->pTab->nRef++;
97131 pItem->iCursor = pParse->nTab++;
97133 if( regNew!=0 ){
97134 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
97136 if( regOld!=0 ){
97137 /* If there is a RESTRICT action configured for the current operation
97138 ** on the parent table of this FK, then throw an exception
97139 ** immediately if the FK constraint is violated, even if this is a
97140 ** deferred trigger. That's what RESTRICT means. To defer checking
97141 ** the constraint, the FK should specify NO ACTION (represented
97142 ** using OE_None). NO ACTION is the default. */
97143 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
97145 pItem->zName = 0;
97146 sqlite3SrcListDelete(db, pSrc);
97148 sqlite3DbFree(db, aiCol);
97152 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
97155 ** This function is called before generating code to update or delete a
97156 ** row contained in table pTab.
97158 SQLITE_PRIVATE u32 sqlite3FkOldmask(
97159 Parse *pParse, /* Parse context */
97160 Table *pTab /* Table being modified */
97162 u32 mask = 0;
97163 if( pParse->db->flags&SQLITE_ForeignKeys ){
97164 FKey *p;
97165 int i;
97166 for(p=pTab->pFKey; p; p=p->pNextFrom){
97167 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
97169 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
97170 Index *pIdx = 0;
97171 sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
97172 if( pIdx ){
97173 for(i=0; i<pIdx->nKeyCol; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
97177 return mask;
97182 ** This function is called before generating code to update or delete a
97183 ** row contained in table pTab. If the operation is a DELETE, then
97184 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
97185 ** to an array of size N, where N is the number of columns in table pTab.
97186 ** If the i'th column is not modified by the UPDATE, then the corresponding
97187 ** entry in the aChange[] array is set to -1. If the column is modified,
97188 ** the value is 0 or greater. Parameter chngRowid is set to true if the
97189 ** UPDATE statement modifies the rowid fields of the table.
97191 ** If any foreign key processing will be required, this function returns
97192 ** true. If there is no foreign key related processing, this function
97193 ** returns false.
97195 SQLITE_PRIVATE int sqlite3FkRequired(
97196 Parse *pParse, /* Parse context */
97197 Table *pTab, /* Table being modified */
97198 int *aChange, /* Non-NULL for UPDATE operations */
97199 int chngRowid /* True for UPDATE that affects rowid */
97201 if( pParse->db->flags&SQLITE_ForeignKeys ){
97202 if( !aChange ){
97203 /* A DELETE operation. Foreign key processing is required if the
97204 ** table in question is either the child or parent table for any
97205 ** foreign key constraint. */
97206 return (sqlite3FkReferences(pTab) || pTab->pFKey);
97207 }else{
97208 /* This is an UPDATE. Foreign key processing is only required if the
97209 ** operation modifies one or more child or parent key columns. */
97210 FKey *p;
97212 /* Check if any child key columns are being modified. */
97213 for(p=pTab->pFKey; p; p=p->pNextFrom){
97214 if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
97217 /* Check if any parent key columns are being modified. */
97218 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
97219 if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
97223 return 0;
97227 ** This function is called when an UPDATE or DELETE operation is being
97228 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
97229 ** If the current operation is an UPDATE, then the pChanges parameter is
97230 ** passed a pointer to the list of columns being modified. If it is a
97231 ** DELETE, pChanges is passed a NULL pointer.
97233 ** It returns a pointer to a Trigger structure containing a trigger
97234 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
97235 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
97236 ** returned (these actions require no special handling by the triggers
97237 ** sub-system, code for them is created by fkScanChildren()).
97239 ** For example, if pFKey is the foreign key and pTab is table "p" in
97240 ** the following schema:
97242 ** CREATE TABLE p(pk PRIMARY KEY);
97243 ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
97245 ** then the returned trigger structure is equivalent to:
97247 ** CREATE TRIGGER ... DELETE ON p BEGIN
97248 ** DELETE FROM c WHERE ck = old.pk;
97249 ** END;
97251 ** The returned pointer is cached as part of the foreign key object. It
97252 ** is eventually freed along with the rest of the foreign key object by
97253 ** sqlite3FkDelete().
97255 static Trigger *fkActionTrigger(
97256 Parse *pParse, /* Parse context */
97257 Table *pTab, /* Table being updated or deleted from */
97258 FKey *pFKey, /* Foreign key to get action for */
97259 ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
97261 sqlite3 *db = pParse->db; /* Database handle */
97262 int action; /* One of OE_None, OE_Cascade etc. */
97263 Trigger *pTrigger; /* Trigger definition to return */
97264 int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
97266 action = pFKey->aAction[iAction];
97267 pTrigger = pFKey->apTrigger[iAction];
97269 if( action!=OE_None && !pTrigger ){
97270 u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
97271 char const *zFrom; /* Name of child table */
97272 int nFrom; /* Length in bytes of zFrom */
97273 Index *pIdx = 0; /* Parent key index for this FK */
97274 int *aiCol = 0; /* child table cols -> parent key cols */
97275 TriggerStep *pStep = 0; /* First (only) step of trigger program */
97276 Expr *pWhere = 0; /* WHERE clause of trigger step */
97277 ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
97278 Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
97279 int i; /* Iterator variable */
97280 Expr *pWhen = 0; /* WHEN clause for the trigger */
97282 if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
97283 assert( aiCol || pFKey->nCol==1 );
97285 for(i=0; i<pFKey->nCol; i++){
97286 Token tOld = { "old", 3 }; /* Literal "old" token */
97287 Token tNew = { "new", 3 }; /* Literal "new" token */
97288 Token tFromCol; /* Name of column in child table */
97289 Token tToCol; /* Name of column in parent table */
97290 int iFromCol; /* Idx of column in child table */
97291 Expr *pEq; /* tFromCol = OLD.tToCol */
97293 iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
97294 assert( iFromCol>=0 );
97295 tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
97296 tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
97298 tToCol.n = sqlite3Strlen30(tToCol.z);
97299 tFromCol.n = sqlite3Strlen30(tFromCol.z);
97301 /* Create the expression "OLD.zToCol = zFromCol". It is important
97302 ** that the "OLD.zToCol" term is on the LHS of the = operator, so
97303 ** that the affinity and collation sequence associated with the
97304 ** parent table are used for the comparison. */
97305 pEq = sqlite3PExpr(pParse, TK_EQ,
97306 sqlite3PExpr(pParse, TK_DOT,
97307 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
97308 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
97309 , 0),
97310 sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
97311 , 0);
97312 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
97314 /* For ON UPDATE, construct the next term of the WHEN clause.
97315 ** The final WHEN clause will be like this:
97317 ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
97319 if( pChanges ){
97320 pEq = sqlite3PExpr(pParse, TK_IS,
97321 sqlite3PExpr(pParse, TK_DOT,
97322 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
97323 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
97325 sqlite3PExpr(pParse, TK_DOT,
97326 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
97327 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
97330 pWhen = sqlite3ExprAnd(db, pWhen, pEq);
97333 if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
97334 Expr *pNew;
97335 if( action==OE_Cascade ){
97336 pNew = sqlite3PExpr(pParse, TK_DOT,
97337 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
97338 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
97339 , 0);
97340 }else if( action==OE_SetDflt ){
97341 Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
97342 if( pDflt ){
97343 pNew = sqlite3ExprDup(db, pDflt, 0);
97344 }else{
97345 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
97347 }else{
97348 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
97350 pList = sqlite3ExprListAppend(pParse, pList, pNew);
97351 sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
97354 sqlite3DbFree(db, aiCol);
97356 zFrom = pFKey->pFrom->zName;
97357 nFrom = sqlite3Strlen30(zFrom);
97359 if( action==OE_Restrict ){
97360 Token tFrom;
97361 Expr *pRaise;
97363 tFrom.z = zFrom;
97364 tFrom.n = nFrom;
97365 pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
97366 if( pRaise ){
97367 pRaise->affinity = OE_Abort;
97369 pSelect = sqlite3SelectNew(pParse,
97370 sqlite3ExprListAppend(pParse, 0, pRaise),
97371 sqlite3SrcListAppend(db, 0, &tFrom, 0),
97372 pWhere,
97373 0, 0, 0, 0, 0, 0
97375 pWhere = 0;
97378 /* Disable lookaside memory allocation */
97379 enableLookaside = db->lookaside.bEnabled;
97380 db->lookaside.bEnabled = 0;
97382 pTrigger = (Trigger *)sqlite3DbMallocZero(db,
97383 sizeof(Trigger) + /* struct Trigger */
97384 sizeof(TriggerStep) + /* Single step in trigger program */
97385 nFrom + 1 /* Space for pStep->target.z */
97387 if( pTrigger ){
97388 pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
97389 pStep->target.z = (char *)&pStep[1];
97390 pStep->target.n = nFrom;
97391 memcpy((char *)pStep->target.z, zFrom, nFrom);
97393 pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
97394 pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
97395 pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
97396 if( pWhen ){
97397 pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
97398 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
97402 /* Re-enable the lookaside buffer, if it was disabled earlier. */
97403 db->lookaside.bEnabled = enableLookaside;
97405 sqlite3ExprDelete(db, pWhere);
97406 sqlite3ExprDelete(db, pWhen);
97407 sqlite3ExprListDelete(db, pList);
97408 sqlite3SelectDelete(db, pSelect);
97409 if( db->mallocFailed==1 ){
97410 fkTriggerDelete(db, pTrigger);
97411 return 0;
97413 assert( pStep!=0 );
97415 switch( action ){
97416 case OE_Restrict:
97417 pStep->op = TK_SELECT;
97418 break;
97419 case OE_Cascade:
97420 if( !pChanges ){
97421 pStep->op = TK_DELETE;
97422 break;
97424 default:
97425 pStep->op = TK_UPDATE;
97427 pStep->pTrig = pTrigger;
97428 pTrigger->pSchema = pTab->pSchema;
97429 pTrigger->pTabSchema = pTab->pSchema;
97430 pFKey->apTrigger[iAction] = pTrigger;
97431 pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
97434 return pTrigger;
97438 ** This function is called when deleting or updating a row to implement
97439 ** any required CASCADE, SET NULL or SET DEFAULT actions.
97441 SQLITE_PRIVATE void sqlite3FkActions(
97442 Parse *pParse, /* Parse context */
97443 Table *pTab, /* Table being updated or deleted from */
97444 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
97445 int regOld, /* Address of array containing old row */
97446 int *aChange, /* Array indicating UPDATEd columns (or 0) */
97447 int bChngRowid /* True if rowid is UPDATEd */
97449 /* If foreign-key support is enabled, iterate through all FKs that
97450 ** refer to table pTab. If there is an action associated with the FK
97451 ** for this operation (either update or delete), invoke the associated
97452 ** trigger sub-program. */
97453 if( pParse->db->flags&SQLITE_ForeignKeys ){
97454 FKey *pFKey; /* Iterator variable */
97455 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
97456 if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
97457 Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
97458 if( pAct ){
97459 sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
97466 #endif /* ifndef SQLITE_OMIT_TRIGGER */
97469 ** Free all memory associated with foreign key definitions attached to
97470 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
97471 ** hash table.
97473 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
97474 FKey *pFKey; /* Iterator variable */
97475 FKey *pNext; /* Copy of pFKey->pNextFrom */
97477 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
97478 for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
97480 /* Remove the FK from the fkeyHash hash table. */
97481 if( !db || db->pnBytesFreed==0 ){
97482 if( pFKey->pPrevTo ){
97483 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
97484 }else{
97485 void *p = (void *)pFKey->pNextTo;
97486 const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
97487 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
97489 if( pFKey->pNextTo ){
97490 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
97494 /* EV: R-30323-21917 Each foreign key constraint in SQLite is
97495 ** classified as either immediate or deferred.
97497 assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
97499 /* Delete any triggers created to implement actions for this FK. */
97500 #ifndef SQLITE_OMIT_TRIGGER
97501 fkTriggerDelete(db, pFKey->apTrigger[0]);
97502 fkTriggerDelete(db, pFKey->apTrigger[1]);
97503 #endif
97505 pNext = pFKey->pNextFrom;
97506 sqlite3DbFree(db, pFKey);
97509 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
97511 /************** End of fkey.c ************************************************/
97512 /************** Begin file insert.c ******************************************/
97514 ** 2001 September 15
97516 ** The author disclaims copyright to this source code. In place of
97517 ** a legal notice, here is a blessing:
97519 ** May you do good and not evil.
97520 ** May you find forgiveness for yourself and forgive others.
97521 ** May you share freely, never taking more than you give.
97523 *************************************************************************
97524 ** This file contains C code routines that are called by the parser
97525 ** to handle INSERT statements in SQLite.
97529 ** Generate code that will
97531 ** (1) acquire a lock for table pTab then
97532 ** (2) open pTab as cursor iCur.
97534 ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
97535 ** for that table that is actually opened.
97537 SQLITE_PRIVATE void sqlite3OpenTable(
97538 Parse *pParse, /* Generate code into this VDBE */
97539 int iCur, /* The cursor number of the table */
97540 int iDb, /* The database index in sqlite3.aDb[] */
97541 Table *pTab, /* The table to be opened */
97542 int opcode /* OP_OpenRead or OP_OpenWrite */
97544 Vdbe *v;
97545 assert( !IsVirtual(pTab) );
97546 v = sqlite3GetVdbe(pParse);
97547 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
97548 sqlite3TableLock(pParse, iDb, pTab->tnum,
97549 (opcode==OP_OpenWrite)?1:0, pTab->zName);
97550 if( HasRowid(pTab) ){
97551 sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
97552 VdbeComment((v, "%s", pTab->zName));
97553 }else{
97554 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
97555 assert( pPk!=0 );
97556 assert( pPk->tnum=pTab->tnum );
97557 sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
97558 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
97559 VdbeComment((v, "%s", pTab->zName));
97564 ** Return a pointer to the column affinity string associated with index
97565 ** pIdx. A column affinity string has one character for each column in
97566 ** the table, according to the affinity of the column:
97568 ** Character Column affinity
97569 ** ------------------------------
97570 ** 'A' NONE
97571 ** 'B' TEXT
97572 ** 'C' NUMERIC
97573 ** 'D' INTEGER
97574 ** 'F' REAL
97576 ** An extra 'D' is appended to the end of the string to cover the
97577 ** rowid that appears as the last column in every index.
97579 ** Memory for the buffer containing the column index affinity string
97580 ** is managed along with the rest of the Index structure. It will be
97581 ** released when sqlite3DeleteIndex() is called.
97583 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
97584 if( !pIdx->zColAff ){
97585 /* The first time a column affinity string for a particular index is
97586 ** required, it is allocated and populated here. It is then stored as
97587 ** a member of the Index structure for subsequent use.
97589 ** The column affinity string will eventually be deleted by
97590 ** sqliteDeleteIndex() when the Index structure itself is cleaned
97591 ** up.
97593 int n;
97594 Table *pTab = pIdx->pTable;
97595 sqlite3 *db = sqlite3VdbeDb(v);
97596 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
97597 if( !pIdx->zColAff ){
97598 db->mallocFailed = 1;
97599 return 0;
97601 for(n=0; n<pIdx->nColumn; n++){
97602 i16 x = pIdx->aiColumn[n];
97603 pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
97605 pIdx->zColAff[n] = 0;
97608 return pIdx->zColAff;
97612 ** Compute the affinity string for table pTab, if it has not already been
97613 ** computed. As an optimization, omit trailing SQLITE_AFF_NONE affinities.
97615 ** If the affinity exists (if it is no entirely SQLITE_AFF_NONE values) and
97616 ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
97617 ** for register iReg and following. Or if affinities exists and iReg==0,
97618 ** then just set the P4 operand of the previous opcode (which should be
97619 ** an OP_MakeRecord) to the affinity string.
97621 ** A column affinity string has one character per column:
97623 ** Character Column affinity
97624 ** ------------------------------
97625 ** 'A' NONE
97626 ** 'B' TEXT
97627 ** 'C' NUMERIC
97628 ** 'D' INTEGER
97629 ** 'E' REAL
97631 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
97632 int i;
97633 char *zColAff = pTab->zColAff;
97634 if( zColAff==0 ){
97635 sqlite3 *db = sqlite3VdbeDb(v);
97636 zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
97637 if( !zColAff ){
97638 db->mallocFailed = 1;
97639 return;
97642 for(i=0; i<pTab->nCol; i++){
97643 zColAff[i] = pTab->aCol[i].affinity;
97646 zColAff[i--] = 0;
97647 }while( i>=0 && zColAff[i]==SQLITE_AFF_NONE );
97648 pTab->zColAff = zColAff;
97650 i = sqlite3Strlen30(zColAff);
97651 if( i ){
97652 if( iReg ){
97653 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
97654 }else{
97655 sqlite3VdbeChangeP4(v, -1, zColAff, i);
97661 ** Return non-zero if the table pTab in database iDb or any of its indices
97662 ** have been opened at any point in the VDBE program. This is used to see if
97663 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
97664 ** run without using a temporary table for the results of the SELECT.
97666 static int readsTable(Parse *p, int iDb, Table *pTab){
97667 Vdbe *v = sqlite3GetVdbe(p);
97668 int i;
97669 int iEnd = sqlite3VdbeCurrentAddr(v);
97670 #ifndef SQLITE_OMIT_VIRTUALTABLE
97671 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
97672 #endif
97674 for(i=1; i<iEnd; i++){
97675 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
97676 assert( pOp!=0 );
97677 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
97678 Index *pIndex;
97679 int tnum = pOp->p2;
97680 if( tnum==pTab->tnum ){
97681 return 1;
97683 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
97684 if( tnum==pIndex->tnum ){
97685 return 1;
97689 #ifndef SQLITE_OMIT_VIRTUALTABLE
97690 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
97691 assert( pOp->p4.pVtab!=0 );
97692 assert( pOp->p4type==P4_VTAB );
97693 return 1;
97695 #endif
97697 return 0;
97700 #ifndef SQLITE_OMIT_AUTOINCREMENT
97702 ** Locate or create an AutoincInfo structure associated with table pTab
97703 ** which is in database iDb. Return the register number for the register
97704 ** that holds the maximum rowid.
97706 ** There is at most one AutoincInfo structure per table even if the
97707 ** same table is autoincremented multiple times due to inserts within
97708 ** triggers. A new AutoincInfo structure is created if this is the
97709 ** first use of table pTab. On 2nd and subsequent uses, the original
97710 ** AutoincInfo structure is used.
97712 ** Three memory locations are allocated:
97714 ** (1) Register to hold the name of the pTab table.
97715 ** (2) Register to hold the maximum ROWID of pTab.
97716 ** (3) Register to hold the rowid in sqlite_sequence of pTab
97718 ** The 2nd register is the one that is returned. That is all the
97719 ** insert routine needs to know about.
97721 static int autoIncBegin(
97722 Parse *pParse, /* Parsing context */
97723 int iDb, /* Index of the database holding pTab */
97724 Table *pTab /* The table we are writing to */
97726 int memId = 0; /* Register holding maximum rowid */
97727 if( pTab->tabFlags & TF_Autoincrement ){
97728 Parse *pToplevel = sqlite3ParseToplevel(pParse);
97729 AutoincInfo *pInfo;
97731 pInfo = pToplevel->pAinc;
97732 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
97733 if( pInfo==0 ){
97734 pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
97735 if( pInfo==0 ) return 0;
97736 pInfo->pNext = pToplevel->pAinc;
97737 pToplevel->pAinc = pInfo;
97738 pInfo->pTab = pTab;
97739 pInfo->iDb = iDb;
97740 pToplevel->nMem++; /* Register to hold name of table */
97741 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
97742 pToplevel->nMem++; /* Rowid in sqlite_sequence */
97744 memId = pInfo->regCtr;
97746 return memId;
97750 ** This routine generates code that will initialize all of the
97751 ** register used by the autoincrement tracker.
97753 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
97754 AutoincInfo *p; /* Information about an AUTOINCREMENT */
97755 sqlite3 *db = pParse->db; /* The database connection */
97756 Db *pDb; /* Database only autoinc table */
97757 int memId; /* Register holding max rowid */
97758 int addr; /* A VDBE address */
97759 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
97761 /* This routine is never called during trigger-generation. It is
97762 ** only called from the top-level */
97763 assert( pParse->pTriggerTab==0 );
97764 assert( pParse==sqlite3ParseToplevel(pParse) );
97766 assert( v ); /* We failed long ago if this is not so */
97767 for(p = pParse->pAinc; p; p = p->pNext){
97768 pDb = &db->aDb[p->iDb];
97769 memId = p->regCtr;
97770 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
97771 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
97772 sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
97773 addr = sqlite3VdbeCurrentAddr(v);
97774 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
97775 sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
97776 sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
97777 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
97778 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
97779 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
97780 sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
97781 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
97782 sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
97783 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
97784 sqlite3VdbeAddOp0(v, OP_Close);
97789 ** Update the maximum rowid for an autoincrement calculation.
97791 ** This routine should be called when the top of the stack holds a
97792 ** new rowid that is about to be inserted. If that new rowid is
97793 ** larger than the maximum rowid in the memId memory cell, then the
97794 ** memory cell is updated. The stack is unchanged.
97796 static void autoIncStep(Parse *pParse, int memId, int regRowid){
97797 if( memId>0 ){
97798 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
97803 ** This routine generates the code needed to write autoincrement
97804 ** maximum rowid values back into the sqlite_sequence register.
97805 ** Every statement that might do an INSERT into an autoincrement
97806 ** table (either directly or through triggers) needs to call this
97807 ** routine just before the "exit" code.
97809 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
97810 AutoincInfo *p;
97811 Vdbe *v = pParse->pVdbe;
97812 sqlite3 *db = pParse->db;
97814 assert( v );
97815 for(p = pParse->pAinc; p; p = p->pNext){
97816 Db *pDb = &db->aDb[p->iDb];
97817 int j1;
97818 int iRec;
97819 int memId = p->regCtr;
97821 iRec = sqlite3GetTempReg(pParse);
97822 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
97823 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
97824 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
97825 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
97826 sqlite3VdbeJumpHere(v, j1);
97827 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
97828 sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
97829 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
97830 sqlite3VdbeAddOp0(v, OP_Close);
97831 sqlite3ReleaseTempReg(pParse, iRec);
97834 #else
97836 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
97837 ** above are all no-ops
97839 # define autoIncBegin(A,B,C) (0)
97840 # define autoIncStep(A,B,C)
97841 #endif /* SQLITE_OMIT_AUTOINCREMENT */
97844 /* Forward declaration */
97845 static int xferOptimization(
97846 Parse *pParse, /* Parser context */
97847 Table *pDest, /* The table we are inserting into */
97848 Select *pSelect, /* A SELECT statement to use as the data source */
97849 int onError, /* How to handle constraint errors */
97850 int iDbDest /* The database of pDest */
97854 ** This routine is called to handle SQL of the following forms:
97856 ** insert into TABLE (IDLIST) values(EXPRLIST)
97857 ** insert into TABLE (IDLIST) select
97859 ** The IDLIST following the table name is always optional. If omitted,
97860 ** then a list of all columns for the table is substituted. The IDLIST
97861 ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
97863 ** The pList parameter holds EXPRLIST in the first form of the INSERT
97864 ** statement above, and pSelect is NULL. For the second form, pList is
97865 ** NULL and pSelect is a pointer to the select statement used to generate
97866 ** data for the insert.
97868 ** The code generated follows one of four templates. For a simple
97869 ** insert with data coming from a VALUES clause, the code executes
97870 ** once straight down through. Pseudo-code follows (we call this
97871 ** the "1st template"):
97873 ** open write cursor to <table> and its indices
97874 ** put VALUES clause expressions into registers
97875 ** write the resulting record into <table>
97876 ** cleanup
97878 ** The three remaining templates assume the statement is of the form
97880 ** INSERT INTO <table> SELECT ...
97882 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
97883 ** in other words if the SELECT pulls all columns from a single table
97884 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
97885 ** if <table2> and <table1> are distinct tables but have identical
97886 ** schemas, including all the same indices, then a special optimization
97887 ** is invoked that copies raw records from <table2> over to <table1>.
97888 ** See the xferOptimization() function for the implementation of this
97889 ** template. This is the 2nd template.
97891 ** open a write cursor to <table>
97892 ** open read cursor on <table2>
97893 ** transfer all records in <table2> over to <table>
97894 ** close cursors
97895 ** foreach index on <table>
97896 ** open a write cursor on the <table> index
97897 ** open a read cursor on the corresponding <table2> index
97898 ** transfer all records from the read to the write cursors
97899 ** close cursors
97900 ** end foreach
97902 ** The 3rd template is for when the second template does not apply
97903 ** and the SELECT clause does not read from <table> at any time.
97904 ** The generated code follows this template:
97906 ** X <- A
97907 ** goto B
97908 ** A: setup for the SELECT
97909 ** loop over the rows in the SELECT
97910 ** load values into registers R..R+n
97911 ** yield X
97912 ** end loop
97913 ** cleanup after the SELECT
97914 ** end-coroutine X
97915 ** B: open write cursor to <table> and its indices
97916 ** C: yield X, at EOF goto D
97917 ** insert the select result into <table> from R..R+n
97918 ** goto C
97919 ** D: cleanup
97921 ** The 4th template is used if the insert statement takes its
97922 ** values from a SELECT but the data is being inserted into a table
97923 ** that is also read as part of the SELECT. In the third form,
97924 ** we have to use an intermediate table to store the results of
97925 ** the select. The template is like this:
97927 ** X <- A
97928 ** goto B
97929 ** A: setup for the SELECT
97930 ** loop over the tables in the SELECT
97931 ** load value into register R..R+n
97932 ** yield X
97933 ** end loop
97934 ** cleanup after the SELECT
97935 ** end co-routine R
97936 ** B: open temp table
97937 ** L: yield X, at EOF goto M
97938 ** insert row from R..R+n into temp table
97939 ** goto L
97940 ** M: open write cursor to <table> and its indices
97941 ** rewind temp table
97942 ** C: loop over rows of intermediate table
97943 ** transfer values form intermediate table into <table>
97944 ** end loop
97945 ** D: cleanup
97947 SQLITE_PRIVATE void sqlite3Insert(
97948 Parse *pParse, /* Parser context */
97949 SrcList *pTabList, /* Name of table into which we are inserting */
97950 Select *pSelect, /* A SELECT statement to use as the data source */
97951 IdList *pColumn, /* Column names corresponding to IDLIST. */
97952 int onError /* How to handle constraint errors */
97954 sqlite3 *db; /* The main database structure */
97955 Table *pTab; /* The table to insert into. aka TABLE */
97956 char *zTab; /* Name of the table into which we are inserting */
97957 const char *zDb; /* Name of the database holding this table */
97958 int i, j, idx; /* Loop counters */
97959 Vdbe *v; /* Generate code into this virtual machine */
97960 Index *pIdx; /* For looping over indices of the table */
97961 int nColumn; /* Number of columns in the data */
97962 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
97963 int iDataCur = 0; /* VDBE cursor that is the main data repository */
97964 int iIdxCur = 0; /* First index cursor */
97965 int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
97966 int endOfLoop; /* Label for the end of the insertion loop */
97967 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
97968 int addrInsTop = 0; /* Jump to label "D" */
97969 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
97970 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
97971 int iDb; /* Index of database holding TABLE */
97972 Db *pDb; /* The database containing table being inserted into */
97973 u8 useTempTable = 0; /* Store SELECT results in intermediate table */
97974 u8 appendFlag = 0; /* True if the insert is likely to be an append */
97975 u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
97976 u8 bIdListInOrder = 1; /* True if IDLIST is in table order */
97977 ExprList *pList = 0; /* List of VALUES() to be inserted */
97979 /* Register allocations */
97980 int regFromSelect = 0;/* Base register for data coming from SELECT */
97981 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
97982 int regRowCount = 0; /* Memory cell used for the row counter */
97983 int regIns; /* Block of regs holding rowid+data being inserted */
97984 int regRowid; /* registers holding insert rowid */
97985 int regData; /* register holding first column to insert */
97986 int *aRegIdx = 0; /* One register allocated to each index */
97988 #ifndef SQLITE_OMIT_TRIGGER
97989 int isView; /* True if attempting to insert into a view */
97990 Trigger *pTrigger; /* List of triggers on pTab, if required */
97991 int tmask; /* Mask of trigger times */
97992 #endif
97994 db = pParse->db;
97995 memset(&dest, 0, sizeof(dest));
97996 if( pParse->nErr || db->mallocFailed ){
97997 goto insert_cleanup;
98000 /* If the Select object is really just a simple VALUES() list with a
98001 ** single row values (the common case) then keep that one row of values
98002 ** and go ahead and discard the Select object
98004 if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
98005 pList = pSelect->pEList;
98006 pSelect->pEList = 0;
98007 sqlite3SelectDelete(db, pSelect);
98008 pSelect = 0;
98011 /* Locate the table into which we will be inserting new information.
98013 assert( pTabList->nSrc==1 );
98014 zTab = pTabList->a[0].zName;
98015 if( NEVER(zTab==0) ) goto insert_cleanup;
98016 pTab = sqlite3SrcListLookup(pParse, pTabList);
98017 if( pTab==0 ){
98018 goto insert_cleanup;
98020 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
98021 assert( iDb<db->nDb );
98022 pDb = &db->aDb[iDb];
98023 zDb = pDb->zName;
98024 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
98025 goto insert_cleanup;
98027 withoutRowid = !HasRowid(pTab);
98029 /* Figure out if we have any triggers and if the table being
98030 ** inserted into is a view
98032 #ifndef SQLITE_OMIT_TRIGGER
98033 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
98034 isView = pTab->pSelect!=0;
98035 #else
98036 # define pTrigger 0
98037 # define tmask 0
98038 # define isView 0
98039 #endif
98040 #ifdef SQLITE_OMIT_VIEW
98041 # undef isView
98042 # define isView 0
98043 #endif
98044 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
98046 /* If pTab is really a view, make sure it has been initialized.
98047 ** ViewGetColumnNames() is a no-op if pTab is not a view.
98049 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
98050 goto insert_cleanup;
98053 /* Cannot insert into a read-only table.
98055 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
98056 goto insert_cleanup;
98059 /* Allocate a VDBE
98061 v = sqlite3GetVdbe(pParse);
98062 if( v==0 ) goto insert_cleanup;
98063 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
98064 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
98066 #ifndef SQLITE_OMIT_XFER_OPT
98067 /* If the statement is of the form
98069 ** INSERT INTO <table1> SELECT * FROM <table2>;
98071 ** Then special optimizations can be applied that make the transfer
98072 ** very fast and which reduce fragmentation of indices.
98074 ** This is the 2nd template.
98076 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
98077 assert( !pTrigger );
98078 assert( pList==0 );
98079 goto insert_end;
98081 #endif /* SQLITE_OMIT_XFER_OPT */
98083 /* If this is an AUTOINCREMENT table, look up the sequence number in the
98084 ** sqlite_sequence table and store it in memory cell regAutoinc.
98086 regAutoinc = autoIncBegin(pParse, iDb, pTab);
98088 /* Allocate registers for holding the rowid of the new row,
98089 ** the content of the new row, and the assembled row record.
98091 regRowid = regIns = pParse->nMem+1;
98092 pParse->nMem += pTab->nCol + 1;
98093 if( IsVirtual(pTab) ){
98094 regRowid++;
98095 pParse->nMem++;
98097 regData = regRowid+1;
98099 /* If the INSERT statement included an IDLIST term, then make sure
98100 ** all elements of the IDLIST really are columns of the table and
98101 ** remember the column indices.
98103 ** If the table has an INTEGER PRIMARY KEY column and that column
98104 ** is named in the IDLIST, then record in the ipkColumn variable
98105 ** the index into IDLIST of the primary key column. ipkColumn is
98106 ** the index of the primary key as it appears in IDLIST, not as
98107 ** is appears in the original table. (The index of the INTEGER
98108 ** PRIMARY KEY in the original table is pTab->iPKey.)
98110 if( pColumn ){
98111 for(i=0; i<pColumn->nId; i++){
98112 pColumn->a[i].idx = -1;
98114 for(i=0; i<pColumn->nId; i++){
98115 for(j=0; j<pTab->nCol; j++){
98116 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
98117 pColumn->a[i].idx = j;
98118 if( i!=j ) bIdListInOrder = 0;
98119 if( j==pTab->iPKey ){
98120 ipkColumn = i; assert( !withoutRowid );
98122 break;
98125 if( j>=pTab->nCol ){
98126 if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
98127 ipkColumn = i;
98128 bIdListInOrder = 0;
98129 }else{
98130 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
98131 pTabList, 0, pColumn->a[i].zName);
98132 pParse->checkSchema = 1;
98133 goto insert_cleanup;
98139 /* Figure out how many columns of data are supplied. If the data
98140 ** is coming from a SELECT statement, then generate a co-routine that
98141 ** produces a single row of the SELECT on each invocation. The
98142 ** co-routine is the common header to the 3rd and 4th templates.
98144 if( pSelect ){
98145 /* Data is coming from a SELECT. Generate a co-routine to run the SELECT */
98146 int regYield; /* Register holding co-routine entry-point */
98147 int addrTop; /* Top of the co-routine */
98148 int rc; /* Result code */
98150 regYield = ++pParse->nMem;
98151 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
98152 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
98153 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
98154 dest.iSdst = bIdListInOrder ? regData : 0;
98155 dest.nSdst = pTab->nCol;
98156 rc = sqlite3Select(pParse, pSelect, &dest);
98157 regFromSelect = dest.iSdst;
98158 assert( pParse->nErr==0 || rc );
98159 if( rc || db->mallocFailed ) goto insert_cleanup;
98160 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
98161 sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
98162 assert( pSelect->pEList );
98163 nColumn = pSelect->pEList->nExpr;
98165 /* Set useTempTable to TRUE if the result of the SELECT statement
98166 ** should be written into a temporary table (template 4). Set to
98167 ** FALSE if each output row of the SELECT can be written directly into
98168 ** the destination table (template 3).
98170 ** A temp table must be used if the table being updated is also one
98171 ** of the tables being read by the SELECT statement. Also use a
98172 ** temp table in the case of row triggers.
98174 if( pTrigger || readsTable(pParse, iDb, pTab) ){
98175 useTempTable = 1;
98178 if( useTempTable ){
98179 /* Invoke the coroutine to extract information from the SELECT
98180 ** and add it to a transient table srcTab. The code generated
98181 ** here is from the 4th template:
98183 ** B: open temp table
98184 ** L: yield X, goto M at EOF
98185 ** insert row from R..R+n into temp table
98186 ** goto L
98187 ** M: ...
98189 int regRec; /* Register to hold packed record */
98190 int regTempRowid; /* Register to hold temp table ROWID */
98191 int addrL; /* Label "L" */
98193 srcTab = pParse->nTab++;
98194 regRec = sqlite3GetTempReg(pParse);
98195 regTempRowid = sqlite3GetTempReg(pParse);
98196 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
98197 addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
98198 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
98199 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
98200 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
98201 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrL);
98202 sqlite3VdbeJumpHere(v, addrL);
98203 sqlite3ReleaseTempReg(pParse, regRec);
98204 sqlite3ReleaseTempReg(pParse, regTempRowid);
98206 }else{
98207 /* This is the case if the data for the INSERT is coming from a VALUES
98208 ** clause
98210 NameContext sNC;
98211 memset(&sNC, 0, sizeof(sNC));
98212 sNC.pParse = pParse;
98213 srcTab = -1;
98214 assert( useTempTable==0 );
98215 nColumn = pList ? pList->nExpr : 0;
98216 for(i=0; i<nColumn; i++){
98217 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
98218 goto insert_cleanup;
98223 /* If there is no IDLIST term but the table has an integer primary
98224 ** key, the set the ipkColumn variable to the integer primary key
98225 ** column index in the original table definition.
98227 if( pColumn==0 && nColumn>0 ){
98228 ipkColumn = pTab->iPKey;
98231 /* Make sure the number of columns in the source data matches the number
98232 ** of columns to be inserted into the table.
98234 if( IsVirtual(pTab) ){
98235 for(i=0; i<pTab->nCol; i++){
98236 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
98239 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
98240 sqlite3ErrorMsg(pParse,
98241 "table %S has %d columns but %d values were supplied",
98242 pTabList, 0, pTab->nCol-nHidden, nColumn);
98243 goto insert_cleanup;
98245 if( pColumn!=0 && nColumn!=pColumn->nId ){
98246 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
98247 goto insert_cleanup;
98250 /* Initialize the count of rows to be inserted
98252 if( db->flags & SQLITE_CountRows ){
98253 regRowCount = ++pParse->nMem;
98254 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
98257 /* If this is not a view, open the table and and all indices */
98258 if( !isView ){
98259 int nIdx;
98260 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
98261 &iDataCur, &iIdxCur);
98262 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
98263 if( aRegIdx==0 ){
98264 goto insert_cleanup;
98266 for(i=0; i<nIdx; i++){
98267 aRegIdx[i] = ++pParse->nMem;
98271 /* This is the top of the main insertion loop */
98272 if( useTempTable ){
98273 /* This block codes the top of loop only. The complete loop is the
98274 ** following pseudocode (template 4):
98276 ** rewind temp table, if empty goto D
98277 ** C: loop over rows of intermediate table
98278 ** transfer values form intermediate table into <table>
98279 ** end loop
98280 ** D: ...
98282 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
98283 addrCont = sqlite3VdbeCurrentAddr(v);
98284 }else if( pSelect ){
98285 /* This block codes the top of loop only. The complete loop is the
98286 ** following pseudocode (template 3):
98288 ** C: yield X, at EOF goto D
98289 ** insert the select result into <table> from R..R+n
98290 ** goto C
98291 ** D: ...
98293 addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
98294 VdbeCoverage(v);
98297 /* Run the BEFORE and INSTEAD OF triggers, if there are any
98299 endOfLoop = sqlite3VdbeMakeLabel(v);
98300 if( tmask & TRIGGER_BEFORE ){
98301 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
98303 /* build the NEW.* reference row. Note that if there is an INTEGER
98304 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
98305 ** translated into a unique ID for the row. But on a BEFORE trigger,
98306 ** we do not know what the unique ID will be (because the insert has
98307 ** not happened yet) so we substitute a rowid of -1
98309 if( ipkColumn<0 ){
98310 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
98311 }else{
98312 int j1;
98313 assert( !withoutRowid );
98314 if( useTempTable ){
98315 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
98316 }else{
98317 assert( pSelect==0 ); /* Otherwise useTempTable is true */
98318 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
98320 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
98321 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
98322 sqlite3VdbeJumpHere(v, j1);
98323 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
98326 /* Cannot have triggers on a virtual table. If it were possible,
98327 ** this block would have to account for hidden column.
98329 assert( !IsVirtual(pTab) );
98331 /* Create the new column data
98333 for(i=0; i<pTab->nCol; i++){
98334 if( pColumn==0 ){
98335 j = i;
98336 }else{
98337 for(j=0; j<pColumn->nId; j++){
98338 if( pColumn->a[j].idx==i ) break;
98341 if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
98342 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
98343 }else if( useTempTable ){
98344 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
98345 }else{
98346 assert( pSelect==0 ); /* Otherwise useTempTable is true */
98347 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
98351 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
98352 ** do not attempt any conversions before assembling the record.
98353 ** If this is a real table, attempt conversions as required by the
98354 ** table column affinities.
98356 if( !isView ){
98357 sqlite3TableAffinity(v, pTab, regCols+1);
98360 /* Fire BEFORE or INSTEAD OF triggers */
98361 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
98362 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
98364 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
98367 /* Compute the content of the next row to insert into a range of
98368 ** registers beginning at regIns.
98370 if( !isView ){
98371 if( IsVirtual(pTab) ){
98372 /* The row that the VUpdate opcode will delete: none */
98373 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
98375 if( ipkColumn>=0 ){
98376 if( useTempTable ){
98377 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
98378 }else if( pSelect ){
98379 sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
98380 }else{
98381 VdbeOp *pOp;
98382 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
98383 pOp = sqlite3VdbeGetOp(v, -1);
98384 if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
98385 appendFlag = 1;
98386 pOp->opcode = OP_NewRowid;
98387 pOp->p1 = iDataCur;
98388 pOp->p2 = regRowid;
98389 pOp->p3 = regAutoinc;
98392 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
98393 ** to generate a unique primary key value.
98395 if( !appendFlag ){
98396 int j1;
98397 if( !IsVirtual(pTab) ){
98398 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
98399 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
98400 sqlite3VdbeJumpHere(v, j1);
98401 }else{
98402 j1 = sqlite3VdbeCurrentAddr(v);
98403 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); VdbeCoverage(v);
98405 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
98407 }else if( IsVirtual(pTab) || withoutRowid ){
98408 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
98409 }else{
98410 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
98411 appendFlag = 1;
98413 autoIncStep(pParse, regAutoinc, regRowid);
98415 /* Compute data for all columns of the new entry, beginning
98416 ** with the first column.
98418 nHidden = 0;
98419 for(i=0; i<pTab->nCol; i++){
98420 int iRegStore = regRowid+1+i;
98421 if( i==pTab->iPKey ){
98422 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
98423 ** Whenever this column is read, the rowid will be substituted
98424 ** in its place. Hence, fill this column with a NULL to avoid
98425 ** taking up data space with information that will never be used.
98426 ** As there may be shallow copies of this value, make it a soft-NULL */
98427 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
98428 continue;
98430 if( pColumn==0 ){
98431 if( IsHiddenColumn(&pTab->aCol[i]) ){
98432 assert( IsVirtual(pTab) );
98433 j = -1;
98434 nHidden++;
98435 }else{
98436 j = i - nHidden;
98438 }else{
98439 for(j=0; j<pColumn->nId; j++){
98440 if( pColumn->a[j].idx==i ) break;
98443 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
98444 sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
98445 }else if( useTempTable ){
98446 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
98447 }else if( pSelect ){
98448 if( regFromSelect!=regData ){
98449 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
98451 }else{
98452 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
98456 /* Generate code to check constraints and generate index keys and
98457 ** do the insertion.
98459 #ifndef SQLITE_OMIT_VIRTUALTABLE
98460 if( IsVirtual(pTab) ){
98461 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
98462 sqlite3VtabMakeWritable(pParse, pTab);
98463 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
98464 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
98465 sqlite3MayAbort(pParse);
98466 }else
98467 #endif
98469 int isReplace; /* Set to true if constraints may cause a replace */
98470 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
98471 regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
98473 sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
98474 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
98475 regIns, aRegIdx, 0, appendFlag, isReplace==0);
98479 /* Update the count of rows that are inserted
98481 if( (db->flags & SQLITE_CountRows)!=0 ){
98482 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
98485 if( pTrigger ){
98486 /* Code AFTER triggers */
98487 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
98488 pTab, regData-2-pTab->nCol, onError, endOfLoop);
98491 /* The bottom of the main insertion loop, if the data source
98492 ** is a SELECT statement.
98494 sqlite3VdbeResolveLabel(v, endOfLoop);
98495 if( useTempTable ){
98496 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
98497 sqlite3VdbeJumpHere(v, addrInsTop);
98498 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
98499 }else if( pSelect ){
98500 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
98501 sqlite3VdbeJumpHere(v, addrInsTop);
98504 if( !IsVirtual(pTab) && !isView ){
98505 /* Close all tables opened */
98506 if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
98507 for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
98508 sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
98512 insert_end:
98513 /* Update the sqlite_sequence table by storing the content of the
98514 ** maximum rowid counter values recorded while inserting into
98515 ** autoincrement tables.
98517 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
98518 sqlite3AutoincrementEnd(pParse);
98522 ** Return the number of rows inserted. If this routine is
98523 ** generating code because of a call to sqlite3NestedParse(), do not
98524 ** invoke the callback function.
98526 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
98527 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
98528 sqlite3VdbeSetNumCols(v, 1);
98529 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
98532 insert_cleanup:
98533 sqlite3SrcListDelete(db, pTabList);
98534 sqlite3ExprListDelete(db, pList);
98535 sqlite3SelectDelete(db, pSelect);
98536 sqlite3IdListDelete(db, pColumn);
98537 sqlite3DbFree(db, aRegIdx);
98540 /* Make sure "isView" and other macros defined above are undefined. Otherwise
98541 ** they may interfere with compilation of other functions in this file
98542 ** (or in another file, if this file becomes part of the amalgamation). */
98543 #ifdef isView
98544 #undef isView
98545 #endif
98546 #ifdef pTrigger
98547 #undef pTrigger
98548 #endif
98549 #ifdef tmask
98550 #undef tmask
98551 #endif
98554 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
98555 ** on table pTab.
98557 ** The regNewData parameter is the first register in a range that contains
98558 ** the data to be inserted or the data after the update. There will be
98559 ** pTab->nCol+1 registers in this range. The first register (the one
98560 ** that regNewData points to) will contain the new rowid, or NULL in the
98561 ** case of a WITHOUT ROWID table. The second register in the range will
98562 ** contain the content of the first table column. The third register will
98563 ** contain the content of the second table column. And so forth.
98565 ** The regOldData parameter is similar to regNewData except that it contains
98566 ** the data prior to an UPDATE rather than afterwards. regOldData is zero
98567 ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
98568 ** checking regOldData for zero.
98570 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
98571 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
98572 ** might be modified by the UPDATE. If pkChng is false, then the key of
98573 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
98575 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
98576 ** was explicitly specified as part of the INSERT statement. If pkChng
98577 ** is zero, it means that the either rowid is computed automatically or
98578 ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
98579 ** pkChng will only be true if the INSERT statement provides an integer
98580 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
98582 ** The code generated by this routine will store new index entries into
98583 ** registers identified by aRegIdx[]. No index entry is created for
98584 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
98585 ** the same as the order of indices on the linked list of indices
98586 ** at pTab->pIndex.
98588 ** The caller must have already opened writeable cursors on the main
98589 ** table and all applicable indices (that is to say, all indices for which
98590 ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
98591 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
98592 ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
98593 ** for the first index in the pTab->pIndex list. Cursors for other indices
98594 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
98596 ** This routine also generates code to check constraints. NOT NULL,
98597 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
98598 ** then the appropriate action is performed. There are five possible
98599 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
98601 ** Constraint type Action What Happens
98602 ** --------------- ---------- ----------------------------------------
98603 ** any ROLLBACK The current transaction is rolled back and
98604 ** sqlite3_step() returns immediately with a
98605 ** return code of SQLITE_CONSTRAINT.
98607 ** any ABORT Back out changes from the current command
98608 ** only (do not do a complete rollback) then
98609 ** cause sqlite3_step() to return immediately
98610 ** with SQLITE_CONSTRAINT.
98612 ** any FAIL Sqlite3_step() returns immediately with a
98613 ** return code of SQLITE_CONSTRAINT. The
98614 ** transaction is not rolled back and any
98615 ** changes to prior rows are retained.
98617 ** any IGNORE The attempt in insert or update the current
98618 ** row is skipped, without throwing an error.
98619 ** Processing continues with the next row.
98620 ** (There is an immediate jump to ignoreDest.)
98622 ** NOT NULL REPLACE The NULL value is replace by the default
98623 ** value for that column. If the default value
98624 ** is NULL, the action is the same as ABORT.
98626 ** UNIQUE REPLACE The other row that conflicts with the row
98627 ** being inserted is removed.
98629 ** CHECK REPLACE Illegal. The results in an exception.
98631 ** Which action to take is determined by the overrideError parameter.
98632 ** Or if overrideError==OE_Default, then the pParse->onError parameter
98633 ** is used. Or if pParse->onError==OE_Default then the onError value
98634 ** for the constraint is used.
98636 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
98637 Parse *pParse, /* The parser context */
98638 Table *pTab, /* The table being inserted or updated */
98639 int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
98640 int iDataCur, /* Canonical data cursor (main table or PK index) */
98641 int iIdxCur, /* First index cursor */
98642 int regNewData, /* First register in a range holding values to insert */
98643 int regOldData, /* Previous content. 0 for INSERTs */
98644 u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
98645 u8 overrideError, /* Override onError to this if not OE_Default */
98646 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
98647 int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
98649 Vdbe *v; /* VDBE under constrution */
98650 Index *pIdx; /* Pointer to one of the indices */
98651 Index *pPk = 0; /* The PRIMARY KEY index */
98652 sqlite3 *db; /* Database connection */
98653 int i; /* loop counter */
98654 int ix; /* Index loop counter */
98655 int nCol; /* Number of columns */
98656 int onError; /* Conflict resolution strategy */
98657 int j1; /* Address of jump instruction */
98658 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
98659 int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
98660 int ipkTop = 0; /* Top of the rowid change constraint check */
98661 int ipkBottom = 0; /* Bottom of the rowid change constraint check */
98662 u8 isUpdate; /* True if this is an UPDATE operation */
98663 u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
98664 int regRowid = -1; /* Register holding ROWID value */
98666 isUpdate = regOldData!=0;
98667 db = pParse->db;
98668 v = sqlite3GetVdbe(pParse);
98669 assert( v!=0 );
98670 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
98671 nCol = pTab->nCol;
98673 /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
98674 ** normal rowid tables. nPkField is the number of key fields in the
98675 ** pPk index or 1 for a rowid table. In other words, nPkField is the
98676 ** number of fields in the true primary key of the table. */
98677 if( HasRowid(pTab) ){
98678 pPk = 0;
98679 nPkField = 1;
98680 }else{
98681 pPk = sqlite3PrimaryKeyIndex(pTab);
98682 nPkField = pPk->nKeyCol;
98685 /* Record that this module has started */
98686 VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
98687 iDataCur, iIdxCur, regNewData, regOldData, pkChng));
98689 /* Test all NOT NULL constraints.
98691 for(i=0; i<nCol; i++){
98692 if( i==pTab->iPKey ){
98693 continue;
98695 onError = pTab->aCol[i].notNull;
98696 if( onError==OE_None ) continue;
98697 if( overrideError!=OE_Default ){
98698 onError = overrideError;
98699 }else if( onError==OE_Default ){
98700 onError = OE_Abort;
98702 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
98703 onError = OE_Abort;
98705 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
98706 || onError==OE_Ignore || onError==OE_Replace );
98707 switch( onError ){
98708 case OE_Abort:
98709 sqlite3MayAbort(pParse);
98710 /* Fall through */
98711 case OE_Rollback:
98712 case OE_Fail: {
98713 char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
98714 pTab->aCol[i].zName);
98715 sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
98716 regNewData+1+i, zMsg, P4_DYNAMIC);
98717 sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
98718 VdbeCoverage(v);
98719 break;
98721 case OE_Ignore: {
98722 sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
98723 VdbeCoverage(v);
98724 break;
98726 default: {
98727 assert( onError==OE_Replace );
98728 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v);
98729 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
98730 sqlite3VdbeJumpHere(v, j1);
98731 break;
98736 /* Test all CHECK constraints
98738 #ifndef SQLITE_OMIT_CHECK
98739 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
98740 ExprList *pCheck = pTab->pCheck;
98741 pParse->ckBase = regNewData+1;
98742 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
98743 for(i=0; i<pCheck->nExpr; i++){
98744 int allOk = sqlite3VdbeMakeLabel(v);
98745 sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
98746 if( onError==OE_Ignore ){
98747 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
98748 }else{
98749 char *zName = pCheck->a[i].zName;
98750 if( zName==0 ) zName = pTab->zName;
98751 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
98752 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
98753 onError, zName, P4_TRANSIENT,
98754 P5_ConstraintCheck);
98756 sqlite3VdbeResolveLabel(v, allOk);
98759 #endif /* !defined(SQLITE_OMIT_CHECK) */
98761 /* If rowid is changing, make sure the new rowid does not previously
98762 ** exist in the table.
98764 if( pkChng && pPk==0 ){
98765 int addrRowidOk = sqlite3VdbeMakeLabel(v);
98767 /* Figure out what action to take in case of a rowid collision */
98768 onError = pTab->keyConf;
98769 if( overrideError!=OE_Default ){
98770 onError = overrideError;
98771 }else if( onError==OE_Default ){
98772 onError = OE_Abort;
98775 if( isUpdate ){
98776 /* pkChng!=0 does not mean that the rowid has change, only that
98777 ** it might have changed. Skip the conflict logic below if the rowid
98778 ** is unchanged. */
98779 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
98780 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
98781 VdbeCoverage(v);
98784 /* If the response to a rowid conflict is REPLACE but the response
98785 ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
98786 ** to defer the running of the rowid conflict checking until after
98787 ** the UNIQUE constraints have run.
98789 if( onError==OE_Replace && overrideError!=OE_Replace ){
98790 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98791 if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
98792 ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
98793 break;
98798 /* Check to see if the new rowid already exists in the table. Skip
98799 ** the following conflict logic if it does not. */
98800 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
98801 VdbeCoverage(v);
98803 /* Generate code that deals with a rowid collision */
98804 switch( onError ){
98805 default: {
98806 onError = OE_Abort;
98807 /* Fall thru into the next case */
98809 case OE_Rollback:
98810 case OE_Abort:
98811 case OE_Fail: {
98812 sqlite3RowidConstraint(pParse, onError, pTab);
98813 break;
98815 case OE_Replace: {
98816 /* If there are DELETE triggers on this table and the
98817 ** recursive-triggers flag is set, call GenerateRowDelete() to
98818 ** remove the conflicting row from the table. This will fire
98819 ** the triggers and remove both the table and index b-tree entries.
98821 ** Otherwise, if there are no triggers or the recursive-triggers
98822 ** flag is not set, but the table has one or more indexes, call
98823 ** GenerateRowIndexDelete(). This removes the index b-tree entries
98824 ** only. The table b-tree entry will be replaced by the new entry
98825 ** when it is inserted.
98827 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
98828 ** also invoke MultiWrite() to indicate that this VDBE may require
98829 ** statement rollback (if the statement is aborted after the delete
98830 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
98831 ** but being more selective here allows statements like:
98833 ** REPLACE INTO t(rowid) VALUES($newrowid)
98835 ** to run without a statement journal if there are no indexes on the
98836 ** table.
98838 Trigger *pTrigger = 0;
98839 if( db->flags&SQLITE_RecTriggers ){
98840 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
98842 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
98843 sqlite3MultiWrite(pParse);
98844 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
98845 regNewData, 1, 0, OE_Replace, 1);
98846 }else if( pTab->pIndex ){
98847 sqlite3MultiWrite(pParse);
98848 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
98850 seenReplace = 1;
98851 break;
98853 case OE_Ignore: {
98854 /*assert( seenReplace==0 );*/
98855 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
98856 break;
98859 sqlite3VdbeResolveLabel(v, addrRowidOk);
98860 if( ipkTop ){
98861 ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
98862 sqlite3VdbeJumpHere(v, ipkTop);
98866 /* Test all UNIQUE constraints by creating entries for each UNIQUE
98867 ** index and making sure that duplicate entries do not already exist.
98868 ** Compute the revised record entries for indices as we go.
98870 ** This loop also handles the case of the PRIMARY KEY index for a
98871 ** WITHOUT ROWID table.
98873 for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
98874 int regIdx; /* Range of registers hold conent for pIdx */
98875 int regR; /* Range of registers holding conflicting PK */
98876 int iThisCur; /* Cursor for this UNIQUE index */
98877 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
98879 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
98880 if( bAffinityDone==0 ){
98881 sqlite3TableAffinity(v, pTab, regNewData+1);
98882 bAffinityDone = 1;
98884 iThisCur = iIdxCur+ix;
98885 addrUniqueOk = sqlite3VdbeMakeLabel(v);
98887 /* Skip partial indices for which the WHERE clause is not true */
98888 if( pIdx->pPartIdxWhere ){
98889 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
98890 pParse->ckBase = regNewData+1;
98891 sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
98892 SQLITE_JUMPIFNULL);
98893 pParse->ckBase = 0;
98896 /* Create a record for this index entry as it should appear after
98897 ** the insert or update. Store that record in the aRegIdx[ix] register
98899 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
98900 for(i=0; i<pIdx->nColumn; i++){
98901 int iField = pIdx->aiColumn[i];
98902 int x;
98903 if( iField<0 || iField==pTab->iPKey ){
98904 if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
98905 x = regNewData;
98906 regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i;
98907 }else{
98908 x = iField + regNewData + 1;
98910 sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
98911 VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
98913 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
98914 VdbeComment((v, "for %s", pIdx->zName));
98915 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
98917 /* In an UPDATE operation, if this index is the PRIMARY KEY index
98918 ** of a WITHOUT ROWID table and there has been no change the
98919 ** primary key, then no collision is possible. The collision detection
98920 ** logic below can all be skipped. */
98921 if( isUpdate && pPk==pIdx && pkChng==0 ){
98922 sqlite3VdbeResolveLabel(v, addrUniqueOk);
98923 continue;
98926 /* Find out what action to take in case there is a uniqueness conflict */
98927 onError = pIdx->onError;
98928 if( onError==OE_None ){
98929 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
98930 sqlite3VdbeResolveLabel(v, addrUniqueOk);
98931 continue; /* pIdx is not a UNIQUE index */
98933 if( overrideError!=OE_Default ){
98934 onError = overrideError;
98935 }else if( onError==OE_Default ){
98936 onError = OE_Abort;
98939 /* Check to see if the new index entry will be unique */
98940 sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
98941 regIdx, pIdx->nKeyCol); VdbeCoverage(v);
98943 /* Generate code to handle collisions */
98944 regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
98945 if( isUpdate || onError==OE_Replace ){
98946 if( HasRowid(pTab) ){
98947 sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
98948 /* Conflict only if the rowid of the existing index entry
98949 ** is different from old-rowid */
98950 if( isUpdate ){
98951 sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
98952 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
98953 VdbeCoverage(v);
98955 }else{
98956 int x;
98957 /* Extract the PRIMARY KEY from the end of the index entry and
98958 ** store it in registers regR..regR+nPk-1 */
98959 if( pIdx!=pPk ){
98960 for(i=0; i<pPk->nKeyCol; i++){
98961 x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
98962 sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
98963 VdbeComment((v, "%s.%s", pTab->zName,
98964 pTab->aCol[pPk->aiColumn[i]].zName));
98967 if( isUpdate ){
98968 /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
98969 ** table, only conflict if the new PRIMARY KEY values are actually
98970 ** different from the old.
98972 ** For a UNIQUE index, only conflict if the PRIMARY KEY values
98973 ** of the matched index row are different from the original PRIMARY
98974 ** KEY values of this row before the update. */
98975 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
98976 int op = OP_Ne;
98977 int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
98979 for(i=0; i<pPk->nKeyCol; i++){
98980 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
98981 x = pPk->aiColumn[i];
98982 if( i==(pPk->nKeyCol-1) ){
98983 addrJump = addrUniqueOk;
98984 op = OP_Eq;
98986 sqlite3VdbeAddOp4(v, op,
98987 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
98989 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
98990 VdbeCoverageIf(v, op==OP_Eq);
98991 VdbeCoverageIf(v, op==OP_Ne);
98997 /* Generate code that executes if the new index entry is not unique */
98998 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
98999 || onError==OE_Ignore || onError==OE_Replace );
99000 switch( onError ){
99001 case OE_Rollback:
99002 case OE_Abort:
99003 case OE_Fail: {
99004 sqlite3UniqueConstraint(pParse, onError, pIdx);
99005 break;
99007 case OE_Ignore: {
99008 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
99009 break;
99011 default: {
99012 Trigger *pTrigger = 0;
99013 assert( onError==OE_Replace );
99014 sqlite3MultiWrite(pParse);
99015 if( db->flags&SQLITE_RecTriggers ){
99016 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
99018 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
99019 regR, nPkField, 0, OE_Replace, pIdx==pPk);
99020 seenReplace = 1;
99021 break;
99024 sqlite3VdbeResolveLabel(v, addrUniqueOk);
99025 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
99026 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
99028 if( ipkTop ){
99029 sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1);
99030 sqlite3VdbeJumpHere(v, ipkBottom);
99033 *pbMayReplace = seenReplace;
99034 VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
99038 ** This routine generates code to finish the INSERT or UPDATE operation
99039 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
99040 ** A consecutive range of registers starting at regNewData contains the
99041 ** rowid and the content to be inserted.
99043 ** The arguments to this routine should be the same as the first six
99044 ** arguments to sqlite3GenerateConstraintChecks.
99046 SQLITE_PRIVATE void sqlite3CompleteInsertion(
99047 Parse *pParse, /* The parser context */
99048 Table *pTab, /* the table into which we are inserting */
99049 int iDataCur, /* Cursor of the canonical data source */
99050 int iIdxCur, /* First index cursor */
99051 int regNewData, /* Range of content */
99052 int *aRegIdx, /* Register used by each index. 0 for unused indices */
99053 int isUpdate, /* True for UPDATE, False for INSERT */
99054 int appendBias, /* True if this is likely to be an append */
99055 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
99057 Vdbe *v; /* Prepared statements under construction */
99058 Index *pIdx; /* An index being inserted or updated */
99059 u8 pik_flags; /* flag values passed to the btree insert */
99060 int regData; /* Content registers (after the rowid) */
99061 int regRec; /* Register holding assembled record for the table */
99062 int i; /* Loop counter */
99063 u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
99065 v = sqlite3GetVdbe(pParse);
99066 assert( v!=0 );
99067 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
99068 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
99069 if( aRegIdx[i]==0 ) continue;
99070 bAffinityDone = 1;
99071 if( pIdx->pPartIdxWhere ){
99072 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
99073 VdbeCoverage(v);
99075 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
99076 pik_flags = 0;
99077 if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
99078 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
99079 assert( pParse->nested==0 );
99080 pik_flags |= OPFLAG_NCHANGE;
99082 if( pik_flags ) sqlite3VdbeChangeP5(v, pik_flags);
99084 if( !HasRowid(pTab) ) return;
99085 regData = regNewData + 1;
99086 regRec = sqlite3GetTempReg(pParse);
99087 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
99088 if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
99089 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
99090 if( pParse->nested ){
99091 pik_flags = 0;
99092 }else{
99093 pik_flags = OPFLAG_NCHANGE;
99094 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
99096 if( appendBias ){
99097 pik_flags |= OPFLAG_APPEND;
99099 if( useSeekResult ){
99100 pik_flags |= OPFLAG_USESEEKRESULT;
99102 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
99103 if( !pParse->nested ){
99104 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
99106 sqlite3VdbeChangeP5(v, pik_flags);
99110 ** Allocate cursors for the pTab table and all its indices and generate
99111 ** code to open and initialized those cursors.
99113 ** The cursor for the object that contains the complete data (normally
99114 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
99115 ** ROWID table) is returned in *piDataCur. The first index cursor is
99116 ** returned in *piIdxCur. The number of indices is returned.
99118 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
99119 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
99120 ** If iBase is negative, then allocate the next available cursor.
99122 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
99123 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
99124 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
99125 ** pTab->pIndex list.
99127 ** If pTab is a virtual table, then this routine is a no-op and the
99128 ** *piDataCur and *piIdxCur values are left uninitialized.
99130 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
99131 Parse *pParse, /* Parsing context */
99132 Table *pTab, /* Table to be opened */
99133 int op, /* OP_OpenRead or OP_OpenWrite */
99134 int iBase, /* Use this for the table cursor, if there is one */
99135 u8 *aToOpen, /* If not NULL: boolean for each table and index */
99136 int *piDataCur, /* Write the database source cursor number here */
99137 int *piIdxCur /* Write the first index cursor number here */
99139 int i;
99140 int iDb;
99141 int iDataCur;
99142 Index *pIdx;
99143 Vdbe *v;
99145 assert( op==OP_OpenRead || op==OP_OpenWrite );
99146 if( IsVirtual(pTab) ){
99147 /* This routine is a no-op for virtual tables. Leave the output
99148 ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
99149 ** can detect if they are used by mistake in the caller. */
99150 return 0;
99152 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
99153 v = sqlite3GetVdbe(pParse);
99154 assert( v!=0 );
99155 if( iBase<0 ) iBase = pParse->nTab;
99156 iDataCur = iBase++;
99157 if( piDataCur ) *piDataCur = iDataCur;
99158 if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
99159 sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
99160 }else{
99161 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
99163 if( piIdxCur ) *piIdxCur = iBase;
99164 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
99165 int iIdxCur = iBase++;
99166 assert( pIdx->pSchema==pTab->pSchema );
99167 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){
99168 *piDataCur = iIdxCur;
99170 if( aToOpen==0 || aToOpen[i+1] ){
99171 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
99172 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
99173 VdbeComment((v, "%s", pIdx->zName));
99176 if( iBase>pParse->nTab ) pParse->nTab = iBase;
99177 return i;
99181 #ifdef SQLITE_TEST
99183 ** The following global variable is incremented whenever the
99184 ** transfer optimization is used. This is used for testing
99185 ** purposes only - to make sure the transfer optimization really
99186 ** is happening when it is supposed to.
99188 SQLITE_API int sqlite3_xferopt_count;
99189 #endif /* SQLITE_TEST */
99192 #ifndef SQLITE_OMIT_XFER_OPT
99194 ** Check to collation names to see if they are compatible.
99196 static int xferCompatibleCollation(const char *z1, const char *z2){
99197 if( z1==0 ){
99198 return z2==0;
99200 if( z2==0 ){
99201 return 0;
99203 return sqlite3StrICmp(z1, z2)==0;
99208 ** Check to see if index pSrc is compatible as a source of data
99209 ** for index pDest in an insert transfer optimization. The rules
99210 ** for a compatible index:
99212 ** * The index is over the same set of columns
99213 ** * The same DESC and ASC markings occurs on all columns
99214 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
99215 ** * The same collating sequence on each column
99216 ** * The index has the exact same WHERE clause
99218 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
99219 int i;
99220 assert( pDest && pSrc );
99221 assert( pDest->pTable!=pSrc->pTable );
99222 if( pDest->nKeyCol!=pSrc->nKeyCol ){
99223 return 0; /* Different number of columns */
99225 if( pDest->onError!=pSrc->onError ){
99226 return 0; /* Different conflict resolution strategies */
99228 for(i=0; i<pSrc->nKeyCol; i++){
99229 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
99230 return 0; /* Different columns indexed */
99232 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
99233 return 0; /* Different sort orders */
99235 if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
99236 return 0; /* Different collating sequences */
99239 if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
99240 return 0; /* Different WHERE clauses */
99243 /* If no test above fails then the indices must be compatible */
99244 return 1;
99248 ** Attempt the transfer optimization on INSERTs of the form
99250 ** INSERT INTO tab1 SELECT * FROM tab2;
99252 ** The xfer optimization transfers raw records from tab2 over to tab1.
99253 ** Columns are not decoded and reassembled, which greatly improves
99254 ** performance. Raw index records are transferred in the same way.
99256 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
99257 ** There are lots of rules for determining compatibility - see comments
99258 ** embedded in the code for details.
99260 ** This routine returns TRUE if the optimization is guaranteed to be used.
99261 ** Sometimes the xfer optimization will only work if the destination table
99262 ** is empty - a factor that can only be determined at run-time. In that
99263 ** case, this routine generates code for the xfer optimization but also
99264 ** does a test to see if the destination table is empty and jumps over the
99265 ** xfer optimization code if the test fails. In that case, this routine
99266 ** returns FALSE so that the caller will know to go ahead and generate
99267 ** an unoptimized transfer. This routine also returns FALSE if there
99268 ** is no chance that the xfer optimization can be applied.
99270 ** This optimization is particularly useful at making VACUUM run faster.
99272 static int xferOptimization(
99273 Parse *pParse, /* Parser context */
99274 Table *pDest, /* The table we are inserting into */
99275 Select *pSelect, /* A SELECT statement to use as the data source */
99276 int onError, /* How to handle constraint errors */
99277 int iDbDest /* The database of pDest */
99279 ExprList *pEList; /* The result set of the SELECT */
99280 Table *pSrc; /* The table in the FROM clause of SELECT */
99281 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
99282 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
99283 int i; /* Loop counter */
99284 int iDbSrc; /* The database of pSrc */
99285 int iSrc, iDest; /* Cursors from source and destination */
99286 int addr1, addr2; /* Loop addresses */
99287 int emptyDestTest = 0; /* Address of test for empty pDest */
99288 int emptySrcTest = 0; /* Address of test for empty pSrc */
99289 Vdbe *v; /* The VDBE we are building */
99290 int regAutoinc; /* Memory register used by AUTOINC */
99291 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
99292 int regData, regRowid; /* Registers holding data and rowid */
99294 if( pSelect==0 ){
99295 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
99297 if( pParse->pWith || pSelect->pWith ){
99298 /* Do not attempt to process this query if there are an WITH clauses
99299 ** attached to it. Proceeding may generate a false "no such table: xxx"
99300 ** error if pSelect reads from a CTE named "xxx". */
99301 return 0;
99303 if( sqlite3TriggerList(pParse, pDest) ){
99304 return 0; /* tab1 must not have triggers */
99306 #ifndef SQLITE_OMIT_VIRTUALTABLE
99307 if( pDest->tabFlags & TF_Virtual ){
99308 return 0; /* tab1 must not be a virtual table */
99310 #endif
99311 if( onError==OE_Default ){
99312 if( pDest->iPKey>=0 ) onError = pDest->keyConf;
99313 if( onError==OE_Default ) onError = OE_Abort;
99315 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
99316 if( pSelect->pSrc->nSrc!=1 ){
99317 return 0; /* FROM clause must have exactly one term */
99319 if( pSelect->pSrc->a[0].pSelect ){
99320 return 0; /* FROM clause cannot contain a subquery */
99322 if( pSelect->pWhere ){
99323 return 0; /* SELECT may not have a WHERE clause */
99325 if( pSelect->pOrderBy ){
99326 return 0; /* SELECT may not have an ORDER BY clause */
99328 /* Do not need to test for a HAVING clause. If HAVING is present but
99329 ** there is no ORDER BY, we will get an error. */
99330 if( pSelect->pGroupBy ){
99331 return 0; /* SELECT may not have a GROUP BY clause */
99333 if( pSelect->pLimit ){
99334 return 0; /* SELECT may not have a LIMIT clause */
99336 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
99337 if( pSelect->pPrior ){
99338 return 0; /* SELECT may not be a compound query */
99340 if( pSelect->selFlags & SF_Distinct ){
99341 return 0; /* SELECT may not be DISTINCT */
99343 pEList = pSelect->pEList;
99344 assert( pEList!=0 );
99345 if( pEList->nExpr!=1 ){
99346 return 0; /* The result set must have exactly one column */
99348 assert( pEList->a[0].pExpr );
99349 if( pEList->a[0].pExpr->op!=TK_ALL ){
99350 return 0; /* The result set must be the special operator "*" */
99353 /* At this point we have established that the statement is of the
99354 ** correct syntactic form to participate in this optimization. Now
99355 ** we have to check the semantics.
99357 pItem = pSelect->pSrc->a;
99358 pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
99359 if( pSrc==0 ){
99360 return 0; /* FROM clause does not contain a real table */
99362 if( pSrc==pDest ){
99363 return 0; /* tab1 and tab2 may not be the same table */
99365 if( HasRowid(pDest)!=HasRowid(pSrc) ){
99366 return 0; /* source and destination must both be WITHOUT ROWID or not */
99368 #ifndef SQLITE_OMIT_VIRTUALTABLE
99369 if( pSrc->tabFlags & TF_Virtual ){
99370 return 0; /* tab2 must not be a virtual table */
99372 #endif
99373 if( pSrc->pSelect ){
99374 return 0; /* tab2 may not be a view */
99376 if( pDest->nCol!=pSrc->nCol ){
99377 return 0; /* Number of columns must be the same in tab1 and tab2 */
99379 if( pDest->iPKey!=pSrc->iPKey ){
99380 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
99382 for(i=0; i<pDest->nCol; i++){
99383 Column *pDestCol = &pDest->aCol[i];
99384 Column *pSrcCol = &pSrc->aCol[i];
99385 if( pDestCol->affinity!=pSrcCol->affinity ){
99386 return 0; /* Affinity must be the same on all columns */
99388 if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){
99389 return 0; /* Collating sequence must be the same on all columns */
99391 if( pDestCol->notNull && !pSrcCol->notNull ){
99392 return 0; /* tab2 must be NOT NULL if tab1 is */
99394 /* Default values for second and subsequent columns need to match. */
99395 if( i>0
99396 && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0)
99397 || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
99399 return 0; /* Default values must be the same for all columns */
99402 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
99403 if( IsUniqueIndex(pDestIdx) ){
99404 destHasUniqueIdx = 1;
99406 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
99407 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
99409 if( pSrcIdx==0 ){
99410 return 0; /* pDestIdx has no corresponding index in pSrc */
99413 #ifndef SQLITE_OMIT_CHECK
99414 if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
99415 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
99417 #endif
99418 #ifndef SQLITE_OMIT_FOREIGN_KEY
99419 /* Disallow the transfer optimization if the destination table constains
99420 ** any foreign key constraints. This is more restrictive than necessary.
99421 ** But the main beneficiary of the transfer optimization is the VACUUM
99422 ** command, and the VACUUM command disables foreign key constraints. So
99423 ** the extra complication to make this rule less restrictive is probably
99424 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
99426 if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
99427 return 0;
99429 #endif
99430 if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
99431 return 0; /* xfer opt does not play well with PRAGMA count_changes */
99434 /* If we get this far, it means that the xfer optimization is at
99435 ** least a possibility, though it might only work if the destination
99436 ** table (tab1) is initially empty.
99438 #ifdef SQLITE_TEST
99439 sqlite3_xferopt_count++;
99440 #endif
99441 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
99442 v = sqlite3GetVdbe(pParse);
99443 sqlite3CodeVerifySchema(pParse, iDbSrc);
99444 iSrc = pParse->nTab++;
99445 iDest = pParse->nTab++;
99446 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
99447 regData = sqlite3GetTempReg(pParse);
99448 regRowid = sqlite3GetTempReg(pParse);
99449 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
99450 assert( HasRowid(pDest) || destHasUniqueIdx );
99451 if( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
99452 || destHasUniqueIdx /* (2) */
99453 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
99455 /* In some circumstances, we are able to run the xfer optimization
99456 ** only if the destination table is initially empty. This code makes
99457 ** that determination. Conditions under which the destination must
99458 ** be empty:
99460 ** (1) There is no INTEGER PRIMARY KEY but there are indices.
99461 ** (If the destination is not initially empty, the rowid fields
99462 ** of index entries might need to change.)
99464 ** (2) The destination has a unique index. (The xfer optimization
99465 ** is unable to test uniqueness.)
99467 ** (3) onError is something other than OE_Abort and OE_Rollback.
99469 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
99470 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
99471 sqlite3VdbeJumpHere(v, addr1);
99473 if( HasRowid(pSrc) ){
99474 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
99475 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
99476 if( pDest->iPKey>=0 ){
99477 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
99478 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
99479 VdbeCoverage(v);
99480 sqlite3RowidConstraint(pParse, onError, pDest);
99481 sqlite3VdbeJumpHere(v, addr2);
99482 autoIncStep(pParse, regAutoinc, regRowid);
99483 }else if( pDest->pIndex==0 ){
99484 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
99485 }else{
99486 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
99487 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
99489 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
99490 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
99491 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
99492 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
99493 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
99494 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
99495 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
99496 }else{
99497 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
99498 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
99500 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
99501 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
99502 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
99504 assert( pSrcIdx );
99505 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
99506 sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
99507 VdbeComment((v, "%s", pSrcIdx->zName));
99508 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
99509 sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
99510 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
99511 VdbeComment((v, "%s", pDestIdx->zName));
99512 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
99513 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
99514 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
99515 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
99516 sqlite3VdbeJumpHere(v, addr1);
99517 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
99518 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
99520 if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
99521 sqlite3ReleaseTempReg(pParse, regRowid);
99522 sqlite3ReleaseTempReg(pParse, regData);
99523 if( emptyDestTest ){
99524 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
99525 sqlite3VdbeJumpHere(v, emptyDestTest);
99526 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
99527 return 0;
99528 }else{
99529 return 1;
99532 #endif /* SQLITE_OMIT_XFER_OPT */
99534 /************** End of insert.c **********************************************/
99535 /************** Begin file legacy.c ******************************************/
99537 ** 2001 September 15
99539 ** The author disclaims copyright to this source code. In place of
99540 ** a legal notice, here is a blessing:
99542 ** May you do good and not evil.
99543 ** May you find forgiveness for yourself and forgive others.
99544 ** May you share freely, never taking more than you give.
99546 *************************************************************************
99547 ** Main file for the SQLite library. The routines in this file
99548 ** implement the programmer interface to the library. Routines in
99549 ** other files are for internal use by SQLite and should not be
99550 ** accessed by users of the library.
99555 ** Execute SQL code. Return one of the SQLITE_ success/failure
99556 ** codes. Also write an error message into memory obtained from
99557 ** malloc() and make *pzErrMsg point to that message.
99559 ** If the SQL is a query, then for each row in the query result
99560 ** the xCallback() function is called. pArg becomes the first
99561 ** argument to xCallback(). If xCallback=NULL then no callback
99562 ** is invoked, even for queries.
99564 SQLITE_API int sqlite3_exec(
99565 sqlite3 *db, /* The database on which the SQL executes */
99566 const char *zSql, /* The SQL to be executed */
99567 sqlite3_callback xCallback, /* Invoke this callback routine */
99568 void *pArg, /* First argument to xCallback() */
99569 char **pzErrMsg /* Write error messages here */
99571 int rc = SQLITE_OK; /* Return code */
99572 const char *zLeftover; /* Tail of unprocessed SQL */
99573 sqlite3_stmt *pStmt = 0; /* The current SQL statement */
99574 char **azCols = 0; /* Names of result columns */
99575 int callbackIsInit; /* True if callback data is initialized */
99577 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
99578 if( zSql==0 ) zSql = "";
99580 sqlite3_mutex_enter(db->mutex);
99581 sqlite3Error(db, SQLITE_OK);
99582 while( rc==SQLITE_OK && zSql[0] ){
99583 int nCol;
99584 char **azVals = 0;
99586 pStmt = 0;
99587 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
99588 assert( rc==SQLITE_OK || pStmt==0 );
99589 if( rc!=SQLITE_OK ){
99590 continue;
99592 if( !pStmt ){
99593 /* this happens for a comment or white-space */
99594 zSql = zLeftover;
99595 continue;
99598 callbackIsInit = 0;
99599 nCol = sqlite3_column_count(pStmt);
99601 while( 1 ){
99602 int i;
99603 rc = sqlite3_step(pStmt);
99605 /* Invoke the callback function if required */
99606 if( xCallback && (SQLITE_ROW==rc ||
99607 (SQLITE_DONE==rc && !callbackIsInit
99608 && db->flags&SQLITE_NullCallback)) ){
99609 if( !callbackIsInit ){
99610 azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
99611 if( azCols==0 ){
99612 goto exec_out;
99614 for(i=0; i<nCol; i++){
99615 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
99616 /* sqlite3VdbeSetColName() installs column names as UTF8
99617 ** strings so there is no way for sqlite3_column_name() to fail. */
99618 assert( azCols[i]!=0 );
99620 callbackIsInit = 1;
99622 if( rc==SQLITE_ROW ){
99623 azVals = &azCols[nCol];
99624 for(i=0; i<nCol; i++){
99625 azVals[i] = (char *)sqlite3_column_text(pStmt, i);
99626 if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
99627 db->mallocFailed = 1;
99628 goto exec_out;
99632 if( xCallback(pArg, nCol, azVals, azCols) ){
99633 /* EVIDENCE-OF: R-38229-40159 If the callback function to
99634 ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
99635 ** return SQLITE_ABORT. */
99636 rc = SQLITE_ABORT;
99637 sqlite3VdbeFinalize((Vdbe *)pStmt);
99638 pStmt = 0;
99639 sqlite3Error(db, SQLITE_ABORT);
99640 goto exec_out;
99644 if( rc!=SQLITE_ROW ){
99645 rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
99646 pStmt = 0;
99647 zSql = zLeftover;
99648 while( sqlite3Isspace(zSql[0]) ) zSql++;
99649 break;
99653 sqlite3DbFree(db, azCols);
99654 azCols = 0;
99657 exec_out:
99658 if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
99659 sqlite3DbFree(db, azCols);
99661 rc = sqlite3ApiExit(db, rc);
99662 if( rc!=SQLITE_OK && pzErrMsg ){
99663 int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
99664 *pzErrMsg = sqlite3Malloc(nErrMsg);
99665 if( *pzErrMsg ){
99666 memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
99667 }else{
99668 rc = SQLITE_NOMEM;
99669 sqlite3Error(db, SQLITE_NOMEM);
99671 }else if( pzErrMsg ){
99672 *pzErrMsg = 0;
99675 assert( (rc&db->errMask)==rc );
99676 sqlite3_mutex_leave(db->mutex);
99677 return rc;
99680 /************** End of legacy.c **********************************************/
99681 /************** Begin file loadext.c *****************************************/
99683 ** 2006 June 7
99685 ** The author disclaims copyright to this source code. In place of
99686 ** a legal notice, here is a blessing:
99688 ** May you do good and not evil.
99689 ** May you find forgiveness for yourself and forgive others.
99690 ** May you share freely, never taking more than you give.
99692 *************************************************************************
99693 ** This file contains code used to dynamically load extensions into
99694 ** the SQLite library.
99697 #ifndef SQLITE_CORE
99698 #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
99699 #endif
99700 /************** Include sqlite3ext.h in the middle of loadext.c **************/
99701 /************** Begin file sqlite3ext.h **************************************/
99703 ** 2006 June 7
99705 ** The author disclaims copyright to this source code. In place of
99706 ** a legal notice, here is a blessing:
99708 ** May you do good and not evil.
99709 ** May you find forgiveness for yourself and forgive others.
99710 ** May you share freely, never taking more than you give.
99712 *************************************************************************
99713 ** This header file defines the SQLite interface for use by
99714 ** shared libraries that want to be imported as extensions into
99715 ** an SQLite instance. Shared libraries that intend to be loaded
99716 ** as extensions by SQLite should #include this file instead of
99717 ** sqlite3.h.
99719 #ifndef _SQLITE3EXT_H_
99720 #define _SQLITE3EXT_H_
99722 typedef struct sqlite3_api_routines sqlite3_api_routines;
99725 ** The following structure holds pointers to all of the SQLite API
99726 ** routines.
99728 ** WARNING: In order to maintain backwards compatibility, add new
99729 ** interfaces to the end of this structure only. If you insert new
99730 ** interfaces in the middle of this structure, then older different
99731 ** versions of SQLite will not be able to load each other's shared
99732 ** libraries!
99734 struct sqlite3_api_routines {
99735 void * (*aggregate_context)(sqlite3_context*,int nBytes);
99736 int (*aggregate_count)(sqlite3_context*);
99737 int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
99738 int (*bind_double)(sqlite3_stmt*,int,double);
99739 int (*bind_int)(sqlite3_stmt*,int,int);
99740 int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
99741 int (*bind_null)(sqlite3_stmt*,int);
99742 int (*bind_parameter_count)(sqlite3_stmt*);
99743 int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
99744 const char * (*bind_parameter_name)(sqlite3_stmt*,int);
99745 int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
99746 int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
99747 int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
99748 int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
99749 int (*busy_timeout)(sqlite3*,int ms);
99750 int (*changes)(sqlite3*);
99751 int (*close)(sqlite3*);
99752 int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
99753 int eTextRep,const char*));
99754 int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
99755 int eTextRep,const void*));
99756 const void * (*column_blob)(sqlite3_stmt*,int iCol);
99757 int (*column_bytes)(sqlite3_stmt*,int iCol);
99758 int (*column_bytes16)(sqlite3_stmt*,int iCol);
99759 int (*column_count)(sqlite3_stmt*pStmt);
99760 const char * (*column_database_name)(sqlite3_stmt*,int);
99761 const void * (*column_database_name16)(sqlite3_stmt*,int);
99762 const char * (*column_decltype)(sqlite3_stmt*,int i);
99763 const void * (*column_decltype16)(sqlite3_stmt*,int);
99764 double (*column_double)(sqlite3_stmt*,int iCol);
99765 int (*column_int)(sqlite3_stmt*,int iCol);
99766 sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
99767 const char * (*column_name)(sqlite3_stmt*,int);
99768 const void * (*column_name16)(sqlite3_stmt*,int);
99769 const char * (*column_origin_name)(sqlite3_stmt*,int);
99770 const void * (*column_origin_name16)(sqlite3_stmt*,int);
99771 const char * (*column_table_name)(sqlite3_stmt*,int);
99772 const void * (*column_table_name16)(sqlite3_stmt*,int);
99773 const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
99774 const void * (*column_text16)(sqlite3_stmt*,int iCol);
99775 int (*column_type)(sqlite3_stmt*,int iCol);
99776 sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
99777 void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
99778 int (*complete)(const char*sql);
99779 int (*complete16)(const void*sql);
99780 int (*create_collation)(sqlite3*,const char*,int,void*,
99781 int(*)(void*,int,const void*,int,const void*));
99782 int (*create_collation16)(sqlite3*,const void*,int,void*,
99783 int(*)(void*,int,const void*,int,const void*));
99784 int (*create_function)(sqlite3*,const char*,int,int,void*,
99785 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
99786 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
99787 void (*xFinal)(sqlite3_context*));
99788 int (*create_function16)(sqlite3*,const void*,int,int,void*,
99789 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
99790 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
99791 void (*xFinal)(sqlite3_context*));
99792 int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
99793 int (*data_count)(sqlite3_stmt*pStmt);
99794 sqlite3 * (*db_handle)(sqlite3_stmt*);
99795 int (*declare_vtab)(sqlite3*,const char*);
99796 int (*enable_shared_cache)(int);
99797 int (*errcode)(sqlite3*db);
99798 const char * (*errmsg)(sqlite3*);
99799 const void * (*errmsg16)(sqlite3*);
99800 int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
99801 int (*expired)(sqlite3_stmt*);
99802 int (*finalize)(sqlite3_stmt*pStmt);
99803 void (*free)(void*);
99804 void (*free_table)(char**result);
99805 int (*get_autocommit)(sqlite3*);
99806 void * (*get_auxdata)(sqlite3_context*,int);
99807 int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
99808 int (*global_recover)(void);
99809 void (*interruptx)(sqlite3*);
99810 sqlite_int64 (*last_insert_rowid)(sqlite3*);
99811 const char * (*libversion)(void);
99812 int (*libversion_number)(void);
99813 void *(*malloc)(int);
99814 char * (*mprintf)(const char*,...);
99815 int (*open)(const char*,sqlite3**);
99816 int (*open16)(const void*,sqlite3**);
99817 int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
99818 int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
99819 void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
99820 void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
99821 void *(*realloc)(void*,int);
99822 int (*reset)(sqlite3_stmt*pStmt);
99823 void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
99824 void (*result_double)(sqlite3_context*,double);
99825 void (*result_error)(sqlite3_context*,const char*,int);
99826 void (*result_error16)(sqlite3_context*,const void*,int);
99827 void (*result_int)(sqlite3_context*,int);
99828 void (*result_int64)(sqlite3_context*,sqlite_int64);
99829 void (*result_null)(sqlite3_context*);
99830 void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
99831 void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
99832 void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
99833 void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
99834 void (*result_value)(sqlite3_context*,sqlite3_value*);
99835 void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
99836 int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
99837 const char*,const char*),void*);
99838 void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
99839 char * (*snprintf)(int,char*,const char*,...);
99840 int (*step)(sqlite3_stmt*);
99841 int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
99842 char const**,char const**,int*,int*,int*);
99843 void (*thread_cleanup)(void);
99844 int (*total_changes)(sqlite3*);
99845 void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
99846 int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
99847 void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
99848 sqlite_int64),void*);
99849 void * (*user_data)(sqlite3_context*);
99850 const void * (*value_blob)(sqlite3_value*);
99851 int (*value_bytes)(sqlite3_value*);
99852 int (*value_bytes16)(sqlite3_value*);
99853 double (*value_double)(sqlite3_value*);
99854 int (*value_int)(sqlite3_value*);
99855 sqlite_int64 (*value_int64)(sqlite3_value*);
99856 int (*value_numeric_type)(sqlite3_value*);
99857 const unsigned char * (*value_text)(sqlite3_value*);
99858 const void * (*value_text16)(sqlite3_value*);
99859 const void * (*value_text16be)(sqlite3_value*);
99860 const void * (*value_text16le)(sqlite3_value*);
99861 int (*value_type)(sqlite3_value*);
99862 char *(*vmprintf)(const char*,va_list);
99863 /* Added ??? */
99864 int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
99865 /* Added by 3.3.13 */
99866 int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
99867 int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
99868 int (*clear_bindings)(sqlite3_stmt*);
99869 /* Added by 3.4.1 */
99870 int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
99871 void (*xDestroy)(void *));
99872 /* Added by 3.5.0 */
99873 int (*bind_zeroblob)(sqlite3_stmt*,int,int);
99874 int (*blob_bytes)(sqlite3_blob*);
99875 int (*blob_close)(sqlite3_blob*);
99876 int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
99877 int,sqlite3_blob**);
99878 int (*blob_read)(sqlite3_blob*,void*,int,int);
99879 int (*blob_write)(sqlite3_blob*,const void*,int,int);
99880 int (*create_collation_v2)(sqlite3*,const char*,int,void*,
99881 int(*)(void*,int,const void*,int,const void*),
99882 void(*)(void*));
99883 int (*file_control)(sqlite3*,const char*,int,void*);
99884 sqlite3_int64 (*memory_highwater)(int);
99885 sqlite3_int64 (*memory_used)(void);
99886 sqlite3_mutex *(*mutex_alloc)(int);
99887 void (*mutex_enter)(sqlite3_mutex*);
99888 void (*mutex_free)(sqlite3_mutex*);
99889 void (*mutex_leave)(sqlite3_mutex*);
99890 int (*mutex_try)(sqlite3_mutex*);
99891 int (*open_v2)(const char*,sqlite3**,int,const char*);
99892 int (*release_memory)(int);
99893 void (*result_error_nomem)(sqlite3_context*);
99894 void (*result_error_toobig)(sqlite3_context*);
99895 int (*sleep)(int);
99896 void (*soft_heap_limit)(int);
99897 sqlite3_vfs *(*vfs_find)(const char*);
99898 int (*vfs_register)(sqlite3_vfs*,int);
99899 int (*vfs_unregister)(sqlite3_vfs*);
99900 int (*xthreadsafe)(void);
99901 void (*result_zeroblob)(sqlite3_context*,int);
99902 void (*result_error_code)(sqlite3_context*,int);
99903 int (*test_control)(int, ...);
99904 void (*randomness)(int,void*);
99905 sqlite3 *(*context_db_handle)(sqlite3_context*);
99906 int (*extended_result_codes)(sqlite3*,int);
99907 int (*limit)(sqlite3*,int,int);
99908 sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
99909 const char *(*sql)(sqlite3_stmt*);
99910 int (*status)(int,int*,int*,int);
99911 int (*backup_finish)(sqlite3_backup*);
99912 sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
99913 int (*backup_pagecount)(sqlite3_backup*);
99914 int (*backup_remaining)(sqlite3_backup*);
99915 int (*backup_step)(sqlite3_backup*,int);
99916 const char *(*compileoption_get)(int);
99917 int (*compileoption_used)(const char*);
99918 int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
99919 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
99920 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
99921 void (*xFinal)(sqlite3_context*),
99922 void(*xDestroy)(void*));
99923 int (*db_config)(sqlite3*,int,...);
99924 sqlite3_mutex *(*db_mutex)(sqlite3*);
99925 int (*db_status)(sqlite3*,int,int*,int*,int);
99926 int (*extended_errcode)(sqlite3*);
99927 void (*log)(int,const char*,...);
99928 sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
99929 const char *(*sourceid)(void);
99930 int (*stmt_status)(sqlite3_stmt*,int,int);
99931 int (*strnicmp)(const char*,const char*,int);
99932 int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
99933 int (*wal_autocheckpoint)(sqlite3*,int);
99934 int (*wal_checkpoint)(sqlite3*,const char*);
99935 void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
99936 int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
99937 int (*vtab_config)(sqlite3*,int op,...);
99938 int (*vtab_on_conflict)(sqlite3*);
99939 /* Version 3.7.16 and later */
99940 int (*close_v2)(sqlite3*);
99941 const char *(*db_filename)(sqlite3*,const char*);
99942 int (*db_readonly)(sqlite3*,const char*);
99943 int (*db_release_memory)(sqlite3*);
99944 const char *(*errstr)(int);
99945 int (*stmt_busy)(sqlite3_stmt*);
99946 int (*stmt_readonly)(sqlite3_stmt*);
99947 int (*stricmp)(const char*,const char*);
99948 int (*uri_boolean)(const char*,const char*,int);
99949 sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
99950 const char *(*uri_parameter)(const char*,const char*);
99951 char *(*vsnprintf)(int,char*,const char*,va_list);
99952 int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
99953 /* Version 3.8.7 and later */
99954 int (*auto_extension)(void(*)(void));
99955 int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
99956 void(*)(void*));
99957 int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
99958 void(*)(void*),unsigned char);
99959 int (*cancel_auto_extension)(void(*)(void));
99960 int (*load_extension)(sqlite3*,const char*,const char*,char**);
99961 void *(*malloc64)(sqlite3_uint64);
99962 sqlite3_uint64 (*msize)(void*);
99963 void *(*realloc64)(void*,sqlite3_uint64);
99964 void (*reset_auto_extension)(void);
99965 void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
99966 void(*)(void*));
99967 void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
99968 void(*)(void*), unsigned char);
99969 int (*strglob)(const char*,const char*);
99973 ** The following macros redefine the API routines so that they are
99974 ** redirected through the global sqlite3_api structure.
99976 ** This header file is also used by the loadext.c source file
99977 ** (part of the main SQLite library - not an extension) so that
99978 ** it can get access to the sqlite3_api_routines structure
99979 ** definition. But the main library does not want to redefine
99980 ** the API. So the redefinition macros are only valid if the
99981 ** SQLITE_CORE macros is undefined.
99983 #ifndef SQLITE_CORE
99984 #define sqlite3_aggregate_context sqlite3_api->aggregate_context
99985 #ifndef SQLITE_OMIT_DEPRECATED
99986 #define sqlite3_aggregate_count sqlite3_api->aggregate_count
99987 #endif
99988 #define sqlite3_bind_blob sqlite3_api->bind_blob
99989 #define sqlite3_bind_double sqlite3_api->bind_double
99990 #define sqlite3_bind_int sqlite3_api->bind_int
99991 #define sqlite3_bind_int64 sqlite3_api->bind_int64
99992 #define sqlite3_bind_null sqlite3_api->bind_null
99993 #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
99994 #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
99995 #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
99996 #define sqlite3_bind_text sqlite3_api->bind_text
99997 #define sqlite3_bind_text16 sqlite3_api->bind_text16
99998 #define sqlite3_bind_value sqlite3_api->bind_value
99999 #define sqlite3_busy_handler sqlite3_api->busy_handler
100000 #define sqlite3_busy_timeout sqlite3_api->busy_timeout
100001 #define sqlite3_changes sqlite3_api->changes
100002 #define sqlite3_close sqlite3_api->close
100003 #define sqlite3_collation_needed sqlite3_api->collation_needed
100004 #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
100005 #define sqlite3_column_blob sqlite3_api->column_blob
100006 #define sqlite3_column_bytes sqlite3_api->column_bytes
100007 #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
100008 #define sqlite3_column_count sqlite3_api->column_count
100009 #define sqlite3_column_database_name sqlite3_api->column_database_name
100010 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
100011 #define sqlite3_column_decltype sqlite3_api->column_decltype
100012 #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
100013 #define sqlite3_column_double sqlite3_api->column_double
100014 #define sqlite3_column_int sqlite3_api->column_int
100015 #define sqlite3_column_int64 sqlite3_api->column_int64
100016 #define sqlite3_column_name sqlite3_api->column_name
100017 #define sqlite3_column_name16 sqlite3_api->column_name16
100018 #define sqlite3_column_origin_name sqlite3_api->column_origin_name
100019 #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
100020 #define sqlite3_column_table_name sqlite3_api->column_table_name
100021 #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
100022 #define sqlite3_column_text sqlite3_api->column_text
100023 #define sqlite3_column_text16 sqlite3_api->column_text16
100024 #define sqlite3_column_type sqlite3_api->column_type
100025 #define sqlite3_column_value sqlite3_api->column_value
100026 #define sqlite3_commit_hook sqlite3_api->commit_hook
100027 #define sqlite3_complete sqlite3_api->complete
100028 #define sqlite3_complete16 sqlite3_api->complete16
100029 #define sqlite3_create_collation sqlite3_api->create_collation
100030 #define sqlite3_create_collation16 sqlite3_api->create_collation16
100031 #define sqlite3_create_function sqlite3_api->create_function
100032 #define sqlite3_create_function16 sqlite3_api->create_function16
100033 #define sqlite3_create_module sqlite3_api->create_module
100034 #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
100035 #define sqlite3_data_count sqlite3_api->data_count
100036 #define sqlite3_db_handle sqlite3_api->db_handle
100037 #define sqlite3_declare_vtab sqlite3_api->declare_vtab
100038 #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
100039 #define sqlite3_errcode sqlite3_api->errcode
100040 #define sqlite3_errmsg sqlite3_api->errmsg
100041 #define sqlite3_errmsg16 sqlite3_api->errmsg16
100042 #define sqlite3_exec sqlite3_api->exec
100043 #ifndef SQLITE_OMIT_DEPRECATED
100044 #define sqlite3_expired sqlite3_api->expired
100045 #endif
100046 #define sqlite3_finalize sqlite3_api->finalize
100047 #define sqlite3_free sqlite3_api->free
100048 #define sqlite3_free_table sqlite3_api->free_table
100049 #define sqlite3_get_autocommit sqlite3_api->get_autocommit
100050 #define sqlite3_get_auxdata sqlite3_api->get_auxdata
100051 #define sqlite3_get_table sqlite3_api->get_table
100052 #ifndef SQLITE_OMIT_DEPRECATED
100053 #define sqlite3_global_recover sqlite3_api->global_recover
100054 #endif
100055 #define sqlite3_interrupt sqlite3_api->interruptx
100056 #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
100057 #define sqlite3_libversion sqlite3_api->libversion
100058 #define sqlite3_libversion_number sqlite3_api->libversion_number
100059 #define sqlite3_malloc sqlite3_api->malloc
100060 #define sqlite3_mprintf sqlite3_api->mprintf
100061 #define sqlite3_open sqlite3_api->open
100062 #define sqlite3_open16 sqlite3_api->open16
100063 #define sqlite3_prepare sqlite3_api->prepare
100064 #define sqlite3_prepare16 sqlite3_api->prepare16
100065 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
100066 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
100067 #define sqlite3_profile sqlite3_api->profile
100068 #define sqlite3_progress_handler sqlite3_api->progress_handler
100069 #define sqlite3_realloc sqlite3_api->realloc
100070 #define sqlite3_reset sqlite3_api->reset
100071 #define sqlite3_result_blob sqlite3_api->result_blob
100072 #define sqlite3_result_double sqlite3_api->result_double
100073 #define sqlite3_result_error sqlite3_api->result_error
100074 #define sqlite3_result_error16 sqlite3_api->result_error16
100075 #define sqlite3_result_int sqlite3_api->result_int
100076 #define sqlite3_result_int64 sqlite3_api->result_int64
100077 #define sqlite3_result_null sqlite3_api->result_null
100078 #define sqlite3_result_text sqlite3_api->result_text
100079 #define sqlite3_result_text16 sqlite3_api->result_text16
100080 #define sqlite3_result_text16be sqlite3_api->result_text16be
100081 #define sqlite3_result_text16le sqlite3_api->result_text16le
100082 #define sqlite3_result_value sqlite3_api->result_value
100083 #define sqlite3_rollback_hook sqlite3_api->rollback_hook
100084 #define sqlite3_set_authorizer sqlite3_api->set_authorizer
100085 #define sqlite3_set_auxdata sqlite3_api->set_auxdata
100086 #define sqlite3_snprintf sqlite3_api->snprintf
100087 #define sqlite3_step sqlite3_api->step
100088 #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
100089 #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
100090 #define sqlite3_total_changes sqlite3_api->total_changes
100091 #define sqlite3_trace sqlite3_api->trace
100092 #ifndef SQLITE_OMIT_DEPRECATED
100093 #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
100094 #endif
100095 #define sqlite3_update_hook sqlite3_api->update_hook
100096 #define sqlite3_user_data sqlite3_api->user_data
100097 #define sqlite3_value_blob sqlite3_api->value_blob
100098 #define sqlite3_value_bytes sqlite3_api->value_bytes
100099 #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
100100 #define sqlite3_value_double sqlite3_api->value_double
100101 #define sqlite3_value_int sqlite3_api->value_int
100102 #define sqlite3_value_int64 sqlite3_api->value_int64
100103 #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
100104 #define sqlite3_value_text sqlite3_api->value_text
100105 #define sqlite3_value_text16 sqlite3_api->value_text16
100106 #define sqlite3_value_text16be sqlite3_api->value_text16be
100107 #define sqlite3_value_text16le sqlite3_api->value_text16le
100108 #define sqlite3_value_type sqlite3_api->value_type
100109 #define sqlite3_vmprintf sqlite3_api->vmprintf
100110 #define sqlite3_overload_function sqlite3_api->overload_function
100111 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
100112 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
100113 #define sqlite3_clear_bindings sqlite3_api->clear_bindings
100114 #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
100115 #define sqlite3_blob_bytes sqlite3_api->blob_bytes
100116 #define sqlite3_blob_close sqlite3_api->blob_close
100117 #define sqlite3_blob_open sqlite3_api->blob_open
100118 #define sqlite3_blob_read sqlite3_api->blob_read
100119 #define sqlite3_blob_write sqlite3_api->blob_write
100120 #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
100121 #define sqlite3_file_control sqlite3_api->file_control
100122 #define sqlite3_memory_highwater sqlite3_api->memory_highwater
100123 #define sqlite3_memory_used sqlite3_api->memory_used
100124 #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
100125 #define sqlite3_mutex_enter sqlite3_api->mutex_enter
100126 #define sqlite3_mutex_free sqlite3_api->mutex_free
100127 #define sqlite3_mutex_leave sqlite3_api->mutex_leave
100128 #define sqlite3_mutex_try sqlite3_api->mutex_try
100129 #define sqlite3_open_v2 sqlite3_api->open_v2
100130 #define sqlite3_release_memory sqlite3_api->release_memory
100131 #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
100132 #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
100133 #define sqlite3_sleep sqlite3_api->sleep
100134 #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
100135 #define sqlite3_vfs_find sqlite3_api->vfs_find
100136 #define sqlite3_vfs_register sqlite3_api->vfs_register
100137 #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
100138 #define sqlite3_threadsafe sqlite3_api->xthreadsafe
100139 #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
100140 #define sqlite3_result_error_code sqlite3_api->result_error_code
100141 #define sqlite3_test_control sqlite3_api->test_control
100142 #define sqlite3_randomness sqlite3_api->randomness
100143 #define sqlite3_context_db_handle sqlite3_api->context_db_handle
100144 #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
100145 #define sqlite3_limit sqlite3_api->limit
100146 #define sqlite3_next_stmt sqlite3_api->next_stmt
100147 #define sqlite3_sql sqlite3_api->sql
100148 #define sqlite3_status sqlite3_api->status
100149 #define sqlite3_backup_finish sqlite3_api->backup_finish
100150 #define sqlite3_backup_init sqlite3_api->backup_init
100151 #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
100152 #define sqlite3_backup_remaining sqlite3_api->backup_remaining
100153 #define sqlite3_backup_step sqlite3_api->backup_step
100154 #define sqlite3_compileoption_get sqlite3_api->compileoption_get
100155 #define sqlite3_compileoption_used sqlite3_api->compileoption_used
100156 #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
100157 #define sqlite3_db_config sqlite3_api->db_config
100158 #define sqlite3_db_mutex sqlite3_api->db_mutex
100159 #define sqlite3_db_status sqlite3_api->db_status
100160 #define sqlite3_extended_errcode sqlite3_api->extended_errcode
100161 #define sqlite3_log sqlite3_api->log
100162 #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
100163 #define sqlite3_sourceid sqlite3_api->sourceid
100164 #define sqlite3_stmt_status sqlite3_api->stmt_status
100165 #define sqlite3_strnicmp sqlite3_api->strnicmp
100166 #define sqlite3_unlock_notify sqlite3_api->unlock_notify
100167 #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
100168 #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
100169 #define sqlite3_wal_hook sqlite3_api->wal_hook
100170 #define sqlite3_blob_reopen sqlite3_api->blob_reopen
100171 #define sqlite3_vtab_config sqlite3_api->vtab_config
100172 #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
100173 /* Version 3.7.16 and later */
100174 #define sqlite3_close_v2 sqlite3_api->close_v2
100175 #define sqlite3_db_filename sqlite3_api->db_filename
100176 #define sqlite3_db_readonly sqlite3_api->db_readonly
100177 #define sqlite3_db_release_memory sqlite3_api->db_release_memory
100178 #define sqlite3_errstr sqlite3_api->errstr
100179 #define sqlite3_stmt_busy sqlite3_api->stmt_busy
100180 #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
100181 #define sqlite3_stricmp sqlite3_api->stricmp
100182 #define sqlite3_uri_boolean sqlite3_api->uri_boolean
100183 #define sqlite3_uri_int64 sqlite3_api->uri_int64
100184 #define sqlite3_uri_parameter sqlite3_api->uri_parameter
100185 #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
100186 #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
100187 /* Version 3.8.7 and later */
100188 #define sqlite3_auto_extension sqlite3_api->auto_extension
100189 #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
100190 #define sqlite3_bind_text64 sqlite3_api->bind_text64
100191 #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
100192 #define sqlite3_load_extension sqlite3_api->load_extension
100193 #define sqlite3_malloc64 sqlite3_api->malloc64
100194 #define sqlite3_msize sqlite3_api->msize
100195 #define sqlite3_realloc64 sqlite3_api->realloc64
100196 #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
100197 #define sqlite3_result_blob64 sqlite3_api->result_blob64
100198 #define sqlite3_result_text64 sqlite3_api->result_text64
100199 #define sqlite3_strglob sqlite3_api->strglob
100200 #endif /* SQLITE_CORE */
100202 #ifndef SQLITE_CORE
100203 /* This case when the file really is being compiled as a loadable
100204 ** extension */
100205 # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
100206 # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
100207 # define SQLITE_EXTENSION_INIT3 \
100208 extern const sqlite3_api_routines *sqlite3_api;
100209 #else
100210 /* This case when the file is being statically linked into the
100211 ** application */
100212 # define SQLITE_EXTENSION_INIT1 /*no-op*/
100213 # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
100214 # define SQLITE_EXTENSION_INIT3 /*no-op*/
100215 #endif
100217 #endif /* _SQLITE3EXT_H_ */
100219 /************** End of sqlite3ext.h ******************************************/
100220 /************** Continuing where we left off in loadext.c ********************/
100221 /* #include <string.h> */
100223 #ifndef SQLITE_OMIT_LOAD_EXTENSION
100226 ** Some API routines are omitted when various features are
100227 ** excluded from a build of SQLite. Substitute a NULL pointer
100228 ** for any missing APIs.
100230 #ifndef SQLITE_ENABLE_COLUMN_METADATA
100231 # define sqlite3_column_database_name 0
100232 # define sqlite3_column_database_name16 0
100233 # define sqlite3_column_table_name 0
100234 # define sqlite3_column_table_name16 0
100235 # define sqlite3_column_origin_name 0
100236 # define sqlite3_column_origin_name16 0
100237 # define sqlite3_table_column_metadata 0
100238 #endif
100240 #ifdef SQLITE_OMIT_AUTHORIZATION
100241 # define sqlite3_set_authorizer 0
100242 #endif
100244 #ifdef SQLITE_OMIT_UTF16
100245 # define sqlite3_bind_text16 0
100246 # define sqlite3_collation_needed16 0
100247 # define sqlite3_column_decltype16 0
100248 # define sqlite3_column_name16 0
100249 # define sqlite3_column_text16 0
100250 # define sqlite3_complete16 0
100251 # define sqlite3_create_collation16 0
100252 # define sqlite3_create_function16 0
100253 # define sqlite3_errmsg16 0
100254 # define sqlite3_open16 0
100255 # define sqlite3_prepare16 0
100256 # define sqlite3_prepare16_v2 0
100257 # define sqlite3_result_error16 0
100258 # define sqlite3_result_text16 0
100259 # define sqlite3_result_text16be 0
100260 # define sqlite3_result_text16le 0
100261 # define sqlite3_value_text16 0
100262 # define sqlite3_value_text16be 0
100263 # define sqlite3_value_text16le 0
100264 # define sqlite3_column_database_name16 0
100265 # define sqlite3_column_table_name16 0
100266 # define sqlite3_column_origin_name16 0
100267 #endif
100269 #ifdef SQLITE_OMIT_COMPLETE
100270 # define sqlite3_complete 0
100271 # define sqlite3_complete16 0
100272 #endif
100274 #ifdef SQLITE_OMIT_DECLTYPE
100275 # define sqlite3_column_decltype16 0
100276 # define sqlite3_column_decltype 0
100277 #endif
100279 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
100280 # define sqlite3_progress_handler 0
100281 #endif
100283 #ifdef SQLITE_OMIT_VIRTUALTABLE
100284 # define sqlite3_create_module 0
100285 # define sqlite3_create_module_v2 0
100286 # define sqlite3_declare_vtab 0
100287 # define sqlite3_vtab_config 0
100288 # define sqlite3_vtab_on_conflict 0
100289 #endif
100291 #ifdef SQLITE_OMIT_SHARED_CACHE
100292 # define sqlite3_enable_shared_cache 0
100293 #endif
100295 #ifdef SQLITE_OMIT_TRACE
100296 # define sqlite3_profile 0
100297 # define sqlite3_trace 0
100298 #endif
100300 #ifdef SQLITE_OMIT_GET_TABLE
100301 # define sqlite3_free_table 0
100302 # define sqlite3_get_table 0
100303 #endif
100305 #ifdef SQLITE_OMIT_INCRBLOB
100306 #define sqlite3_bind_zeroblob 0
100307 #define sqlite3_blob_bytes 0
100308 #define sqlite3_blob_close 0
100309 #define sqlite3_blob_open 0
100310 #define sqlite3_blob_read 0
100311 #define sqlite3_blob_write 0
100312 #define sqlite3_blob_reopen 0
100313 #endif
100316 ** The following structure contains pointers to all SQLite API routines.
100317 ** A pointer to this structure is passed into extensions when they are
100318 ** loaded so that the extension can make calls back into the SQLite
100319 ** library.
100321 ** When adding new APIs, add them to the bottom of this structure
100322 ** in order to preserve backwards compatibility.
100324 ** Extensions that use newer APIs should first call the
100325 ** sqlite3_libversion_number() to make sure that the API they
100326 ** intend to use is supported by the library. Extensions should
100327 ** also check to make sure that the pointer to the function is
100328 ** not NULL before calling it.
100330 static const sqlite3_api_routines sqlite3Apis = {
100331 sqlite3_aggregate_context,
100332 #ifndef SQLITE_OMIT_DEPRECATED
100333 sqlite3_aggregate_count,
100334 #else
100336 #endif
100337 sqlite3_bind_blob,
100338 sqlite3_bind_double,
100339 sqlite3_bind_int,
100340 sqlite3_bind_int64,
100341 sqlite3_bind_null,
100342 sqlite3_bind_parameter_count,
100343 sqlite3_bind_parameter_index,
100344 sqlite3_bind_parameter_name,
100345 sqlite3_bind_text,
100346 sqlite3_bind_text16,
100347 sqlite3_bind_value,
100348 sqlite3_busy_handler,
100349 sqlite3_busy_timeout,
100350 sqlite3_changes,
100351 sqlite3_close,
100352 sqlite3_collation_needed,
100353 sqlite3_collation_needed16,
100354 sqlite3_column_blob,
100355 sqlite3_column_bytes,
100356 sqlite3_column_bytes16,
100357 sqlite3_column_count,
100358 sqlite3_column_database_name,
100359 sqlite3_column_database_name16,
100360 sqlite3_column_decltype,
100361 sqlite3_column_decltype16,
100362 sqlite3_column_double,
100363 sqlite3_column_int,
100364 sqlite3_column_int64,
100365 sqlite3_column_name,
100366 sqlite3_column_name16,
100367 sqlite3_column_origin_name,
100368 sqlite3_column_origin_name16,
100369 sqlite3_column_table_name,
100370 sqlite3_column_table_name16,
100371 sqlite3_column_text,
100372 sqlite3_column_text16,
100373 sqlite3_column_type,
100374 sqlite3_column_value,
100375 sqlite3_commit_hook,
100376 sqlite3_complete,
100377 sqlite3_complete16,
100378 sqlite3_create_collation,
100379 sqlite3_create_collation16,
100380 sqlite3_create_function,
100381 sqlite3_create_function16,
100382 sqlite3_create_module,
100383 sqlite3_data_count,
100384 sqlite3_db_handle,
100385 sqlite3_declare_vtab,
100386 sqlite3_enable_shared_cache,
100387 sqlite3_errcode,
100388 sqlite3_errmsg,
100389 sqlite3_errmsg16,
100390 sqlite3_exec,
100391 #ifndef SQLITE_OMIT_DEPRECATED
100392 sqlite3_expired,
100393 #else
100395 #endif
100396 sqlite3_finalize,
100397 sqlite3_free,
100398 sqlite3_free_table,
100399 sqlite3_get_autocommit,
100400 sqlite3_get_auxdata,
100401 sqlite3_get_table,
100402 0, /* Was sqlite3_global_recover(), but that function is deprecated */
100403 sqlite3_interrupt,
100404 sqlite3_last_insert_rowid,
100405 sqlite3_libversion,
100406 sqlite3_libversion_number,
100407 sqlite3_malloc,
100408 sqlite3_mprintf,
100409 sqlite3_open,
100410 sqlite3_open16,
100411 sqlite3_prepare,
100412 sqlite3_prepare16,
100413 sqlite3_profile,
100414 sqlite3_progress_handler,
100415 sqlite3_realloc,
100416 sqlite3_reset,
100417 sqlite3_result_blob,
100418 sqlite3_result_double,
100419 sqlite3_result_error,
100420 sqlite3_result_error16,
100421 sqlite3_result_int,
100422 sqlite3_result_int64,
100423 sqlite3_result_null,
100424 sqlite3_result_text,
100425 sqlite3_result_text16,
100426 sqlite3_result_text16be,
100427 sqlite3_result_text16le,
100428 sqlite3_result_value,
100429 sqlite3_rollback_hook,
100430 sqlite3_set_authorizer,
100431 sqlite3_set_auxdata,
100432 sqlite3_snprintf,
100433 sqlite3_step,
100434 sqlite3_table_column_metadata,
100435 #ifndef SQLITE_OMIT_DEPRECATED
100436 sqlite3_thread_cleanup,
100437 #else
100439 #endif
100440 sqlite3_total_changes,
100441 sqlite3_trace,
100442 #ifndef SQLITE_OMIT_DEPRECATED
100443 sqlite3_transfer_bindings,
100444 #else
100446 #endif
100447 sqlite3_update_hook,
100448 sqlite3_user_data,
100449 sqlite3_value_blob,
100450 sqlite3_value_bytes,
100451 sqlite3_value_bytes16,
100452 sqlite3_value_double,
100453 sqlite3_value_int,
100454 sqlite3_value_int64,
100455 sqlite3_value_numeric_type,
100456 sqlite3_value_text,
100457 sqlite3_value_text16,
100458 sqlite3_value_text16be,
100459 sqlite3_value_text16le,
100460 sqlite3_value_type,
100461 sqlite3_vmprintf,
100463 ** The original API set ends here. All extensions can call any
100464 ** of the APIs above provided that the pointer is not NULL. But
100465 ** before calling APIs that follow, extension should check the
100466 ** sqlite3_libversion_number() to make sure they are dealing with
100467 ** a library that is new enough to support that API.
100468 *************************************************************************
100470 sqlite3_overload_function,
100473 ** Added after 3.3.13
100475 sqlite3_prepare_v2,
100476 sqlite3_prepare16_v2,
100477 sqlite3_clear_bindings,
100480 ** Added for 3.4.1
100482 sqlite3_create_module_v2,
100485 ** Added for 3.5.0
100487 sqlite3_bind_zeroblob,
100488 sqlite3_blob_bytes,
100489 sqlite3_blob_close,
100490 sqlite3_blob_open,
100491 sqlite3_blob_read,
100492 sqlite3_blob_write,
100493 sqlite3_create_collation_v2,
100494 sqlite3_file_control,
100495 sqlite3_memory_highwater,
100496 sqlite3_memory_used,
100497 #ifdef SQLITE_MUTEX_OMIT
100503 #else
100504 sqlite3_mutex_alloc,
100505 sqlite3_mutex_enter,
100506 sqlite3_mutex_free,
100507 sqlite3_mutex_leave,
100508 sqlite3_mutex_try,
100509 #endif
100510 sqlite3_open_v2,
100511 sqlite3_release_memory,
100512 sqlite3_result_error_nomem,
100513 sqlite3_result_error_toobig,
100514 sqlite3_sleep,
100515 sqlite3_soft_heap_limit,
100516 sqlite3_vfs_find,
100517 sqlite3_vfs_register,
100518 sqlite3_vfs_unregister,
100521 ** Added for 3.5.8
100523 sqlite3_threadsafe,
100524 sqlite3_result_zeroblob,
100525 sqlite3_result_error_code,
100526 sqlite3_test_control,
100527 sqlite3_randomness,
100528 sqlite3_context_db_handle,
100531 ** Added for 3.6.0
100533 sqlite3_extended_result_codes,
100534 sqlite3_limit,
100535 sqlite3_next_stmt,
100536 sqlite3_sql,
100537 sqlite3_status,
100540 ** Added for 3.7.4
100542 sqlite3_backup_finish,
100543 sqlite3_backup_init,
100544 sqlite3_backup_pagecount,
100545 sqlite3_backup_remaining,
100546 sqlite3_backup_step,
100547 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
100548 sqlite3_compileoption_get,
100549 sqlite3_compileoption_used,
100550 #else
100553 #endif
100554 sqlite3_create_function_v2,
100555 sqlite3_db_config,
100556 sqlite3_db_mutex,
100557 sqlite3_db_status,
100558 sqlite3_extended_errcode,
100559 sqlite3_log,
100560 sqlite3_soft_heap_limit64,
100561 sqlite3_sourceid,
100562 sqlite3_stmt_status,
100563 sqlite3_strnicmp,
100564 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
100565 sqlite3_unlock_notify,
100566 #else
100568 #endif
100569 #ifndef SQLITE_OMIT_WAL
100570 sqlite3_wal_autocheckpoint,
100571 sqlite3_wal_checkpoint,
100572 sqlite3_wal_hook,
100573 #else
100577 #endif
100578 sqlite3_blob_reopen,
100579 sqlite3_vtab_config,
100580 sqlite3_vtab_on_conflict,
100581 sqlite3_close_v2,
100582 sqlite3_db_filename,
100583 sqlite3_db_readonly,
100584 sqlite3_db_release_memory,
100585 sqlite3_errstr,
100586 sqlite3_stmt_busy,
100587 sqlite3_stmt_readonly,
100588 sqlite3_stricmp,
100589 sqlite3_uri_boolean,
100590 sqlite3_uri_int64,
100591 sqlite3_uri_parameter,
100592 sqlite3_vsnprintf,
100593 sqlite3_wal_checkpoint_v2,
100594 /* Version 3.8.7 and later */
100595 sqlite3_auto_extension,
100596 sqlite3_bind_blob64,
100597 sqlite3_bind_text64,
100598 sqlite3_cancel_auto_extension,
100599 sqlite3_load_extension,
100600 sqlite3_malloc64,
100601 sqlite3_msize,
100602 sqlite3_realloc64,
100603 sqlite3_reset_auto_extension,
100604 sqlite3_result_blob64,
100605 sqlite3_result_text64,
100606 sqlite3_strglob
100610 ** Attempt to load an SQLite extension library contained in the file
100611 ** zFile. The entry point is zProc. zProc may be 0 in which case a
100612 ** default entry point name (sqlite3_extension_init) is used. Use
100613 ** of the default name is recommended.
100615 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
100617 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
100618 ** error message text. The calling function should free this memory
100619 ** by calling sqlite3DbFree(db, ).
100621 static int sqlite3LoadExtension(
100622 sqlite3 *db, /* Load the extension into this database connection */
100623 const char *zFile, /* Name of the shared library containing extension */
100624 const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
100625 char **pzErrMsg /* Put error message here if not 0 */
100627 sqlite3_vfs *pVfs = db->pVfs;
100628 void *handle;
100629 int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
100630 char *zErrmsg = 0;
100631 const char *zEntry;
100632 char *zAltEntry = 0;
100633 void **aHandle;
100634 int nMsg = 300 + sqlite3Strlen30(zFile);
100635 int ii;
100637 /* Shared library endings to try if zFile cannot be loaded as written */
100638 static const char *azEndings[] = {
100639 #if SQLITE_OS_WIN
100640 "dll"
100641 #elif defined(__APPLE__)
100642 "dylib"
100643 #else
100645 #endif
100649 if( pzErrMsg ) *pzErrMsg = 0;
100651 /* Ticket #1863. To avoid a creating security problems for older
100652 ** applications that relink against newer versions of SQLite, the
100653 ** ability to run load_extension is turned off by default. One
100654 ** must call sqlite3_enable_load_extension() to turn on extension
100655 ** loading. Otherwise you get the following error.
100657 if( (db->flags & SQLITE_LoadExtension)==0 ){
100658 if( pzErrMsg ){
100659 *pzErrMsg = sqlite3_mprintf("not authorized");
100661 return SQLITE_ERROR;
100664 zEntry = zProc ? zProc : "sqlite3_extension_init";
100666 handle = sqlite3OsDlOpen(pVfs, zFile);
100667 #if SQLITE_OS_UNIX || SQLITE_OS_WIN
100668 for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
100669 char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
100670 if( zAltFile==0 ) return SQLITE_NOMEM;
100671 handle = sqlite3OsDlOpen(pVfs, zAltFile);
100672 sqlite3_free(zAltFile);
100674 #endif
100675 if( handle==0 ){
100676 if( pzErrMsg ){
100677 *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
100678 if( zErrmsg ){
100679 sqlite3_snprintf(nMsg, zErrmsg,
100680 "unable to open shared library [%s]", zFile);
100681 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
100684 return SQLITE_ERROR;
100686 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
100687 sqlite3OsDlSym(pVfs, handle, zEntry);
100689 /* If no entry point was specified and the default legacy
100690 ** entry point name "sqlite3_extension_init" was not found, then
100691 ** construct an entry point name "sqlite3_X_init" where the X is
100692 ** replaced by the lowercase value of every ASCII alphabetic
100693 ** character in the filename after the last "/" upto the first ".",
100694 ** and eliding the first three characters if they are "lib".
100695 ** Examples:
100697 ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
100698 ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
100700 if( xInit==0 && zProc==0 ){
100701 int iFile, iEntry, c;
100702 int ncFile = sqlite3Strlen30(zFile);
100703 zAltEntry = sqlite3_malloc(ncFile+30);
100704 if( zAltEntry==0 ){
100705 sqlite3OsDlClose(pVfs, handle);
100706 return SQLITE_NOMEM;
100708 memcpy(zAltEntry, "sqlite3_", 8);
100709 for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
100710 iFile++;
100711 if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
100712 for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
100713 if( sqlite3Isalpha(c) ){
100714 zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
100717 memcpy(zAltEntry+iEntry, "_init", 6);
100718 zEntry = zAltEntry;
100719 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
100720 sqlite3OsDlSym(pVfs, handle, zEntry);
100722 if( xInit==0 ){
100723 if( pzErrMsg ){
100724 nMsg += sqlite3Strlen30(zEntry);
100725 *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
100726 if( zErrmsg ){
100727 sqlite3_snprintf(nMsg, zErrmsg,
100728 "no entry point [%s] in shared library [%s]", zEntry, zFile);
100729 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
100732 sqlite3OsDlClose(pVfs, handle);
100733 sqlite3_free(zAltEntry);
100734 return SQLITE_ERROR;
100736 sqlite3_free(zAltEntry);
100737 if( xInit(db, &zErrmsg, &sqlite3Apis) ){
100738 if( pzErrMsg ){
100739 *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
100741 sqlite3_free(zErrmsg);
100742 sqlite3OsDlClose(pVfs, handle);
100743 return SQLITE_ERROR;
100746 /* Append the new shared library handle to the db->aExtension array. */
100747 aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
100748 if( aHandle==0 ){
100749 return SQLITE_NOMEM;
100751 if( db->nExtension>0 ){
100752 memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
100754 sqlite3DbFree(db, db->aExtension);
100755 db->aExtension = aHandle;
100757 db->aExtension[db->nExtension++] = handle;
100758 return SQLITE_OK;
100760 SQLITE_API int sqlite3_load_extension(
100761 sqlite3 *db, /* Load the extension into this database connection */
100762 const char *zFile, /* Name of the shared library containing extension */
100763 const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
100764 char **pzErrMsg /* Put error message here if not 0 */
100766 int rc;
100767 sqlite3_mutex_enter(db->mutex);
100768 rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
100769 rc = sqlite3ApiExit(db, rc);
100770 sqlite3_mutex_leave(db->mutex);
100771 return rc;
100775 ** Call this routine when the database connection is closing in order
100776 ** to clean up loaded extensions
100778 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
100779 int i;
100780 assert( sqlite3_mutex_held(db->mutex) );
100781 for(i=0; i<db->nExtension; i++){
100782 sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
100784 sqlite3DbFree(db, db->aExtension);
100788 ** Enable or disable extension loading. Extension loading is disabled by
100789 ** default so as not to open security holes in older applications.
100791 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
100792 sqlite3_mutex_enter(db->mutex);
100793 if( onoff ){
100794 db->flags |= SQLITE_LoadExtension;
100795 }else{
100796 db->flags &= ~SQLITE_LoadExtension;
100798 sqlite3_mutex_leave(db->mutex);
100799 return SQLITE_OK;
100802 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
100805 ** The auto-extension code added regardless of whether or not extension
100806 ** loading is supported. We need a dummy sqlite3Apis pointer for that
100807 ** code if regular extension loading is not available. This is that
100808 ** dummy pointer.
100810 #ifdef SQLITE_OMIT_LOAD_EXTENSION
100811 static const sqlite3_api_routines sqlite3Apis = { 0 };
100812 #endif
100816 ** The following object holds the list of automatically loaded
100817 ** extensions.
100819 ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
100820 ** mutex must be held while accessing this list.
100822 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
100823 static SQLITE_WSD struct sqlite3AutoExtList {
100824 int nExt; /* Number of entries in aExt[] */
100825 void (**aExt)(void); /* Pointers to the extension init functions */
100826 } sqlite3Autoext = { 0, 0 };
100828 /* The "wsdAutoext" macro will resolve to the autoextension
100829 ** state vector. If writable static data is unsupported on the target,
100830 ** we have to locate the state vector at run-time. In the more common
100831 ** case where writable static data is supported, wsdStat can refer directly
100832 ** to the "sqlite3Autoext" state vector declared above.
100834 #ifdef SQLITE_OMIT_WSD
100835 # define wsdAutoextInit \
100836 sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
100837 # define wsdAutoext x[0]
100838 #else
100839 # define wsdAutoextInit
100840 # define wsdAutoext sqlite3Autoext
100841 #endif
100845 ** Register a statically linked extension that is automatically
100846 ** loaded by every new database connection.
100848 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
100849 int rc = SQLITE_OK;
100850 #ifndef SQLITE_OMIT_AUTOINIT
100851 rc = sqlite3_initialize();
100852 if( rc ){
100853 return rc;
100854 }else
100855 #endif
100857 int i;
100858 #if SQLITE_THREADSAFE
100859 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
100860 #endif
100861 wsdAutoextInit;
100862 sqlite3_mutex_enter(mutex);
100863 for(i=0; i<wsdAutoext.nExt; i++){
100864 if( wsdAutoext.aExt[i]==xInit ) break;
100866 if( i==wsdAutoext.nExt ){
100867 int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
100868 void (**aNew)(void);
100869 aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
100870 if( aNew==0 ){
100871 rc = SQLITE_NOMEM;
100872 }else{
100873 wsdAutoext.aExt = aNew;
100874 wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
100875 wsdAutoext.nExt++;
100878 sqlite3_mutex_leave(mutex);
100879 assert( (rc&0xff)==rc );
100880 return rc;
100885 ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
100886 ** set of routines that is invoked for each new database connection, if it
100887 ** is currently on the list. If xInit is not on the list, then this
100888 ** routine is a no-op.
100890 ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
100891 ** was not on the list.
100893 SQLITE_API int sqlite3_cancel_auto_extension(void (*xInit)(void)){
100894 #if SQLITE_THREADSAFE
100895 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
100896 #endif
100897 int i;
100898 int n = 0;
100899 wsdAutoextInit;
100900 sqlite3_mutex_enter(mutex);
100901 for(i=wsdAutoext.nExt-1; i>=0; i--){
100902 if( wsdAutoext.aExt[i]==xInit ){
100903 wsdAutoext.nExt--;
100904 wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
100906 break;
100909 sqlite3_mutex_leave(mutex);
100910 return n;
100914 ** Reset the automatic extension loading mechanism.
100916 SQLITE_API void sqlite3_reset_auto_extension(void){
100917 #ifndef SQLITE_OMIT_AUTOINIT
100918 if( sqlite3_initialize()==SQLITE_OK )
100919 #endif
100921 #if SQLITE_THREADSAFE
100922 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
100923 #endif
100924 wsdAutoextInit;
100925 sqlite3_mutex_enter(mutex);
100926 sqlite3_free(wsdAutoext.aExt);
100927 wsdAutoext.aExt = 0;
100928 wsdAutoext.nExt = 0;
100929 sqlite3_mutex_leave(mutex);
100934 ** Load all automatic extensions.
100936 ** If anything goes wrong, set an error in the database connection.
100938 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
100939 int i;
100940 int go = 1;
100941 int rc;
100942 int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
100944 wsdAutoextInit;
100945 if( wsdAutoext.nExt==0 ){
100946 /* Common case: early out without every having to acquire a mutex */
100947 return;
100949 for(i=0; go; i++){
100950 char *zErrmsg;
100951 #if SQLITE_THREADSAFE
100952 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
100953 #endif
100954 sqlite3_mutex_enter(mutex);
100955 if( i>=wsdAutoext.nExt ){
100956 xInit = 0;
100957 go = 0;
100958 }else{
100959 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
100960 wsdAutoext.aExt[i];
100962 sqlite3_mutex_leave(mutex);
100963 zErrmsg = 0;
100964 if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
100965 sqlite3ErrorWithMsg(db, rc,
100966 "automatic extension loading failed: %s", zErrmsg);
100967 go = 0;
100969 sqlite3_free(zErrmsg);
100973 /************** End of loadext.c *********************************************/
100974 /************** Begin file pragma.c ******************************************/
100976 ** 2003 April 6
100978 ** The author disclaims copyright to this source code. In place of
100979 ** a legal notice, here is a blessing:
100981 ** May you do good and not evil.
100982 ** May you find forgiveness for yourself and forgive others.
100983 ** May you share freely, never taking more than you give.
100985 *************************************************************************
100986 ** This file contains code used to implement the PRAGMA command.
100989 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
100990 # if defined(__APPLE__)
100991 # define SQLITE_ENABLE_LOCKING_STYLE 1
100992 # else
100993 # define SQLITE_ENABLE_LOCKING_STYLE 0
100994 # endif
100995 #endif
100997 /***************************************************************************
100998 ** The next block of code, including the PragTyp_XXXX macro definitions and
100999 ** the aPragmaName[] object is composed of generated code. DO NOT EDIT.
101001 ** To add new pragmas, edit the code in ../tool/mkpragmatab.tcl and rerun
101002 ** that script. Then copy/paste the output in place of the following:
101004 #define PragTyp_HEADER_VALUE 0
101005 #define PragTyp_AUTO_VACUUM 1
101006 #define PragTyp_FLAG 2
101007 #define PragTyp_BUSY_TIMEOUT 3
101008 #define PragTyp_CACHE_SIZE 4
101009 #define PragTyp_CASE_SENSITIVE_LIKE 5
101010 #define PragTyp_COLLATION_LIST 6
101011 #define PragTyp_COMPILE_OPTIONS 7
101012 #define PragTyp_DATA_STORE_DIRECTORY 8
101013 #define PragTyp_DATABASE_LIST 9
101014 #define PragTyp_DEFAULT_CACHE_SIZE 10
101015 #define PragTyp_ENCODING 11
101016 #define PragTyp_FOREIGN_KEY_CHECK 12
101017 #define PragTyp_FOREIGN_KEY_LIST 13
101018 #define PragTyp_INCREMENTAL_VACUUM 14
101019 #define PragTyp_INDEX_INFO 15
101020 #define PragTyp_INDEX_LIST 16
101021 #define PragTyp_INTEGRITY_CHECK 17
101022 #define PragTyp_JOURNAL_MODE 18
101023 #define PragTyp_JOURNAL_SIZE_LIMIT 19
101024 #define PragTyp_LOCK_PROXY_FILE 20
101025 #define PragTyp_LOCKING_MODE 21
101026 #define PragTyp_PAGE_COUNT 22
101027 #define PragTyp_MMAP_SIZE 23
101028 #define PragTyp_PAGE_SIZE 24
101029 #define PragTyp_SECURE_DELETE 25
101030 #define PragTyp_SHRINK_MEMORY 26
101031 #define PragTyp_SOFT_HEAP_LIMIT 27
101032 #define PragTyp_STATS 28
101033 #define PragTyp_SYNCHRONOUS 29
101034 #define PragTyp_TABLE_INFO 30
101035 #define PragTyp_TEMP_STORE 31
101036 #define PragTyp_TEMP_STORE_DIRECTORY 32
101037 #define PragTyp_THREADS 33
101038 #define PragTyp_WAL_AUTOCHECKPOINT 34
101039 #define PragTyp_WAL_CHECKPOINT 35
101040 #define PragTyp_ACTIVATE_EXTENSIONS 36
101041 #define PragTyp_HEXKEY 37
101042 #define PragTyp_KEY 38
101043 #define PragTyp_REKEY 39
101044 #define PragTyp_LOCK_STATUS 40
101045 #define PragTyp_PARSER_TRACE 41
101046 #define PragFlag_NeedSchema 0x01
101047 static const struct sPragmaNames {
101048 const char *const zName; /* Name of pragma */
101049 u8 ePragTyp; /* PragTyp_XXX value */
101050 u8 mPragFlag; /* Zero or more PragFlag_XXX values */
101051 u32 iArg; /* Extra argument */
101052 } aPragmaNames[] = {
101053 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
101054 { /* zName: */ "activate_extensions",
101055 /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
101056 /* ePragFlag: */ 0,
101057 /* iArg: */ 0 },
101058 #endif
101059 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
101060 { /* zName: */ "application_id",
101061 /* ePragTyp: */ PragTyp_HEADER_VALUE,
101062 /* ePragFlag: */ 0,
101063 /* iArg: */ 0 },
101064 #endif
101065 #if !defined(SQLITE_OMIT_AUTOVACUUM)
101066 { /* zName: */ "auto_vacuum",
101067 /* ePragTyp: */ PragTyp_AUTO_VACUUM,
101068 /* ePragFlag: */ PragFlag_NeedSchema,
101069 /* iArg: */ 0 },
101070 #endif
101071 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101072 #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
101073 { /* zName: */ "automatic_index",
101074 /* ePragTyp: */ PragTyp_FLAG,
101075 /* ePragFlag: */ 0,
101076 /* iArg: */ SQLITE_AutoIndex },
101077 #endif
101078 #endif
101079 { /* zName: */ "busy_timeout",
101080 /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
101081 /* ePragFlag: */ 0,
101082 /* iArg: */ 0 },
101083 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101084 { /* zName: */ "cache_size",
101085 /* ePragTyp: */ PragTyp_CACHE_SIZE,
101086 /* ePragFlag: */ PragFlag_NeedSchema,
101087 /* iArg: */ 0 },
101088 #endif
101089 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101090 { /* zName: */ "cache_spill",
101091 /* ePragTyp: */ PragTyp_FLAG,
101092 /* ePragFlag: */ 0,
101093 /* iArg: */ SQLITE_CacheSpill },
101094 #endif
101095 { /* zName: */ "case_sensitive_like",
101096 /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
101097 /* ePragFlag: */ 0,
101098 /* iArg: */ 0 },
101099 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101100 { /* zName: */ "checkpoint_fullfsync",
101101 /* ePragTyp: */ PragTyp_FLAG,
101102 /* ePragFlag: */ 0,
101103 /* iArg: */ SQLITE_CkptFullFSync },
101104 #endif
101105 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
101106 { /* zName: */ "collation_list",
101107 /* ePragTyp: */ PragTyp_COLLATION_LIST,
101108 /* ePragFlag: */ 0,
101109 /* iArg: */ 0 },
101110 #endif
101111 #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
101112 { /* zName: */ "compile_options",
101113 /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
101114 /* ePragFlag: */ 0,
101115 /* iArg: */ 0 },
101116 #endif
101117 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101118 { /* zName: */ "count_changes",
101119 /* ePragTyp: */ PragTyp_FLAG,
101120 /* ePragFlag: */ 0,
101121 /* iArg: */ SQLITE_CountRows },
101122 #endif
101123 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
101124 { /* zName: */ "data_store_directory",
101125 /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
101126 /* ePragFlag: */ 0,
101127 /* iArg: */ 0 },
101128 #endif
101129 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
101130 { /* zName: */ "database_list",
101131 /* ePragTyp: */ PragTyp_DATABASE_LIST,
101132 /* ePragFlag: */ PragFlag_NeedSchema,
101133 /* iArg: */ 0 },
101134 #endif
101135 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
101136 { /* zName: */ "default_cache_size",
101137 /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
101138 /* ePragFlag: */ PragFlag_NeedSchema,
101139 /* iArg: */ 0 },
101140 #endif
101141 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101142 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
101143 { /* zName: */ "defer_foreign_keys",
101144 /* ePragTyp: */ PragTyp_FLAG,
101145 /* ePragFlag: */ 0,
101146 /* iArg: */ SQLITE_DeferFKs },
101147 #endif
101148 #endif
101149 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101150 { /* zName: */ "empty_result_callbacks",
101151 /* ePragTyp: */ PragTyp_FLAG,
101152 /* ePragFlag: */ 0,
101153 /* iArg: */ SQLITE_NullCallback },
101154 #endif
101155 #if !defined(SQLITE_OMIT_UTF16)
101156 { /* zName: */ "encoding",
101157 /* ePragTyp: */ PragTyp_ENCODING,
101158 /* ePragFlag: */ 0,
101159 /* iArg: */ 0 },
101160 #endif
101161 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
101162 { /* zName: */ "foreign_key_check",
101163 /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
101164 /* ePragFlag: */ PragFlag_NeedSchema,
101165 /* iArg: */ 0 },
101166 #endif
101167 #if !defined(SQLITE_OMIT_FOREIGN_KEY)
101168 { /* zName: */ "foreign_key_list",
101169 /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
101170 /* ePragFlag: */ PragFlag_NeedSchema,
101171 /* iArg: */ 0 },
101172 #endif
101173 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101174 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
101175 { /* zName: */ "foreign_keys",
101176 /* ePragTyp: */ PragTyp_FLAG,
101177 /* ePragFlag: */ 0,
101178 /* iArg: */ SQLITE_ForeignKeys },
101179 #endif
101180 #endif
101181 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
101182 { /* zName: */ "freelist_count",
101183 /* ePragTyp: */ PragTyp_HEADER_VALUE,
101184 /* ePragFlag: */ 0,
101185 /* iArg: */ 0 },
101186 #endif
101187 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101188 { /* zName: */ "full_column_names",
101189 /* ePragTyp: */ PragTyp_FLAG,
101190 /* ePragFlag: */ 0,
101191 /* iArg: */ SQLITE_FullColNames },
101192 { /* zName: */ "fullfsync",
101193 /* ePragTyp: */ PragTyp_FLAG,
101194 /* ePragFlag: */ 0,
101195 /* iArg: */ SQLITE_FullFSync },
101196 #endif
101197 #if defined(SQLITE_HAS_CODEC)
101198 { /* zName: */ "hexkey",
101199 /* ePragTyp: */ PragTyp_HEXKEY,
101200 /* ePragFlag: */ 0,
101201 /* iArg: */ 0 },
101202 { /* zName: */ "hexrekey",
101203 /* ePragTyp: */ PragTyp_HEXKEY,
101204 /* ePragFlag: */ 0,
101205 /* iArg: */ 0 },
101206 #endif
101207 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101208 #if !defined(SQLITE_OMIT_CHECK)
101209 { /* zName: */ "ignore_check_constraints",
101210 /* ePragTyp: */ PragTyp_FLAG,
101211 /* ePragFlag: */ 0,
101212 /* iArg: */ SQLITE_IgnoreChecks },
101213 #endif
101214 #endif
101215 #if !defined(SQLITE_OMIT_AUTOVACUUM)
101216 { /* zName: */ "incremental_vacuum",
101217 /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
101218 /* ePragFlag: */ PragFlag_NeedSchema,
101219 /* iArg: */ 0 },
101220 #endif
101221 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
101222 { /* zName: */ "index_info",
101223 /* ePragTyp: */ PragTyp_INDEX_INFO,
101224 /* ePragFlag: */ PragFlag_NeedSchema,
101225 /* iArg: */ 0 },
101226 { /* zName: */ "index_list",
101227 /* ePragTyp: */ PragTyp_INDEX_LIST,
101228 /* ePragFlag: */ PragFlag_NeedSchema,
101229 /* iArg: */ 0 },
101230 #endif
101231 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
101232 { /* zName: */ "integrity_check",
101233 /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
101234 /* ePragFlag: */ PragFlag_NeedSchema,
101235 /* iArg: */ 0 },
101236 #endif
101237 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101238 { /* zName: */ "journal_mode",
101239 /* ePragTyp: */ PragTyp_JOURNAL_MODE,
101240 /* ePragFlag: */ PragFlag_NeedSchema,
101241 /* iArg: */ 0 },
101242 { /* zName: */ "journal_size_limit",
101243 /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
101244 /* ePragFlag: */ 0,
101245 /* iArg: */ 0 },
101246 #endif
101247 #if defined(SQLITE_HAS_CODEC)
101248 { /* zName: */ "key",
101249 /* ePragTyp: */ PragTyp_KEY,
101250 /* ePragFlag: */ 0,
101251 /* iArg: */ 0 },
101252 #endif
101253 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101254 { /* zName: */ "legacy_file_format",
101255 /* ePragTyp: */ PragTyp_FLAG,
101256 /* ePragFlag: */ 0,
101257 /* iArg: */ SQLITE_LegacyFileFmt },
101258 #endif
101259 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
101260 { /* zName: */ "lock_proxy_file",
101261 /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
101262 /* ePragFlag: */ 0,
101263 /* iArg: */ 0 },
101264 #endif
101265 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
101266 { /* zName: */ "lock_status",
101267 /* ePragTyp: */ PragTyp_LOCK_STATUS,
101268 /* ePragFlag: */ 0,
101269 /* iArg: */ 0 },
101270 #endif
101271 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101272 { /* zName: */ "locking_mode",
101273 /* ePragTyp: */ PragTyp_LOCKING_MODE,
101274 /* ePragFlag: */ 0,
101275 /* iArg: */ 0 },
101276 { /* zName: */ "max_page_count",
101277 /* ePragTyp: */ PragTyp_PAGE_COUNT,
101278 /* ePragFlag: */ PragFlag_NeedSchema,
101279 /* iArg: */ 0 },
101280 { /* zName: */ "mmap_size",
101281 /* ePragTyp: */ PragTyp_MMAP_SIZE,
101282 /* ePragFlag: */ 0,
101283 /* iArg: */ 0 },
101284 { /* zName: */ "page_count",
101285 /* ePragTyp: */ PragTyp_PAGE_COUNT,
101286 /* ePragFlag: */ PragFlag_NeedSchema,
101287 /* iArg: */ 0 },
101288 { /* zName: */ "page_size",
101289 /* ePragTyp: */ PragTyp_PAGE_SIZE,
101290 /* ePragFlag: */ 0,
101291 /* iArg: */ 0 },
101292 #endif
101293 #if defined(SQLITE_DEBUG)
101294 { /* zName: */ "parser_trace",
101295 /* ePragTyp: */ PragTyp_PARSER_TRACE,
101296 /* ePragFlag: */ 0,
101297 /* iArg: */ 0 },
101298 #endif
101299 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101300 { /* zName: */ "query_only",
101301 /* ePragTyp: */ PragTyp_FLAG,
101302 /* ePragFlag: */ 0,
101303 /* iArg: */ SQLITE_QueryOnly },
101304 #endif
101305 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
101306 { /* zName: */ "quick_check",
101307 /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
101308 /* ePragFlag: */ PragFlag_NeedSchema,
101309 /* iArg: */ 0 },
101310 #endif
101311 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101312 { /* zName: */ "read_uncommitted",
101313 /* ePragTyp: */ PragTyp_FLAG,
101314 /* ePragFlag: */ 0,
101315 /* iArg: */ SQLITE_ReadUncommitted },
101316 { /* zName: */ "recursive_triggers",
101317 /* ePragTyp: */ PragTyp_FLAG,
101318 /* ePragFlag: */ 0,
101319 /* iArg: */ SQLITE_RecTriggers },
101320 #endif
101321 #if defined(SQLITE_HAS_CODEC)
101322 { /* zName: */ "rekey",
101323 /* ePragTyp: */ PragTyp_REKEY,
101324 /* ePragFlag: */ 0,
101325 /* iArg: */ 0 },
101326 #endif
101327 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101328 { /* zName: */ "reverse_unordered_selects",
101329 /* ePragTyp: */ PragTyp_FLAG,
101330 /* ePragFlag: */ 0,
101331 /* iArg: */ SQLITE_ReverseOrder },
101332 #endif
101333 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
101334 { /* zName: */ "schema_version",
101335 /* ePragTyp: */ PragTyp_HEADER_VALUE,
101336 /* ePragFlag: */ 0,
101337 /* iArg: */ 0 },
101338 #endif
101339 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101340 { /* zName: */ "secure_delete",
101341 /* ePragTyp: */ PragTyp_SECURE_DELETE,
101342 /* ePragFlag: */ 0,
101343 /* iArg: */ 0 },
101344 #endif
101345 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101346 { /* zName: */ "short_column_names",
101347 /* ePragTyp: */ PragTyp_FLAG,
101348 /* ePragFlag: */ 0,
101349 /* iArg: */ SQLITE_ShortColNames },
101350 #endif
101351 { /* zName: */ "shrink_memory",
101352 /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
101353 /* ePragFlag: */ 0,
101354 /* iArg: */ 0 },
101355 { /* zName: */ "soft_heap_limit",
101356 /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
101357 /* ePragFlag: */ 0,
101358 /* iArg: */ 0 },
101359 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101360 #if defined(SQLITE_DEBUG)
101361 { /* zName: */ "sql_trace",
101362 /* ePragTyp: */ PragTyp_FLAG,
101363 /* ePragFlag: */ 0,
101364 /* iArg: */ SQLITE_SqlTrace },
101365 #endif
101366 #endif
101367 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
101368 { /* zName: */ "stats",
101369 /* ePragTyp: */ PragTyp_STATS,
101370 /* ePragFlag: */ PragFlag_NeedSchema,
101371 /* iArg: */ 0 },
101372 #endif
101373 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101374 { /* zName: */ "synchronous",
101375 /* ePragTyp: */ PragTyp_SYNCHRONOUS,
101376 /* ePragFlag: */ PragFlag_NeedSchema,
101377 /* iArg: */ 0 },
101378 #endif
101379 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
101380 { /* zName: */ "table_info",
101381 /* ePragTyp: */ PragTyp_TABLE_INFO,
101382 /* ePragFlag: */ PragFlag_NeedSchema,
101383 /* iArg: */ 0 },
101384 #endif
101385 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101386 { /* zName: */ "temp_store",
101387 /* ePragTyp: */ PragTyp_TEMP_STORE,
101388 /* ePragFlag: */ 0,
101389 /* iArg: */ 0 },
101390 { /* zName: */ "temp_store_directory",
101391 /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
101392 /* ePragFlag: */ 0,
101393 /* iArg: */ 0 },
101394 #endif
101395 { /* zName: */ "threads",
101396 /* ePragTyp: */ PragTyp_THREADS,
101397 /* ePragFlag: */ 0,
101398 /* iArg: */ 0 },
101399 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
101400 { /* zName: */ "user_version",
101401 /* ePragTyp: */ PragTyp_HEADER_VALUE,
101402 /* ePragFlag: */ 0,
101403 /* iArg: */ 0 },
101404 #endif
101405 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101406 #if defined(SQLITE_DEBUG)
101407 { /* zName: */ "vdbe_addoptrace",
101408 /* ePragTyp: */ PragTyp_FLAG,
101409 /* ePragFlag: */ 0,
101410 /* iArg: */ SQLITE_VdbeAddopTrace },
101411 { /* zName: */ "vdbe_debug",
101412 /* ePragTyp: */ PragTyp_FLAG,
101413 /* ePragFlag: */ 0,
101414 /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
101415 { /* zName: */ "vdbe_eqp",
101416 /* ePragTyp: */ PragTyp_FLAG,
101417 /* ePragFlag: */ 0,
101418 /* iArg: */ SQLITE_VdbeEQP },
101419 { /* zName: */ "vdbe_listing",
101420 /* ePragTyp: */ PragTyp_FLAG,
101421 /* ePragFlag: */ 0,
101422 /* iArg: */ SQLITE_VdbeListing },
101423 { /* zName: */ "vdbe_trace",
101424 /* ePragTyp: */ PragTyp_FLAG,
101425 /* ePragFlag: */ 0,
101426 /* iArg: */ SQLITE_VdbeTrace },
101427 #endif
101428 #endif
101429 #if !defined(SQLITE_OMIT_WAL)
101430 { /* zName: */ "wal_autocheckpoint",
101431 /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
101432 /* ePragFlag: */ 0,
101433 /* iArg: */ 0 },
101434 { /* zName: */ "wal_checkpoint",
101435 /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
101436 /* ePragFlag: */ PragFlag_NeedSchema,
101437 /* iArg: */ 0 },
101438 #endif
101439 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101440 { /* zName: */ "writable_schema",
101441 /* ePragTyp: */ PragTyp_FLAG,
101442 /* ePragFlag: */ 0,
101443 /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
101444 #endif
101446 /* Number of pragmas: 57 on by default, 70 total. */
101447 /* End of the automatically generated pragma table.
101448 ***************************************************************************/
101451 ** Interpret the given string as a safety level. Return 0 for OFF,
101452 ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
101453 ** unrecognized string argument. The FULL option is disallowed
101454 ** if the omitFull parameter it 1.
101456 ** Note that the values returned are one less that the values that
101457 ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
101458 ** to support legacy SQL code. The safety level used to be boolean
101459 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
101461 static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
101462 /* 123456789 123456789 */
101463 static const char zText[] = "onoffalseyestruefull";
101464 static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
101465 static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
101466 static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
101467 int i, n;
101468 if( sqlite3Isdigit(*z) ){
101469 return (u8)sqlite3Atoi(z);
101471 n = sqlite3Strlen30(z);
101472 for(i=0; i<ArraySize(iLength)-omitFull; i++){
101473 if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
101474 return iValue[i];
101477 return dflt;
101481 ** Interpret the given string as a boolean value.
101483 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
101484 return getSafetyLevel(z,1,dflt)!=0;
101487 /* The sqlite3GetBoolean() function is used by other modules but the
101488 ** remainder of this file is specific to PRAGMA processing. So omit
101489 ** the rest of the file if PRAGMAs are omitted from the build.
101491 #if !defined(SQLITE_OMIT_PRAGMA)
101494 ** Interpret the given string as a locking mode value.
101496 static int getLockingMode(const char *z){
101497 if( z ){
101498 if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
101499 if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
101501 return PAGER_LOCKINGMODE_QUERY;
101504 #ifndef SQLITE_OMIT_AUTOVACUUM
101506 ** Interpret the given string as an auto-vacuum mode value.
101508 ** The following strings, "none", "full" and "incremental" are
101509 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
101511 static int getAutoVacuum(const char *z){
101512 int i;
101513 if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
101514 if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
101515 if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
101516 i = sqlite3Atoi(z);
101517 return (u8)((i>=0&&i<=2)?i:0);
101519 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
101521 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
101523 ** Interpret the given string as a temp db location. Return 1 for file
101524 ** backed temporary databases, 2 for the Red-Black tree in memory database
101525 ** and 0 to use the compile-time default.
101527 static int getTempStore(const char *z){
101528 if( z[0]>='0' && z[0]<='2' ){
101529 return z[0] - '0';
101530 }else if( sqlite3StrICmp(z, "file")==0 ){
101531 return 1;
101532 }else if( sqlite3StrICmp(z, "memory")==0 ){
101533 return 2;
101534 }else{
101535 return 0;
101538 #endif /* SQLITE_PAGER_PRAGMAS */
101540 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
101542 ** Invalidate temp storage, either when the temp storage is changed
101543 ** from default, or when 'file' and the temp_store_directory has changed
101545 static int invalidateTempStorage(Parse *pParse){
101546 sqlite3 *db = pParse->db;
101547 if( db->aDb[1].pBt!=0 ){
101548 if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
101549 sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
101550 "from within a transaction");
101551 return SQLITE_ERROR;
101553 sqlite3BtreeClose(db->aDb[1].pBt);
101554 db->aDb[1].pBt = 0;
101555 sqlite3ResetAllSchemasOfConnection(db);
101557 return SQLITE_OK;
101559 #endif /* SQLITE_PAGER_PRAGMAS */
101561 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
101563 ** If the TEMP database is open, close it and mark the database schema
101564 ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
101565 ** or DEFAULT_TEMP_STORE pragmas.
101567 static int changeTempStorage(Parse *pParse, const char *zStorageType){
101568 int ts = getTempStore(zStorageType);
101569 sqlite3 *db = pParse->db;
101570 if( db->temp_store==ts ) return SQLITE_OK;
101571 if( invalidateTempStorage( pParse ) != SQLITE_OK ){
101572 return SQLITE_ERROR;
101574 db->temp_store = (u8)ts;
101575 return SQLITE_OK;
101577 #endif /* SQLITE_PAGER_PRAGMAS */
101580 ** Generate code to return a single integer value.
101582 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
101583 Vdbe *v = sqlite3GetVdbe(pParse);
101584 int mem = ++pParse->nMem;
101585 i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
101586 if( pI64 ){
101587 memcpy(pI64, &value, sizeof(value));
101589 sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
101590 sqlite3VdbeSetNumCols(v, 1);
101591 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
101592 sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
101597 ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
101598 ** set these values for all pagers.
101600 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
101601 static void setAllPagerFlags(sqlite3 *db){
101602 if( db->autoCommit ){
101603 Db *pDb = db->aDb;
101604 int n = db->nDb;
101605 assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
101606 assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
101607 assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
101608 assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
101609 == PAGER_FLAGS_MASK );
101610 assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
101611 while( (n--) > 0 ){
101612 if( pDb->pBt ){
101613 sqlite3BtreeSetPagerFlags(pDb->pBt,
101614 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
101616 pDb++;
101620 #else
101621 # define setAllPagerFlags(X) /* no-op */
101622 #endif
101626 ** Return a human-readable name for a constraint resolution action.
101628 #ifndef SQLITE_OMIT_FOREIGN_KEY
101629 static const char *actionName(u8 action){
101630 const char *zName;
101631 switch( action ){
101632 case OE_SetNull: zName = "SET NULL"; break;
101633 case OE_SetDflt: zName = "SET DEFAULT"; break;
101634 case OE_Cascade: zName = "CASCADE"; break;
101635 case OE_Restrict: zName = "RESTRICT"; break;
101636 default: zName = "NO ACTION";
101637 assert( action==OE_None ); break;
101639 return zName;
101641 #endif
101645 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
101646 ** defined in pager.h. This function returns the associated lowercase
101647 ** journal-mode name.
101649 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
101650 static char * const azModeName[] = {
101651 "delete", "persist", "off", "truncate", "memory"
101652 #ifndef SQLITE_OMIT_WAL
101653 , "wal"
101654 #endif
101656 assert( PAGER_JOURNALMODE_DELETE==0 );
101657 assert( PAGER_JOURNALMODE_PERSIST==1 );
101658 assert( PAGER_JOURNALMODE_OFF==2 );
101659 assert( PAGER_JOURNALMODE_TRUNCATE==3 );
101660 assert( PAGER_JOURNALMODE_MEMORY==4 );
101661 assert( PAGER_JOURNALMODE_WAL==5 );
101662 assert( eMode>=0 && eMode<=ArraySize(azModeName) );
101664 if( eMode==ArraySize(azModeName) ) return 0;
101665 return azModeName[eMode];
101669 ** Process a pragma statement.
101671 ** Pragmas are of this form:
101673 ** PRAGMA [database.]id [= value]
101675 ** The identifier might also be a string. The value is a string, and
101676 ** identifier, or a number. If minusFlag is true, then the value is
101677 ** a number that was preceded by a minus sign.
101679 ** If the left side is "database.id" then pId1 is the database name
101680 ** and pId2 is the id. If the left side is just "id" then pId1 is the
101681 ** id and pId2 is any empty string.
101683 SQLITE_PRIVATE void sqlite3Pragma(
101684 Parse *pParse,
101685 Token *pId1, /* First part of [database.]id field */
101686 Token *pId2, /* Second part of [database.]id field, or NULL */
101687 Token *pValue, /* Token for <value>, or NULL */
101688 int minusFlag /* True if a '-' sign preceded <value> */
101690 char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
101691 char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
101692 const char *zDb = 0; /* The database name */
101693 Token *pId; /* Pointer to <id> token */
101694 char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
101695 int iDb; /* Database index for <database> */
101696 int lwr, upr, mid; /* Binary search bounds */
101697 int rc; /* return value form SQLITE_FCNTL_PRAGMA */
101698 sqlite3 *db = pParse->db; /* The database connection */
101699 Db *pDb; /* The specific database being pragmaed */
101700 Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
101702 if( v==0 ) return;
101703 sqlite3VdbeRunOnlyOnce(v);
101704 pParse->nMem = 2;
101706 /* Interpret the [database.] part of the pragma statement. iDb is the
101707 ** index of the database this pragma is being applied to in db.aDb[]. */
101708 iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
101709 if( iDb<0 ) return;
101710 pDb = &db->aDb[iDb];
101712 /* If the temp database has been explicitly named as part of the
101713 ** pragma, make sure it is open.
101715 if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
101716 return;
101719 zLeft = sqlite3NameFromToken(db, pId);
101720 if( !zLeft ) return;
101721 if( minusFlag ){
101722 zRight = sqlite3MPrintf(db, "-%T", pValue);
101723 }else{
101724 zRight = sqlite3NameFromToken(db, pValue);
101727 assert( pId2 );
101728 zDb = pId2->n>0 ? pDb->zName : 0;
101729 if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
101730 goto pragma_out;
101733 /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
101734 ** connection. If it returns SQLITE_OK, then assume that the VFS
101735 ** handled the pragma and generate a no-op prepared statement.
101737 aFcntl[0] = 0;
101738 aFcntl[1] = zLeft;
101739 aFcntl[2] = zRight;
101740 aFcntl[3] = 0;
101741 db->busyHandler.nBusy = 0;
101742 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
101743 if( rc==SQLITE_OK ){
101744 if( aFcntl[0] ){
101745 int mem = ++pParse->nMem;
101746 sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
101747 sqlite3VdbeSetNumCols(v, 1);
101748 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
101749 sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
101750 sqlite3_free(aFcntl[0]);
101752 goto pragma_out;
101754 if( rc!=SQLITE_NOTFOUND ){
101755 if( aFcntl[0] ){
101756 sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
101757 sqlite3_free(aFcntl[0]);
101759 pParse->nErr++;
101760 pParse->rc = rc;
101761 goto pragma_out;
101764 /* Locate the pragma in the lookup table */
101765 lwr = 0;
101766 upr = ArraySize(aPragmaNames)-1;
101767 while( lwr<=upr ){
101768 mid = (lwr+upr)/2;
101769 rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
101770 if( rc==0 ) break;
101771 if( rc<0 ){
101772 upr = mid - 1;
101773 }else{
101774 lwr = mid + 1;
101777 if( lwr>upr ) goto pragma_out;
101779 /* Make sure the database schema is loaded if the pragma requires that */
101780 if( (aPragmaNames[mid].mPragFlag & PragFlag_NeedSchema)!=0 ){
101781 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
101784 /* Jump to the appropriate pragma handler */
101785 switch( aPragmaNames[mid].ePragTyp ){
101787 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
101789 ** PRAGMA [database.]default_cache_size
101790 ** PRAGMA [database.]default_cache_size=N
101792 ** The first form reports the current persistent setting for the
101793 ** page cache size. The value returned is the maximum number of
101794 ** pages in the page cache. The second form sets both the current
101795 ** page cache size value and the persistent page cache size value
101796 ** stored in the database file.
101798 ** Older versions of SQLite would set the default cache size to a
101799 ** negative number to indicate synchronous=OFF. These days, synchronous
101800 ** is always on by default regardless of the sign of the default cache
101801 ** size. But continue to take the absolute value of the default cache
101802 ** size of historical compatibility.
101804 case PragTyp_DEFAULT_CACHE_SIZE: {
101805 static const int iLn = VDBE_OFFSET_LINENO(2);
101806 static const VdbeOpList getCacheSize[] = {
101807 { OP_Transaction, 0, 0, 0}, /* 0 */
101808 { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
101809 { OP_IfPos, 1, 8, 0},
101810 { OP_Integer, 0, 2, 0},
101811 { OP_Subtract, 1, 2, 1},
101812 { OP_IfPos, 1, 8, 0},
101813 { OP_Integer, 0, 1, 0}, /* 6 */
101814 { OP_Noop, 0, 0, 0},
101815 { OP_ResultRow, 1, 1, 0},
101817 int addr;
101818 sqlite3VdbeUsesBtree(v, iDb);
101819 if( !zRight ){
101820 sqlite3VdbeSetNumCols(v, 1);
101821 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
101822 pParse->nMem += 2;
101823 addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize,iLn);
101824 sqlite3VdbeChangeP1(v, addr, iDb);
101825 sqlite3VdbeChangeP1(v, addr+1, iDb);
101826 sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
101827 }else{
101828 int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
101829 sqlite3BeginWriteOperation(pParse, 0, iDb);
101830 sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
101831 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
101832 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101833 pDb->pSchema->cache_size = size;
101834 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
101836 break;
101838 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
101840 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101842 ** PRAGMA [database.]page_size
101843 ** PRAGMA [database.]page_size=N
101845 ** The first form reports the current setting for the
101846 ** database page size in bytes. The second form sets the
101847 ** database page size value. The value can only be set if
101848 ** the database has not yet been created.
101850 case PragTyp_PAGE_SIZE: {
101851 Btree *pBt = pDb->pBt;
101852 assert( pBt!=0 );
101853 if( !zRight ){
101854 int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
101855 returnSingleInt(pParse, "page_size", size);
101856 }else{
101857 /* Malloc may fail when setting the page-size, as there is an internal
101858 ** buffer that the pager module resizes using sqlite3_realloc().
101860 db->nextPagesize = sqlite3Atoi(zRight);
101861 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
101862 db->mallocFailed = 1;
101865 break;
101869 ** PRAGMA [database.]secure_delete
101870 ** PRAGMA [database.]secure_delete=ON/OFF
101872 ** The first form reports the current setting for the
101873 ** secure_delete flag. The second form changes the secure_delete
101874 ** flag setting and reports thenew value.
101876 case PragTyp_SECURE_DELETE: {
101877 Btree *pBt = pDb->pBt;
101878 int b = -1;
101879 assert( pBt!=0 );
101880 if( zRight ){
101881 b = sqlite3GetBoolean(zRight, 0);
101883 if( pId2->n==0 && b>=0 ){
101884 int ii;
101885 for(ii=0; ii<db->nDb; ii++){
101886 sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
101889 b = sqlite3BtreeSecureDelete(pBt, b);
101890 returnSingleInt(pParse, "secure_delete", b);
101891 break;
101895 ** PRAGMA [database.]max_page_count
101896 ** PRAGMA [database.]max_page_count=N
101898 ** The first form reports the current setting for the
101899 ** maximum number of pages in the database file. The
101900 ** second form attempts to change this setting. Both
101901 ** forms return the current setting.
101903 ** The absolute value of N is used. This is undocumented and might
101904 ** change. The only purpose is to provide an easy way to test
101905 ** the sqlite3AbsInt32() function.
101907 ** PRAGMA [database.]page_count
101909 ** Return the number of pages in the specified database.
101911 case PragTyp_PAGE_COUNT: {
101912 int iReg;
101913 sqlite3CodeVerifySchema(pParse, iDb);
101914 iReg = ++pParse->nMem;
101915 if( sqlite3Tolower(zLeft[0])=='p' ){
101916 sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
101917 }else{
101918 sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
101919 sqlite3AbsInt32(sqlite3Atoi(zRight)));
101921 sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
101922 sqlite3VdbeSetNumCols(v, 1);
101923 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
101924 break;
101928 ** PRAGMA [database.]locking_mode
101929 ** PRAGMA [database.]locking_mode = (normal|exclusive)
101931 case PragTyp_LOCKING_MODE: {
101932 const char *zRet = "normal";
101933 int eMode = getLockingMode(zRight);
101935 if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
101936 /* Simple "PRAGMA locking_mode;" statement. This is a query for
101937 ** the current default locking mode (which may be different to
101938 ** the locking-mode of the main database).
101940 eMode = db->dfltLockMode;
101941 }else{
101942 Pager *pPager;
101943 if( pId2->n==0 ){
101944 /* This indicates that no database name was specified as part
101945 ** of the PRAGMA command. In this case the locking-mode must be
101946 ** set on all attached databases, as well as the main db file.
101948 ** Also, the sqlite3.dfltLockMode variable is set so that
101949 ** any subsequently attached databases also use the specified
101950 ** locking mode.
101952 int ii;
101953 assert(pDb==&db->aDb[0]);
101954 for(ii=2; ii<db->nDb; ii++){
101955 pPager = sqlite3BtreePager(db->aDb[ii].pBt);
101956 sqlite3PagerLockingMode(pPager, eMode);
101958 db->dfltLockMode = (u8)eMode;
101960 pPager = sqlite3BtreePager(pDb->pBt);
101961 eMode = sqlite3PagerLockingMode(pPager, eMode);
101964 assert( eMode==PAGER_LOCKINGMODE_NORMAL
101965 || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
101966 if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
101967 zRet = "exclusive";
101969 sqlite3VdbeSetNumCols(v, 1);
101970 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
101971 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
101972 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
101973 break;
101977 ** PRAGMA [database.]journal_mode
101978 ** PRAGMA [database.]journal_mode =
101979 ** (delete|persist|off|truncate|memory|wal|off)
101981 case PragTyp_JOURNAL_MODE: {
101982 int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
101983 int ii; /* Loop counter */
101985 sqlite3VdbeSetNumCols(v, 1);
101986 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
101988 if( zRight==0 ){
101989 /* If there is no "=MODE" part of the pragma, do a query for the
101990 ** current mode */
101991 eMode = PAGER_JOURNALMODE_QUERY;
101992 }else{
101993 const char *zMode;
101994 int n = sqlite3Strlen30(zRight);
101995 for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
101996 if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
101998 if( !zMode ){
101999 /* If the "=MODE" part does not match any known journal mode,
102000 ** then do a query */
102001 eMode = PAGER_JOURNALMODE_QUERY;
102004 if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
102005 /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
102006 iDb = 0;
102007 pId2->n = 1;
102009 for(ii=db->nDb-1; ii>=0; ii--){
102010 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
102011 sqlite3VdbeUsesBtree(v, ii);
102012 sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
102015 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
102016 break;
102020 ** PRAGMA [database.]journal_size_limit
102021 ** PRAGMA [database.]journal_size_limit=N
102023 ** Get or set the size limit on rollback journal files.
102025 case PragTyp_JOURNAL_SIZE_LIMIT: {
102026 Pager *pPager = sqlite3BtreePager(pDb->pBt);
102027 i64 iLimit = -2;
102028 if( zRight ){
102029 sqlite3DecOrHexToI64(zRight, &iLimit);
102030 if( iLimit<-1 ) iLimit = -1;
102032 iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
102033 returnSingleInt(pParse, "journal_size_limit", iLimit);
102034 break;
102037 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
102040 ** PRAGMA [database.]auto_vacuum
102041 ** PRAGMA [database.]auto_vacuum=N
102043 ** Get or set the value of the database 'auto-vacuum' parameter.
102044 ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
102046 #ifndef SQLITE_OMIT_AUTOVACUUM
102047 case PragTyp_AUTO_VACUUM: {
102048 Btree *pBt = pDb->pBt;
102049 assert( pBt!=0 );
102050 if( !zRight ){
102051 returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
102052 }else{
102053 int eAuto = getAutoVacuum(zRight);
102054 assert( eAuto>=0 && eAuto<=2 );
102055 db->nextAutovac = (u8)eAuto;
102056 /* Call SetAutoVacuum() to set initialize the internal auto and
102057 ** incr-vacuum flags. This is required in case this connection
102058 ** creates the database file. It is important that it is created
102059 ** as an auto-vacuum capable db.
102061 rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
102062 if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
102063 /* When setting the auto_vacuum mode to either "full" or
102064 ** "incremental", write the value of meta[6] in the database
102065 ** file. Before writing to meta[6], check that meta[3] indicates
102066 ** that this really is an auto-vacuum capable database.
102068 static const int iLn = VDBE_OFFSET_LINENO(2);
102069 static const VdbeOpList setMeta6[] = {
102070 { OP_Transaction, 0, 1, 0}, /* 0 */
102071 { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
102072 { OP_If, 1, 0, 0}, /* 2 */
102073 { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
102074 { OP_Integer, 0, 1, 0}, /* 4 */
102075 { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
102077 int iAddr;
102078 iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
102079 sqlite3VdbeChangeP1(v, iAddr, iDb);
102080 sqlite3VdbeChangeP1(v, iAddr+1, iDb);
102081 sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
102082 sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
102083 sqlite3VdbeChangeP1(v, iAddr+5, iDb);
102084 sqlite3VdbeUsesBtree(v, iDb);
102087 break;
102089 #endif
102092 ** PRAGMA [database.]incremental_vacuum(N)
102094 ** Do N steps of incremental vacuuming on a database.
102096 #ifndef SQLITE_OMIT_AUTOVACUUM
102097 case PragTyp_INCREMENTAL_VACUUM: {
102098 int iLimit, addr;
102099 if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
102100 iLimit = 0x7fffffff;
102102 sqlite3BeginWriteOperation(pParse, 0, iDb);
102103 sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
102104 addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
102105 sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
102106 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
102107 sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
102108 sqlite3VdbeJumpHere(v, addr);
102109 break;
102111 #endif
102113 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
102115 ** PRAGMA [database.]cache_size
102116 ** PRAGMA [database.]cache_size=N
102118 ** The first form reports the current local setting for the
102119 ** page cache size. The second form sets the local
102120 ** page cache size value. If N is positive then that is the
102121 ** number of pages in the cache. If N is negative, then the
102122 ** number of pages is adjusted so that the cache uses -N kibibytes
102123 ** of memory.
102125 case PragTyp_CACHE_SIZE: {
102126 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
102127 if( !zRight ){
102128 returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
102129 }else{
102130 int size = sqlite3Atoi(zRight);
102131 pDb->pSchema->cache_size = size;
102132 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
102134 break;
102138 ** PRAGMA [database.]mmap_size(N)
102140 ** Used to set mapping size limit. The mapping size limit is
102141 ** used to limit the aggregate size of all memory mapped regions of the
102142 ** database file. If this parameter is set to zero, then memory mapping
102143 ** is not used at all. If N is negative, then the default memory map
102144 ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
102145 ** The parameter N is measured in bytes.
102147 ** This value is advisory. The underlying VFS is free to memory map
102148 ** as little or as much as it wants. Except, if N is set to 0 then the
102149 ** upper layers will never invoke the xFetch interfaces to the VFS.
102151 case PragTyp_MMAP_SIZE: {
102152 sqlite3_int64 sz;
102153 #if SQLITE_MAX_MMAP_SIZE>0
102154 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
102155 if( zRight ){
102156 int ii;
102157 sqlite3DecOrHexToI64(zRight, &sz);
102158 if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
102159 if( pId2->n==0 ) db->szMmap = sz;
102160 for(ii=db->nDb-1; ii>=0; ii--){
102161 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
102162 sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
102166 sz = -1;
102167 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
102168 #else
102169 sz = 0;
102170 rc = SQLITE_OK;
102171 #endif
102172 if( rc==SQLITE_OK ){
102173 returnSingleInt(pParse, "mmap_size", sz);
102174 }else if( rc!=SQLITE_NOTFOUND ){
102175 pParse->nErr++;
102176 pParse->rc = rc;
102178 break;
102182 ** PRAGMA temp_store
102183 ** PRAGMA temp_store = "default"|"memory"|"file"
102185 ** Return or set the local value of the temp_store flag. Changing
102186 ** the local value does not make changes to the disk file and the default
102187 ** value will be restored the next time the database is opened.
102189 ** Note that it is possible for the library compile-time options to
102190 ** override this setting
102192 case PragTyp_TEMP_STORE: {
102193 if( !zRight ){
102194 returnSingleInt(pParse, "temp_store", db->temp_store);
102195 }else{
102196 changeTempStorage(pParse, zRight);
102198 break;
102202 ** PRAGMA temp_store_directory
102203 ** PRAGMA temp_store_directory = ""|"directory_name"
102205 ** Return or set the local value of the temp_store_directory flag. Changing
102206 ** the value sets a specific directory to be used for temporary files.
102207 ** Setting to a null string reverts to the default temporary directory search.
102208 ** If temporary directory is changed, then invalidateTempStorage.
102211 case PragTyp_TEMP_STORE_DIRECTORY: {
102212 if( !zRight ){
102213 if( sqlite3_temp_directory ){
102214 sqlite3VdbeSetNumCols(v, 1);
102215 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
102216 "temp_store_directory", SQLITE_STATIC);
102217 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
102218 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
102220 }else{
102221 #ifndef SQLITE_OMIT_WSD
102222 if( zRight[0] ){
102223 int res;
102224 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
102225 if( rc!=SQLITE_OK || res==0 ){
102226 sqlite3ErrorMsg(pParse, "not a writable directory");
102227 goto pragma_out;
102230 if( SQLITE_TEMP_STORE==0
102231 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
102232 || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
102234 invalidateTempStorage(pParse);
102236 sqlite3_free(sqlite3_temp_directory);
102237 if( zRight[0] ){
102238 sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
102239 }else{
102240 sqlite3_temp_directory = 0;
102242 #endif /* SQLITE_OMIT_WSD */
102244 break;
102247 #if SQLITE_OS_WIN
102249 ** PRAGMA data_store_directory
102250 ** PRAGMA data_store_directory = ""|"directory_name"
102252 ** Return or set the local value of the data_store_directory flag. Changing
102253 ** the value sets a specific directory to be used for database files that
102254 ** were specified with a relative pathname. Setting to a null string reverts
102255 ** to the default database directory, which for database files specified with
102256 ** a relative path will probably be based on the current directory for the
102257 ** process. Database file specified with an absolute path are not impacted
102258 ** by this setting, regardless of its value.
102261 case PragTyp_DATA_STORE_DIRECTORY: {
102262 if( !zRight ){
102263 if( sqlite3_data_directory ){
102264 sqlite3VdbeSetNumCols(v, 1);
102265 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
102266 "data_store_directory", SQLITE_STATIC);
102267 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
102268 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
102270 }else{
102271 #ifndef SQLITE_OMIT_WSD
102272 if( zRight[0] ){
102273 int res;
102274 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
102275 if( rc!=SQLITE_OK || res==0 ){
102276 sqlite3ErrorMsg(pParse, "not a writable directory");
102277 goto pragma_out;
102280 sqlite3_free(sqlite3_data_directory);
102281 if( zRight[0] ){
102282 sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
102283 }else{
102284 sqlite3_data_directory = 0;
102286 #endif /* SQLITE_OMIT_WSD */
102288 break;
102290 #endif
102292 #if SQLITE_ENABLE_LOCKING_STYLE
102294 ** PRAGMA [database.]lock_proxy_file
102295 ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
102297 ** Return or set the value of the lock_proxy_file flag. Changing
102298 ** the value sets a specific file to be used for database access locks.
102301 case PragTyp_LOCK_PROXY_FILE: {
102302 if( !zRight ){
102303 Pager *pPager = sqlite3BtreePager(pDb->pBt);
102304 char *proxy_file_path = NULL;
102305 sqlite3_file *pFile = sqlite3PagerFile(pPager);
102306 sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
102307 &proxy_file_path);
102309 if( proxy_file_path ){
102310 sqlite3VdbeSetNumCols(v, 1);
102311 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
102312 "lock_proxy_file", SQLITE_STATIC);
102313 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
102314 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
102316 }else{
102317 Pager *pPager = sqlite3BtreePager(pDb->pBt);
102318 sqlite3_file *pFile = sqlite3PagerFile(pPager);
102319 int res;
102320 if( zRight[0] ){
102321 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
102322 zRight);
102323 } else {
102324 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
102325 NULL);
102327 if( res!=SQLITE_OK ){
102328 sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
102329 goto pragma_out;
102332 break;
102334 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
102337 ** PRAGMA [database.]synchronous
102338 ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
102340 ** Return or set the local value of the synchronous flag. Changing
102341 ** the local value does not make changes to the disk file and the
102342 ** default value will be restored the next time the database is
102343 ** opened.
102345 case PragTyp_SYNCHRONOUS: {
102346 if( !zRight ){
102347 returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
102348 }else{
102349 if( !db->autoCommit ){
102350 sqlite3ErrorMsg(pParse,
102351 "Safety level may not be changed inside a transaction");
102352 }else{
102353 pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
102354 setAllPagerFlags(db);
102357 break;
102359 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
102361 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
102362 case PragTyp_FLAG: {
102363 if( zRight==0 ){
102364 returnSingleInt(pParse, aPragmaNames[mid].zName,
102365 (db->flags & aPragmaNames[mid].iArg)!=0 );
102366 }else{
102367 int mask = aPragmaNames[mid].iArg; /* Mask of bits to set or clear. */
102368 if( db->autoCommit==0 ){
102369 /* Foreign key support may not be enabled or disabled while not
102370 ** in auto-commit mode. */
102371 mask &= ~(SQLITE_ForeignKeys);
102373 #if SQLITE_USER_AUTHENTICATION
102374 if( db->auth.authLevel==UAUTH_User ){
102375 /* Do not allow non-admin users to modify the schema arbitrarily */
102376 mask &= ~(SQLITE_WriteSchema);
102378 #endif
102380 if( sqlite3GetBoolean(zRight, 0) ){
102381 db->flags |= mask;
102382 }else{
102383 db->flags &= ~mask;
102384 if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
102387 /* Many of the flag-pragmas modify the code generated by the SQL
102388 ** compiler (eg. count_changes). So add an opcode to expire all
102389 ** compiled SQL statements after modifying a pragma value.
102391 sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
102392 setAllPagerFlags(db);
102394 break;
102396 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
102398 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
102400 ** PRAGMA table_info(<table>)
102402 ** Return a single row for each column of the named table. The columns of
102403 ** the returned data set are:
102405 ** cid: Column id (numbered from left to right, starting at 0)
102406 ** name: Column name
102407 ** type: Column declaration type.
102408 ** notnull: True if 'NOT NULL' is part of column declaration
102409 ** dflt_value: The default value for the column, if any.
102411 case PragTyp_TABLE_INFO: if( zRight ){
102412 Table *pTab;
102413 pTab = sqlite3FindTable(db, zRight, zDb);
102414 if( pTab ){
102415 int i, k;
102416 int nHidden = 0;
102417 Column *pCol;
102418 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
102419 sqlite3VdbeSetNumCols(v, 6);
102420 pParse->nMem = 6;
102421 sqlite3CodeVerifySchema(pParse, iDb);
102422 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
102423 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
102424 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
102425 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
102426 sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
102427 sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
102428 sqlite3ViewGetColumnNames(pParse, pTab);
102429 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
102430 if( IsHiddenColumn(pCol) ){
102431 nHidden++;
102432 continue;
102434 sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
102435 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
102436 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
102437 pCol->zType ? pCol->zType : "", 0);
102438 sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
102439 if( pCol->zDflt ){
102440 sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
102441 }else{
102442 sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
102444 if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
102445 k = 0;
102446 }else if( pPk==0 ){
102447 k = 1;
102448 }else{
102449 for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
102451 sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
102452 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
102456 break;
102458 case PragTyp_STATS: {
102459 Index *pIdx;
102460 HashElem *i;
102461 v = sqlite3GetVdbe(pParse);
102462 sqlite3VdbeSetNumCols(v, 4);
102463 pParse->nMem = 4;
102464 sqlite3CodeVerifySchema(pParse, iDb);
102465 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
102466 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
102467 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
102468 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
102469 for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
102470 Table *pTab = sqliteHashData(i);
102471 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
102472 sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
102473 sqlite3VdbeAddOp2(v, OP_Integer,
102474 (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
102475 sqlite3VdbeAddOp2(v, OP_Integer,
102476 (int)sqlite3LogEstToInt(pTab->nRowLogEst), 4);
102477 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
102478 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102479 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
102480 sqlite3VdbeAddOp2(v, OP_Integer,
102481 (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
102482 sqlite3VdbeAddOp2(v, OP_Integer,
102483 (int)sqlite3LogEstToInt(pIdx->aiRowLogEst[0]), 4);
102484 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
102488 break;
102490 case PragTyp_INDEX_INFO: if( zRight ){
102491 Index *pIdx;
102492 Table *pTab;
102493 pIdx = sqlite3FindIndex(db, zRight, zDb);
102494 if( pIdx ){
102495 int i;
102496 pTab = pIdx->pTable;
102497 sqlite3VdbeSetNumCols(v, 3);
102498 pParse->nMem = 3;
102499 sqlite3CodeVerifySchema(pParse, iDb);
102500 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
102501 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
102502 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
102503 for(i=0; i<pIdx->nKeyCol; i++){
102504 i16 cnum = pIdx->aiColumn[i];
102505 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
102506 sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
102507 assert( pTab->nCol>cnum );
102508 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
102509 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
102513 break;
102515 case PragTyp_INDEX_LIST: if( zRight ){
102516 Index *pIdx;
102517 Table *pTab;
102518 int i;
102519 pTab = sqlite3FindTable(db, zRight, zDb);
102520 if( pTab ){
102521 v = sqlite3GetVdbe(pParse);
102522 sqlite3VdbeSetNumCols(v, 3);
102523 pParse->nMem = 3;
102524 sqlite3CodeVerifySchema(pParse, iDb);
102525 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
102526 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
102527 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
102528 for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
102529 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
102530 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
102531 sqlite3VdbeAddOp2(v, OP_Integer, IsUniqueIndex(pIdx), 3);
102532 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
102536 break;
102538 case PragTyp_DATABASE_LIST: {
102539 int i;
102540 sqlite3VdbeSetNumCols(v, 3);
102541 pParse->nMem = 3;
102542 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
102543 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
102544 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
102545 for(i=0; i<db->nDb; i++){
102546 if( db->aDb[i].pBt==0 ) continue;
102547 assert( db->aDb[i].zName!=0 );
102548 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
102549 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
102550 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
102551 sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
102552 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
102555 break;
102557 case PragTyp_COLLATION_LIST: {
102558 int i = 0;
102559 HashElem *p;
102560 sqlite3VdbeSetNumCols(v, 2);
102561 pParse->nMem = 2;
102562 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
102563 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
102564 for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
102565 CollSeq *pColl = (CollSeq *)sqliteHashData(p);
102566 sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
102567 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
102568 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
102571 break;
102572 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
102574 #ifndef SQLITE_OMIT_FOREIGN_KEY
102575 case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
102576 FKey *pFK;
102577 Table *pTab;
102578 pTab = sqlite3FindTable(db, zRight, zDb);
102579 if( pTab ){
102580 v = sqlite3GetVdbe(pParse);
102581 pFK = pTab->pFKey;
102582 if( pFK ){
102583 int i = 0;
102584 sqlite3VdbeSetNumCols(v, 8);
102585 pParse->nMem = 8;
102586 sqlite3CodeVerifySchema(pParse, iDb);
102587 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
102588 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
102589 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
102590 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
102591 sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
102592 sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
102593 sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
102594 sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
102595 while(pFK){
102596 int j;
102597 for(j=0; j<pFK->nCol; j++){
102598 char *zCol = pFK->aCol[j].zCol;
102599 char *zOnDelete = (char *)actionName(pFK->aAction[0]);
102600 char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
102601 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
102602 sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
102603 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
102604 sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
102605 pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
102606 sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
102607 sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
102608 sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
102609 sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
102610 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
102613 pFK = pFK->pNextFrom;
102618 break;
102619 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
102621 #ifndef SQLITE_OMIT_FOREIGN_KEY
102622 #ifndef SQLITE_OMIT_TRIGGER
102623 case PragTyp_FOREIGN_KEY_CHECK: {
102624 FKey *pFK; /* A foreign key constraint */
102625 Table *pTab; /* Child table contain "REFERENCES" keyword */
102626 Table *pParent; /* Parent table that child points to */
102627 Index *pIdx; /* Index in the parent table */
102628 int i; /* Loop counter: Foreign key number for pTab */
102629 int j; /* Loop counter: Field of the foreign key */
102630 HashElem *k; /* Loop counter: Next table in schema */
102631 int x; /* result variable */
102632 int regResult; /* 3 registers to hold a result row */
102633 int regKey; /* Register to hold key for checking the FK */
102634 int regRow; /* Registers to hold a row from pTab */
102635 int addrTop; /* Top of a loop checking foreign keys */
102636 int addrOk; /* Jump here if the key is OK */
102637 int *aiCols; /* child to parent column mapping */
102639 regResult = pParse->nMem+1;
102640 pParse->nMem += 4;
102641 regKey = ++pParse->nMem;
102642 regRow = ++pParse->nMem;
102643 v = sqlite3GetVdbe(pParse);
102644 sqlite3VdbeSetNumCols(v, 4);
102645 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
102646 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
102647 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
102648 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
102649 sqlite3CodeVerifySchema(pParse, iDb);
102650 k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
102651 while( k ){
102652 if( zRight ){
102653 pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
102654 k = 0;
102655 }else{
102656 pTab = (Table*)sqliteHashData(k);
102657 k = sqliteHashNext(k);
102659 if( pTab==0 || pTab->pFKey==0 ) continue;
102660 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
102661 if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
102662 sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
102663 sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
102664 P4_TRANSIENT);
102665 for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
102666 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
102667 if( pParent==0 ) continue;
102668 pIdx = 0;
102669 sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
102670 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
102671 if( x==0 ){
102672 if( pIdx==0 ){
102673 sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
102674 }else{
102675 sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
102676 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
102678 }else{
102679 k = 0;
102680 break;
102683 assert( pParse->nErr>0 || pFK==0 );
102684 if( pFK ) break;
102685 if( pParse->nTab<i ) pParse->nTab = i;
102686 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
102687 for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
102688 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
102689 pIdx = 0;
102690 aiCols = 0;
102691 if( pParent ){
102692 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
102693 assert( x==0 );
102695 addrOk = sqlite3VdbeMakeLabel(v);
102696 if( pParent && pIdx==0 ){
102697 int iKey = pFK->aCol[0].iFrom;
102698 assert( iKey>=0 && iKey<pTab->nCol );
102699 if( iKey!=pTab->iPKey ){
102700 sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
102701 sqlite3ColumnDefault(v, pTab, iKey, regRow);
102702 sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
102703 sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
102704 sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
102705 }else{
102706 sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
102708 sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
102709 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
102710 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
102711 }else{
102712 for(j=0; j<pFK->nCol; j++){
102713 sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
102714 aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
102715 sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
102717 if( pParent ){
102718 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
102719 sqlite3IndexAffinityStr(v,pIdx), pFK->nCol);
102720 sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
102721 VdbeCoverage(v);
102724 sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
102725 sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
102726 pFK->zTo, P4_TRANSIENT);
102727 sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
102728 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
102729 sqlite3VdbeResolveLabel(v, addrOk);
102730 sqlite3DbFree(db, aiCols);
102732 sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
102733 sqlite3VdbeJumpHere(v, addrTop);
102736 break;
102737 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
102738 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
102740 #ifndef NDEBUG
102741 case PragTyp_PARSER_TRACE: {
102742 if( zRight ){
102743 if( sqlite3GetBoolean(zRight, 0) ){
102744 sqlite3ParserTrace(stderr, "parser: ");
102745 }else{
102746 sqlite3ParserTrace(0, 0);
102750 break;
102751 #endif
102753 /* Reinstall the LIKE and GLOB functions. The variant of LIKE
102754 ** used will be case sensitive or not depending on the RHS.
102756 case PragTyp_CASE_SENSITIVE_LIKE: {
102757 if( zRight ){
102758 sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
102761 break;
102763 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
102764 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
102765 #endif
102767 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
102768 /* Pragma "quick_check" is reduced version of
102769 ** integrity_check designed to detect most database corruption
102770 ** without most of the overhead of a full integrity-check.
102772 case PragTyp_INTEGRITY_CHECK: {
102773 int i, j, addr, mxErr;
102775 /* Code that appears at the end of the integrity check. If no error
102776 ** messages have been generated, output OK. Otherwise output the
102777 ** error message
102779 static const int iLn = VDBE_OFFSET_LINENO(2);
102780 static const VdbeOpList endCode[] = {
102781 { OP_IfNeg, 1, 0, 0}, /* 0 */
102782 { OP_String8, 0, 3, 0}, /* 1 */
102783 { OP_ResultRow, 3, 1, 0},
102786 int isQuick = (sqlite3Tolower(zLeft[0])=='q');
102788 /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
102789 ** then iDb is set to the index of the database identified by <db>.
102790 ** In this case, the integrity of database iDb only is verified by
102791 ** the VDBE created below.
102793 ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
102794 ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
102795 ** to -1 here, to indicate that the VDBE should verify the integrity
102796 ** of all attached databases. */
102797 assert( iDb>=0 );
102798 assert( iDb==0 || pId2->z );
102799 if( pId2->z==0 ) iDb = -1;
102801 /* Initialize the VDBE program */
102802 pParse->nMem = 6;
102803 sqlite3VdbeSetNumCols(v, 1);
102804 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
102806 /* Set the maximum error count */
102807 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
102808 if( zRight ){
102809 sqlite3GetInt32(zRight, &mxErr);
102810 if( mxErr<=0 ){
102811 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
102814 sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
102816 /* Do an integrity check on each database file */
102817 for(i=0; i<db->nDb; i++){
102818 HashElem *x;
102819 Hash *pTbls;
102820 int cnt = 0;
102822 if( OMIT_TEMPDB && i==1 ) continue;
102823 if( iDb>=0 && i!=iDb ) continue;
102825 sqlite3CodeVerifySchema(pParse, i);
102826 addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
102827 VdbeCoverage(v);
102828 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
102829 sqlite3VdbeJumpHere(v, addr);
102831 /* Do an integrity check of the B-Tree
102833 ** Begin by filling registers 2, 3, ... with the root pages numbers
102834 ** for all tables and indices in the database.
102836 assert( sqlite3SchemaMutexHeld(db, i, 0) );
102837 pTbls = &db->aDb[i].pSchema->tblHash;
102838 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
102839 Table *pTab = sqliteHashData(x);
102840 Index *pIdx;
102841 if( HasRowid(pTab) ){
102842 sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
102843 VdbeComment((v, "%s", pTab->zName));
102844 cnt++;
102846 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102847 sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
102848 VdbeComment((v, "%s", pIdx->zName));
102849 cnt++;
102853 /* Make sure sufficient number of registers have been allocated */
102854 pParse->nMem = MAX( pParse->nMem, cnt+8 );
102856 /* Do the b-tree integrity checks */
102857 sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
102858 sqlite3VdbeChangeP5(v, (u8)i);
102859 addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
102860 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
102861 sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
102862 P4_DYNAMIC);
102863 sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
102864 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
102865 sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
102866 sqlite3VdbeJumpHere(v, addr);
102868 /* Make sure all the indices are constructed correctly.
102870 for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
102871 Table *pTab = sqliteHashData(x);
102872 Index *pIdx, *pPk;
102873 Index *pPrior = 0;
102874 int loopTop;
102875 int iDataCur, iIdxCur;
102876 int r1 = -1;
102878 if( pTab->pIndex==0 ) continue;
102879 pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
102880 addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
102881 VdbeCoverage(v);
102882 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
102883 sqlite3VdbeJumpHere(v, addr);
102884 sqlite3ExprCacheClear(pParse);
102885 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead,
102886 1, 0, &iDataCur, &iIdxCur);
102887 sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
102888 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
102889 sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
102891 pParse->nMem = MAX(pParse->nMem, 8+j);
102892 sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
102893 loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
102894 /* Verify that all NOT NULL columns really are NOT NULL */
102895 for(j=0; j<pTab->nCol; j++){
102896 char *zErr;
102897 int jmp2, jmp3;
102898 if( j==pTab->iPKey ) continue;
102899 if( pTab->aCol[j].notNull==0 ) continue;
102900 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
102901 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
102902 jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
102903 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
102904 zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
102905 pTab->aCol[j].zName);
102906 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
102907 sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
102908 jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
102909 sqlite3VdbeAddOp0(v, OP_Halt);
102910 sqlite3VdbeJumpHere(v, jmp2);
102911 sqlite3VdbeJumpHere(v, jmp3);
102913 /* Validate index entries for the current row */
102914 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
102915 int jmp2, jmp3, jmp4, jmp5;
102916 int ckUniq = sqlite3VdbeMakeLabel(v);
102917 if( pPk==pIdx ) continue;
102918 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
102919 pPrior, r1);
102920 pPrior = pIdx;
102921 sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */
102922 /* Verify that an index entry exists for the current table row */
102923 jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
102924 pIdx->nColumn); VdbeCoverage(v);
102925 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
102926 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, "row ", P4_STATIC);
102927 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
102928 sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
102929 " missing from index ", P4_STATIC);
102930 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
102931 jmp5 = sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
102932 pIdx->zName, P4_TRANSIENT);
102933 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
102934 sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
102935 jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
102936 sqlite3VdbeAddOp0(v, OP_Halt);
102937 sqlite3VdbeJumpHere(v, jmp2);
102938 /* For UNIQUE indexes, verify that only one entry exists with the
102939 ** current key. The entry is unique if (1) any column is NULL
102940 ** or (2) the next entry has a different key */
102941 if( IsUniqueIndex(pIdx) ){
102942 int uniqOk = sqlite3VdbeMakeLabel(v);
102943 int jmp6;
102944 int kk;
102945 for(kk=0; kk<pIdx->nKeyCol; kk++){
102946 int iCol = pIdx->aiColumn[kk];
102947 assert( iCol>=0 && iCol<pTab->nCol );
102948 if( pTab->aCol[iCol].notNull ) continue;
102949 sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
102950 VdbeCoverage(v);
102952 jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
102953 sqlite3VdbeAddOp2(v, OP_Goto, 0, uniqOk);
102954 sqlite3VdbeJumpHere(v, jmp6);
102955 sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
102956 pIdx->nKeyCol); VdbeCoverage(v);
102957 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
102958 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
102959 "non-unique entry in index ", P4_STATIC);
102960 sqlite3VdbeAddOp2(v, OP_Goto, 0, jmp5);
102961 sqlite3VdbeResolveLabel(v, uniqOk);
102963 sqlite3VdbeJumpHere(v, jmp4);
102964 sqlite3ResolvePartIdxLabel(pParse, jmp3);
102966 sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
102967 sqlite3VdbeJumpHere(v, loopTop-1);
102968 #ifndef SQLITE_OMIT_BTREECOUNT
102969 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0,
102970 "wrong # of entries in index ", P4_STATIC);
102971 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
102972 if( pPk==pIdx ) continue;
102973 addr = sqlite3VdbeCurrentAddr(v);
102974 sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
102975 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
102976 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
102977 sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
102978 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
102979 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
102980 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
102981 sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
102982 sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
102984 #endif /* SQLITE_OMIT_BTREECOUNT */
102987 addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
102988 sqlite3VdbeChangeP3(v, addr, -mxErr);
102989 sqlite3VdbeJumpHere(v, addr);
102990 sqlite3VdbeChangeP4(v, addr+1, "ok", P4_STATIC);
102992 break;
102993 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
102995 #ifndef SQLITE_OMIT_UTF16
102997 ** PRAGMA encoding
102998 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
103000 ** In its first form, this pragma returns the encoding of the main
103001 ** database. If the database is not initialized, it is initialized now.
103003 ** The second form of this pragma is a no-op if the main database file
103004 ** has not already been initialized. In this case it sets the default
103005 ** encoding that will be used for the main database file if a new file
103006 ** is created. If an existing main database file is opened, then the
103007 ** default text encoding for the existing database is used.
103009 ** In all cases new databases created using the ATTACH command are
103010 ** created to use the same default text encoding as the main database. If
103011 ** the main database has not been initialized and/or created when ATTACH
103012 ** is executed, this is done before the ATTACH operation.
103014 ** In the second form this pragma sets the text encoding to be used in
103015 ** new database files created using this database handle. It is only
103016 ** useful if invoked immediately after the main database i
103018 case PragTyp_ENCODING: {
103019 static const struct EncName {
103020 char *zName;
103021 u8 enc;
103022 } encnames[] = {
103023 { "UTF8", SQLITE_UTF8 },
103024 { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
103025 { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
103026 { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
103027 { "UTF16le", SQLITE_UTF16LE },
103028 { "UTF16be", SQLITE_UTF16BE },
103029 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
103030 { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
103031 { 0, 0 }
103033 const struct EncName *pEnc;
103034 if( !zRight ){ /* "PRAGMA encoding" */
103035 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
103036 sqlite3VdbeSetNumCols(v, 1);
103037 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
103038 sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
103039 assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
103040 assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
103041 assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
103042 sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
103043 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
103044 }else{ /* "PRAGMA encoding = XXX" */
103045 /* Only change the value of sqlite.enc if the database handle is not
103046 ** initialized. If the main database exists, the new sqlite.enc value
103047 ** will be overwritten when the schema is next loaded. If it does not
103048 ** already exists, it will be created to use the new encoding value.
103051 !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
103052 DbHasProperty(db, 0, DB_Empty)
103054 for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
103055 if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
103056 ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
103057 break;
103060 if( !pEnc->zName ){
103061 sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
103066 break;
103067 #endif /* SQLITE_OMIT_UTF16 */
103069 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
103071 ** PRAGMA [database.]schema_version
103072 ** PRAGMA [database.]schema_version = <integer>
103074 ** PRAGMA [database.]user_version
103075 ** PRAGMA [database.]user_version = <integer>
103077 ** PRAGMA [database.]freelist_count = <integer>
103079 ** PRAGMA [database.]application_id
103080 ** PRAGMA [database.]application_id = <integer>
103082 ** The pragma's schema_version and user_version are used to set or get
103083 ** the value of the schema-version and user-version, respectively. Both
103084 ** the schema-version and the user-version are 32-bit signed integers
103085 ** stored in the database header.
103087 ** The schema-cookie is usually only manipulated internally by SQLite. It
103088 ** is incremented by SQLite whenever the database schema is modified (by
103089 ** creating or dropping a table or index). The schema version is used by
103090 ** SQLite each time a query is executed to ensure that the internal cache
103091 ** of the schema used when compiling the SQL query matches the schema of
103092 ** the database against which the compiled query is actually executed.
103093 ** Subverting this mechanism by using "PRAGMA schema_version" to modify
103094 ** the schema-version is potentially dangerous and may lead to program
103095 ** crashes or database corruption. Use with caution!
103097 ** The user-version is not used internally by SQLite. It may be used by
103098 ** applications for any purpose.
103100 case PragTyp_HEADER_VALUE: {
103101 int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
103102 sqlite3VdbeUsesBtree(v, iDb);
103103 switch( zLeft[0] ){
103104 case 'a': case 'A':
103105 iCookie = BTREE_APPLICATION_ID;
103106 break;
103107 case 'f': case 'F':
103108 iCookie = BTREE_FREE_PAGE_COUNT;
103109 break;
103110 case 's': case 'S':
103111 iCookie = BTREE_SCHEMA_VERSION;
103112 break;
103113 default:
103114 iCookie = BTREE_USER_VERSION;
103115 break;
103118 if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
103119 /* Write the specified cookie value */
103120 static const VdbeOpList setCookie[] = {
103121 { OP_Transaction, 0, 1, 0}, /* 0 */
103122 { OP_Integer, 0, 1, 0}, /* 1 */
103123 { OP_SetCookie, 0, 0, 1}, /* 2 */
103125 int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
103126 sqlite3VdbeChangeP1(v, addr, iDb);
103127 sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
103128 sqlite3VdbeChangeP1(v, addr+2, iDb);
103129 sqlite3VdbeChangeP2(v, addr+2, iCookie);
103130 }else{
103131 /* Read the specified cookie value */
103132 static const VdbeOpList readCookie[] = {
103133 { OP_Transaction, 0, 0, 0}, /* 0 */
103134 { OP_ReadCookie, 0, 1, 0}, /* 1 */
103135 { OP_ResultRow, 1, 1, 0}
103137 int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
103138 sqlite3VdbeChangeP1(v, addr, iDb);
103139 sqlite3VdbeChangeP1(v, addr+1, iDb);
103140 sqlite3VdbeChangeP3(v, addr+1, iCookie);
103141 sqlite3VdbeSetNumCols(v, 1);
103142 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
103145 break;
103146 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
103148 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
103150 ** PRAGMA compile_options
103152 ** Return the names of all compile-time options used in this build,
103153 ** one option per row.
103155 case PragTyp_COMPILE_OPTIONS: {
103156 int i = 0;
103157 const char *zOpt;
103158 sqlite3VdbeSetNumCols(v, 1);
103159 pParse->nMem = 1;
103160 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
103161 while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
103162 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
103163 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
103166 break;
103167 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
103169 #ifndef SQLITE_OMIT_WAL
103171 ** PRAGMA [database.]wal_checkpoint = passive|full|restart
103173 ** Checkpoint the database.
103175 case PragTyp_WAL_CHECKPOINT: {
103176 int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
103177 int eMode = SQLITE_CHECKPOINT_PASSIVE;
103178 if( zRight ){
103179 if( sqlite3StrICmp(zRight, "full")==0 ){
103180 eMode = SQLITE_CHECKPOINT_FULL;
103181 }else if( sqlite3StrICmp(zRight, "restart")==0 ){
103182 eMode = SQLITE_CHECKPOINT_RESTART;
103185 sqlite3VdbeSetNumCols(v, 3);
103186 pParse->nMem = 3;
103187 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
103188 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
103189 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
103191 sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
103192 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
103194 break;
103197 ** PRAGMA wal_autocheckpoint
103198 ** PRAGMA wal_autocheckpoint = N
103200 ** Configure a database connection to automatically checkpoint a database
103201 ** after accumulating N frames in the log. Or query for the current value
103202 ** of N.
103204 case PragTyp_WAL_AUTOCHECKPOINT: {
103205 if( zRight ){
103206 sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
103208 returnSingleInt(pParse, "wal_autocheckpoint",
103209 db->xWalCallback==sqlite3WalDefaultHook ?
103210 SQLITE_PTR_TO_INT(db->pWalArg) : 0);
103212 break;
103213 #endif
103216 ** PRAGMA shrink_memory
103218 ** This pragma attempts to free as much memory as possible from the
103219 ** current database connection.
103221 case PragTyp_SHRINK_MEMORY: {
103222 sqlite3_db_release_memory(db);
103223 break;
103227 ** PRAGMA busy_timeout
103228 ** PRAGMA busy_timeout = N
103230 ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
103231 ** if one is set. If no busy handler or a different busy handler is set
103232 ** then 0 is returned. Setting the busy_timeout to 0 or negative
103233 ** disables the timeout.
103235 /*case PragTyp_BUSY_TIMEOUT*/ default: {
103236 assert( aPragmaNames[mid].ePragTyp==PragTyp_BUSY_TIMEOUT );
103237 if( zRight ){
103238 sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
103240 returnSingleInt(pParse, "timeout", db->busyTimeout);
103241 break;
103245 ** PRAGMA soft_heap_limit
103246 ** PRAGMA soft_heap_limit = N
103248 ** Call sqlite3_soft_heap_limit64(N). Return the result. If N is omitted,
103249 ** use -1.
103251 case PragTyp_SOFT_HEAP_LIMIT: {
103252 sqlite3_int64 N;
103253 if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
103254 sqlite3_soft_heap_limit64(N);
103256 returnSingleInt(pParse, "soft_heap_limit", sqlite3_soft_heap_limit64(-1));
103257 break;
103261 ** PRAGMA threads
103262 ** PRAGMA threads = N
103264 ** Configure the maximum number of worker threads. Return the new
103265 ** maximum, which might be less than requested.
103267 case PragTyp_THREADS: {
103268 sqlite3_int64 N;
103269 if( zRight
103270 && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
103271 && N>=0
103273 sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
103275 returnSingleInt(pParse, "threads",
103276 sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
103277 break;
103280 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
103282 ** Report the current state of file logs for all databases
103284 case PragTyp_LOCK_STATUS: {
103285 static const char *const azLockName[] = {
103286 "unlocked", "shared", "reserved", "pending", "exclusive"
103288 int i;
103289 sqlite3VdbeSetNumCols(v, 2);
103290 pParse->nMem = 2;
103291 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
103292 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
103293 for(i=0; i<db->nDb; i++){
103294 Btree *pBt;
103295 const char *zState = "unknown";
103296 int j;
103297 if( db->aDb[i].zName==0 ) continue;
103298 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
103299 pBt = db->aDb[i].pBt;
103300 if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
103301 zState = "closed";
103302 }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
103303 SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
103304 zState = azLockName[j];
103306 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
103307 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
103309 break;
103311 #endif
103313 #ifdef SQLITE_HAS_CODEC
103314 case PragTyp_KEY: {
103315 if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
103316 break;
103318 case PragTyp_REKEY: {
103319 if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
103320 break;
103322 case PragTyp_HEXKEY: {
103323 if( zRight ){
103324 u8 iByte;
103325 int i;
103326 char zKey[40];
103327 for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
103328 iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
103329 if( (i&1)!=0 ) zKey[i/2] = iByte;
103331 if( (zLeft[3] & 0xf)==0xb ){
103332 sqlite3_key_v2(db, zDb, zKey, i/2);
103333 }else{
103334 sqlite3_rekey_v2(db, zDb, zKey, i/2);
103337 break;
103339 #endif
103340 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
103341 case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
103342 #ifdef SQLITE_HAS_CODEC
103343 if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
103344 sqlite3_activate_see(&zRight[4]);
103346 #endif
103347 #ifdef SQLITE_ENABLE_CEROD
103348 if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
103349 sqlite3_activate_cerod(&zRight[6]);
103351 #endif
103353 break;
103354 #endif
103356 } /* End of the PRAGMA switch */
103358 pragma_out:
103359 sqlite3DbFree(db, zLeft);
103360 sqlite3DbFree(db, zRight);
103363 #endif /* SQLITE_OMIT_PRAGMA */
103365 /************** End of pragma.c **********************************************/
103366 /************** Begin file prepare.c *****************************************/
103368 ** 2005 May 25
103370 ** The author disclaims copyright to this source code. In place of
103371 ** a legal notice, here is a blessing:
103373 ** May you do good and not evil.
103374 ** May you find forgiveness for yourself and forgive others.
103375 ** May you share freely, never taking more than you give.
103377 *************************************************************************
103378 ** This file contains the implementation of the sqlite3_prepare()
103379 ** interface, and routines that contribute to loading the database schema
103380 ** from disk.
103384 ** Fill the InitData structure with an error message that indicates
103385 ** that the database is corrupt.
103387 static void corruptSchema(
103388 InitData *pData, /* Initialization context */
103389 const char *zObj, /* Object being parsed at the point of error */
103390 const char *zExtra /* Error information */
103392 sqlite3 *db = pData->db;
103393 if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
103394 if( zObj==0 ) zObj = "?";
103395 sqlite3SetString(pData->pzErrMsg, db,
103396 "malformed database schema (%s)", zObj);
103397 if( zExtra ){
103398 *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
103399 "%s - %s", *pData->pzErrMsg, zExtra);
103402 pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
103406 ** This is the callback routine for the code that initializes the
103407 ** database. See sqlite3Init() below for additional information.
103408 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
103410 ** Each callback contains the following information:
103412 ** argv[0] = name of thing being created
103413 ** argv[1] = root page number for table or index. 0 for trigger or view.
103414 ** argv[2] = SQL text for the CREATE statement.
103417 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
103418 InitData *pData = (InitData*)pInit;
103419 sqlite3 *db = pData->db;
103420 int iDb = pData->iDb;
103422 assert( argc==3 );
103423 UNUSED_PARAMETER2(NotUsed, argc);
103424 assert( sqlite3_mutex_held(db->mutex) );
103425 DbClearProperty(db, iDb, DB_Empty);
103426 if( db->mallocFailed ){
103427 corruptSchema(pData, argv[0], 0);
103428 return 1;
103431 assert( iDb>=0 && iDb<db->nDb );
103432 if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
103433 if( argv[1]==0 ){
103434 corruptSchema(pData, argv[0], 0);
103435 }else if( argv[2] && argv[2][0] ){
103436 /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
103437 ** But because db->init.busy is set to 1, no VDBE code is generated
103438 ** or executed. All the parser does is build the internal data
103439 ** structures that describe the table, index, or view.
103441 int rc;
103442 sqlite3_stmt *pStmt;
103443 TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
103445 assert( db->init.busy );
103446 db->init.iDb = iDb;
103447 db->init.newTnum = sqlite3Atoi(argv[1]);
103448 db->init.orphanTrigger = 0;
103449 TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
103450 rc = db->errCode;
103451 assert( (rc&0xFF)==(rcp&0xFF) );
103452 db->init.iDb = 0;
103453 if( SQLITE_OK!=rc ){
103454 if( db->init.orphanTrigger ){
103455 assert( iDb==1 );
103456 }else{
103457 pData->rc = rc;
103458 if( rc==SQLITE_NOMEM ){
103459 db->mallocFailed = 1;
103460 }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
103461 corruptSchema(pData, argv[0], sqlite3_errmsg(db));
103465 sqlite3_finalize(pStmt);
103466 }else if( argv[0]==0 ){
103467 corruptSchema(pData, 0, 0);
103468 }else{
103469 /* If the SQL column is blank it means this is an index that
103470 ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
103471 ** constraint for a CREATE TABLE. The index should have already
103472 ** been created when we processed the CREATE TABLE. All we have
103473 ** to do here is record the root page number for that index.
103475 Index *pIndex;
103476 pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
103477 if( pIndex==0 ){
103478 /* This can occur if there exists an index on a TEMP table which
103479 ** has the same name as another index on a permanent index. Since
103480 ** the permanent table is hidden by the TEMP table, we can also
103481 ** safely ignore the index on the permanent table.
103483 /* Do Nothing */;
103484 }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
103485 corruptSchema(pData, argv[0], "invalid rootpage");
103488 return 0;
103492 ** Attempt to read the database schema and initialize internal
103493 ** data structures for a single database file. The index of the
103494 ** database file is given by iDb. iDb==0 is used for the main
103495 ** database. iDb==1 should never be used. iDb>=2 is used for
103496 ** auxiliary databases. Return one of the SQLITE_ error codes to
103497 ** indicate success or failure.
103499 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
103500 int rc;
103501 int i;
103502 #ifndef SQLITE_OMIT_DEPRECATED
103503 int size;
103504 #endif
103505 Table *pTab;
103506 Db *pDb;
103507 char const *azArg[4];
103508 int meta[5];
103509 InitData initData;
103510 char const *zMasterSchema;
103511 char const *zMasterName;
103512 int openedTransaction = 0;
103515 ** The master database table has a structure like this
103517 static const char master_schema[] =
103518 "CREATE TABLE sqlite_master(\n"
103519 " type text,\n"
103520 " name text,\n"
103521 " tbl_name text,\n"
103522 " rootpage integer,\n"
103523 " sql text\n"
103526 #ifndef SQLITE_OMIT_TEMPDB
103527 static const char temp_master_schema[] =
103528 "CREATE TEMP TABLE sqlite_temp_master(\n"
103529 " type text,\n"
103530 " name text,\n"
103531 " tbl_name text,\n"
103532 " rootpage integer,\n"
103533 " sql text\n"
103536 #else
103537 #define temp_master_schema 0
103538 #endif
103540 assert( iDb>=0 && iDb<db->nDb );
103541 assert( db->aDb[iDb].pSchema );
103542 assert( sqlite3_mutex_held(db->mutex) );
103543 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
103545 /* zMasterSchema and zInitScript are set to point at the master schema
103546 ** and initialisation script appropriate for the database being
103547 ** initialized. zMasterName is the name of the master table.
103549 if( !OMIT_TEMPDB && iDb==1 ){
103550 zMasterSchema = temp_master_schema;
103551 }else{
103552 zMasterSchema = master_schema;
103554 zMasterName = SCHEMA_TABLE(iDb);
103556 /* Construct the schema tables. */
103557 azArg[0] = zMasterName;
103558 azArg[1] = "1";
103559 azArg[2] = zMasterSchema;
103560 azArg[3] = 0;
103561 initData.db = db;
103562 initData.iDb = iDb;
103563 initData.rc = SQLITE_OK;
103564 initData.pzErrMsg = pzErrMsg;
103565 sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
103566 if( initData.rc ){
103567 rc = initData.rc;
103568 goto error_out;
103570 pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
103571 if( ALWAYS(pTab) ){
103572 pTab->tabFlags |= TF_Readonly;
103575 /* Create a cursor to hold the database open
103577 pDb = &db->aDb[iDb];
103578 if( pDb->pBt==0 ){
103579 if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
103580 DbSetProperty(db, 1, DB_SchemaLoaded);
103582 return SQLITE_OK;
103585 /* If there is not already a read-only (or read-write) transaction opened
103586 ** on the b-tree database, open one now. If a transaction is opened, it
103587 ** will be closed before this function returns. */
103588 sqlite3BtreeEnter(pDb->pBt);
103589 if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
103590 rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
103591 if( rc!=SQLITE_OK ){
103592 sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
103593 goto initone_error_out;
103595 openedTransaction = 1;
103598 /* Get the database meta information.
103600 ** Meta values are as follows:
103601 ** meta[0] Schema cookie. Changes with each schema change.
103602 ** meta[1] File format of schema layer.
103603 ** meta[2] Size of the page cache.
103604 ** meta[3] Largest rootpage (auto/incr_vacuum mode)
103605 ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
103606 ** meta[5] User version
103607 ** meta[6] Incremental vacuum mode
103608 ** meta[7] unused
103609 ** meta[8] unused
103610 ** meta[9] unused
103612 ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
103613 ** the possible values of meta[4].
103615 for(i=0; i<ArraySize(meta); i++){
103616 sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
103618 pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
103620 /* If opening a non-empty database, check the text encoding. For the
103621 ** main database, set sqlite3.enc to the encoding of the main database.
103622 ** For an attached db, it is an error if the encoding is not the same
103623 ** as sqlite3.enc.
103625 if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
103626 if( iDb==0 ){
103627 #ifndef SQLITE_OMIT_UTF16
103628 u8 encoding;
103629 /* If opening the main database, set ENC(db). */
103630 encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
103631 if( encoding==0 ) encoding = SQLITE_UTF8;
103632 ENC(db) = encoding;
103633 #else
103634 ENC(db) = SQLITE_UTF8;
103635 #endif
103636 }else{
103637 /* If opening an attached database, the encoding much match ENC(db) */
103638 if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
103639 sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
103640 " text encoding as main database");
103641 rc = SQLITE_ERROR;
103642 goto initone_error_out;
103645 }else{
103646 DbSetProperty(db, iDb, DB_Empty);
103648 pDb->pSchema->enc = ENC(db);
103650 if( pDb->pSchema->cache_size==0 ){
103651 #ifndef SQLITE_OMIT_DEPRECATED
103652 size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
103653 if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
103654 pDb->pSchema->cache_size = size;
103655 #else
103656 pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
103657 #endif
103658 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
103662 ** file_format==1 Version 3.0.0.
103663 ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
103664 ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
103665 ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
103667 pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
103668 if( pDb->pSchema->file_format==0 ){
103669 pDb->pSchema->file_format = 1;
103671 if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
103672 sqlite3SetString(pzErrMsg, db, "unsupported file format");
103673 rc = SQLITE_ERROR;
103674 goto initone_error_out;
103677 /* Ticket #2804: When we open a database in the newer file format,
103678 ** clear the legacy_file_format pragma flag so that a VACUUM will
103679 ** not downgrade the database and thus invalidate any descending
103680 ** indices that the user might have created.
103682 if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
103683 db->flags &= ~SQLITE_LegacyFileFmt;
103686 /* Read the schema information out of the schema tables
103688 assert( db->init.busy );
103690 char *zSql;
103691 zSql = sqlite3MPrintf(db,
103692 "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
103693 db->aDb[iDb].zName, zMasterName);
103694 #ifndef SQLITE_OMIT_AUTHORIZATION
103696 sqlite3_xauth xAuth;
103697 xAuth = db->xAuth;
103698 db->xAuth = 0;
103699 #endif
103700 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
103701 #ifndef SQLITE_OMIT_AUTHORIZATION
103702 db->xAuth = xAuth;
103704 #endif
103705 if( rc==SQLITE_OK ) rc = initData.rc;
103706 sqlite3DbFree(db, zSql);
103707 #ifndef SQLITE_OMIT_ANALYZE
103708 if( rc==SQLITE_OK ){
103709 sqlite3AnalysisLoad(db, iDb);
103711 #endif
103713 if( db->mallocFailed ){
103714 rc = SQLITE_NOMEM;
103715 sqlite3ResetAllSchemasOfConnection(db);
103717 if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
103718 /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
103719 ** the schema loaded, even if errors occurred. In this situation the
103720 ** current sqlite3_prepare() operation will fail, but the following one
103721 ** will attempt to compile the supplied statement against whatever subset
103722 ** of the schema was loaded before the error occurred. The primary
103723 ** purpose of this is to allow access to the sqlite_master table
103724 ** even when its contents have been corrupted.
103726 DbSetProperty(db, iDb, DB_SchemaLoaded);
103727 rc = SQLITE_OK;
103730 /* Jump here for an error that occurs after successfully allocating
103731 ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
103732 ** before that point, jump to error_out.
103734 initone_error_out:
103735 if( openedTransaction ){
103736 sqlite3BtreeCommit(pDb->pBt);
103738 sqlite3BtreeLeave(pDb->pBt);
103740 error_out:
103741 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
103742 db->mallocFailed = 1;
103744 return rc;
103748 ** Initialize all database files - the main database file, the file
103749 ** used to store temporary tables, and any additional database files
103750 ** created using ATTACH statements. Return a success code. If an
103751 ** error occurs, write an error message into *pzErrMsg.
103753 ** After a database is initialized, the DB_SchemaLoaded bit is set
103754 ** bit is set in the flags field of the Db structure. If the database
103755 ** file was of zero-length, then the DB_Empty flag is also set.
103757 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
103758 int i, rc;
103759 int commit_internal = !(db->flags&SQLITE_InternChanges);
103761 assert( sqlite3_mutex_held(db->mutex) );
103762 assert( db->init.busy==0 );
103763 rc = SQLITE_OK;
103764 db->init.busy = 1;
103765 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
103766 if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
103767 rc = sqlite3InitOne(db, i, pzErrMsg);
103768 if( rc ){
103769 sqlite3ResetOneSchema(db, i);
103773 /* Once all the other databases have been initialized, load the schema
103774 ** for the TEMP database. This is loaded last, as the TEMP database
103775 ** schema may contain references to objects in other databases.
103777 #ifndef SQLITE_OMIT_TEMPDB
103778 assert( db->nDb>1 );
103779 if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
103780 rc = sqlite3InitOne(db, 1, pzErrMsg);
103781 if( rc ){
103782 sqlite3ResetOneSchema(db, 1);
103785 #endif
103787 db->init.busy = 0;
103788 if( rc==SQLITE_OK && commit_internal ){
103789 sqlite3CommitInternalChanges(db);
103792 return rc;
103796 ** This routine is a no-op if the database schema is already initialized.
103797 ** Otherwise, the schema is loaded. An error code is returned.
103799 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
103800 int rc = SQLITE_OK;
103801 sqlite3 *db = pParse->db;
103802 assert( sqlite3_mutex_held(db->mutex) );
103803 if( !db->init.busy ){
103804 rc = sqlite3Init(db, &pParse->zErrMsg);
103806 if( rc!=SQLITE_OK ){
103807 pParse->rc = rc;
103808 pParse->nErr++;
103810 return rc;
103815 ** Check schema cookies in all databases. If any cookie is out
103816 ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
103817 ** make no changes to pParse->rc.
103819 static void schemaIsValid(Parse *pParse){
103820 sqlite3 *db = pParse->db;
103821 int iDb;
103822 int rc;
103823 int cookie;
103825 assert( pParse->checkSchema );
103826 assert( sqlite3_mutex_held(db->mutex) );
103827 for(iDb=0; iDb<db->nDb; iDb++){
103828 int openedTransaction = 0; /* True if a transaction is opened */
103829 Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
103830 if( pBt==0 ) continue;
103832 /* If there is not already a read-only (or read-write) transaction opened
103833 ** on the b-tree database, open one now. If a transaction is opened, it
103834 ** will be closed immediately after reading the meta-value. */
103835 if( !sqlite3BtreeIsInReadTrans(pBt) ){
103836 rc = sqlite3BtreeBeginTrans(pBt, 0);
103837 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
103838 db->mallocFailed = 1;
103840 if( rc!=SQLITE_OK ) return;
103841 openedTransaction = 1;
103844 /* Read the schema cookie from the database. If it does not match the
103845 ** value stored as part of the in-memory schema representation,
103846 ** set Parse.rc to SQLITE_SCHEMA. */
103847 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
103848 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
103849 if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
103850 sqlite3ResetOneSchema(db, iDb);
103851 pParse->rc = SQLITE_SCHEMA;
103854 /* Close the transaction, if one was opened. */
103855 if( openedTransaction ){
103856 sqlite3BtreeCommit(pBt);
103862 ** Convert a schema pointer into the iDb index that indicates
103863 ** which database file in db->aDb[] the schema refers to.
103865 ** If the same database is attached more than once, the first
103866 ** attached database is returned.
103868 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
103869 int i = -1000000;
103871 /* If pSchema is NULL, then return -1000000. This happens when code in
103872 ** expr.c is trying to resolve a reference to a transient table (i.e. one
103873 ** created by a sub-select). In this case the return value of this
103874 ** function should never be used.
103876 ** We return -1000000 instead of the more usual -1 simply because using
103877 ** -1000000 as the incorrect index into db->aDb[] is much
103878 ** more likely to cause a segfault than -1 (of course there are assert()
103879 ** statements too, but it never hurts to play the odds).
103881 assert( sqlite3_mutex_held(db->mutex) );
103882 if( pSchema ){
103883 for(i=0; ALWAYS(i<db->nDb); i++){
103884 if( db->aDb[i].pSchema==pSchema ){
103885 break;
103888 assert( i>=0 && i<db->nDb );
103890 return i;
103894 ** Free all memory allocations in the pParse object
103896 SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
103897 if( pParse ){
103898 sqlite3 *db = pParse->db;
103899 sqlite3DbFree(db, pParse->aLabel);
103900 sqlite3ExprListDelete(db, pParse->pConstExpr);
103905 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
103907 static int sqlite3Prepare(
103908 sqlite3 *db, /* Database handle. */
103909 const char *zSql, /* UTF-8 encoded SQL statement. */
103910 int nBytes, /* Length of zSql in bytes. */
103911 int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
103912 Vdbe *pReprepare, /* VM being reprepared */
103913 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
103914 const char **pzTail /* OUT: End of parsed string */
103916 Parse *pParse; /* Parsing context */
103917 char *zErrMsg = 0; /* Error message */
103918 int rc = SQLITE_OK; /* Result code */
103919 int i; /* Loop counter */
103921 /* Allocate the parsing context */
103922 pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
103923 if( pParse==0 ){
103924 rc = SQLITE_NOMEM;
103925 goto end_prepare;
103927 pParse->pReprepare = pReprepare;
103928 assert( ppStmt && *ppStmt==0 );
103929 assert( !db->mallocFailed );
103930 assert( sqlite3_mutex_held(db->mutex) );
103932 /* Check to verify that it is possible to get a read lock on all
103933 ** database schemas. The inability to get a read lock indicates that
103934 ** some other database connection is holding a write-lock, which in
103935 ** turn means that the other connection has made uncommitted changes
103936 ** to the schema.
103938 ** Were we to proceed and prepare the statement against the uncommitted
103939 ** schema changes and if those schema changes are subsequently rolled
103940 ** back and different changes are made in their place, then when this
103941 ** prepared statement goes to run the schema cookie would fail to detect
103942 ** the schema change. Disaster would follow.
103944 ** This thread is currently holding mutexes on all Btrees (because
103945 ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
103946 ** is not possible for another thread to start a new schema change
103947 ** while this routine is running. Hence, we do not need to hold
103948 ** locks on the schema, we just need to make sure nobody else is
103949 ** holding them.
103951 ** Note that setting READ_UNCOMMITTED overrides most lock detection,
103952 ** but it does *not* override schema lock detection, so this all still
103953 ** works even if READ_UNCOMMITTED is set.
103955 for(i=0; i<db->nDb; i++) {
103956 Btree *pBt = db->aDb[i].pBt;
103957 if( pBt ){
103958 assert( sqlite3BtreeHoldsMutex(pBt) );
103959 rc = sqlite3BtreeSchemaLocked(pBt);
103960 if( rc ){
103961 const char *zDb = db->aDb[i].zName;
103962 sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
103963 testcase( db->flags & SQLITE_ReadUncommitted );
103964 goto end_prepare;
103969 sqlite3VtabUnlockList(db);
103971 pParse->db = db;
103972 pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
103973 if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
103974 char *zSqlCopy;
103975 int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
103976 testcase( nBytes==mxLen );
103977 testcase( nBytes==mxLen+1 );
103978 if( nBytes>mxLen ){
103979 sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
103980 rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
103981 goto end_prepare;
103983 zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
103984 if( zSqlCopy ){
103985 sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
103986 sqlite3DbFree(db, zSqlCopy);
103987 pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
103988 }else{
103989 pParse->zTail = &zSql[nBytes];
103991 }else{
103992 sqlite3RunParser(pParse, zSql, &zErrMsg);
103994 assert( 0==pParse->nQueryLoop );
103996 if( db->mallocFailed ){
103997 pParse->rc = SQLITE_NOMEM;
103999 if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
104000 if( pParse->checkSchema ){
104001 schemaIsValid(pParse);
104003 if( db->mallocFailed ){
104004 pParse->rc = SQLITE_NOMEM;
104006 if( pzTail ){
104007 *pzTail = pParse->zTail;
104009 rc = pParse->rc;
104011 #ifndef SQLITE_OMIT_EXPLAIN
104012 if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
104013 static const char * const azColName[] = {
104014 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
104015 "selectid", "order", "from", "detail"
104017 int iFirst, mx;
104018 if( pParse->explain==2 ){
104019 sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
104020 iFirst = 8;
104021 mx = 12;
104022 }else{
104023 sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
104024 iFirst = 0;
104025 mx = 8;
104027 for(i=iFirst; i<mx; i++){
104028 sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
104029 azColName[i], SQLITE_STATIC);
104032 #endif
104034 if( db->init.busy==0 ){
104035 Vdbe *pVdbe = pParse->pVdbe;
104036 sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
104038 if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
104039 sqlite3VdbeFinalize(pParse->pVdbe);
104040 assert(!(*ppStmt));
104041 }else{
104042 *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
104045 if( zErrMsg ){
104046 sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
104047 sqlite3DbFree(db, zErrMsg);
104048 }else{
104049 sqlite3Error(db, rc);
104052 /* Delete any TriggerPrg structures allocated while parsing this statement. */
104053 while( pParse->pTriggerPrg ){
104054 TriggerPrg *pT = pParse->pTriggerPrg;
104055 pParse->pTriggerPrg = pT->pNext;
104056 sqlite3DbFree(db, pT);
104059 end_prepare:
104061 sqlite3ParserReset(pParse);
104062 sqlite3StackFree(db, pParse);
104063 rc = sqlite3ApiExit(db, rc);
104064 assert( (rc&db->errMask)==rc );
104065 return rc;
104067 static int sqlite3LockAndPrepare(
104068 sqlite3 *db, /* Database handle. */
104069 const char *zSql, /* UTF-8 encoded SQL statement. */
104070 int nBytes, /* Length of zSql in bytes. */
104071 int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
104072 Vdbe *pOld, /* VM being reprepared */
104073 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
104074 const char **pzTail /* OUT: End of parsed string */
104076 int rc;
104077 assert( ppStmt!=0 );
104078 *ppStmt = 0;
104079 if( !sqlite3SafetyCheckOk(db) ){
104080 return SQLITE_MISUSE_BKPT;
104082 sqlite3_mutex_enter(db->mutex);
104083 sqlite3BtreeEnterAll(db);
104084 rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
104085 if( rc==SQLITE_SCHEMA ){
104086 sqlite3_finalize(*ppStmt);
104087 rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
104089 sqlite3BtreeLeaveAll(db);
104090 sqlite3_mutex_leave(db->mutex);
104091 assert( rc==SQLITE_OK || *ppStmt==0 );
104092 return rc;
104096 ** Rerun the compilation of a statement after a schema change.
104098 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
104099 ** if the statement cannot be recompiled because another connection has
104100 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
104101 ** occurs, return SQLITE_SCHEMA.
104103 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
104104 int rc;
104105 sqlite3_stmt *pNew;
104106 const char *zSql;
104107 sqlite3 *db;
104109 assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
104110 zSql = sqlite3_sql((sqlite3_stmt *)p);
104111 assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
104112 db = sqlite3VdbeDb(p);
104113 assert( sqlite3_mutex_held(db->mutex) );
104114 rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
104115 if( rc ){
104116 if( rc==SQLITE_NOMEM ){
104117 db->mallocFailed = 1;
104119 assert( pNew==0 );
104120 return rc;
104121 }else{
104122 assert( pNew!=0 );
104124 sqlite3VdbeSwap((Vdbe*)pNew, p);
104125 sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
104126 sqlite3VdbeResetStepResult((Vdbe*)pNew);
104127 sqlite3VdbeFinalize((Vdbe*)pNew);
104128 return SQLITE_OK;
104133 ** Two versions of the official API. Legacy and new use. In the legacy
104134 ** version, the original SQL text is not saved in the prepared statement
104135 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
104136 ** sqlite3_step(). In the new version, the original SQL text is retained
104137 ** and the statement is automatically recompiled if an schema change
104138 ** occurs.
104140 SQLITE_API int sqlite3_prepare(
104141 sqlite3 *db, /* Database handle. */
104142 const char *zSql, /* UTF-8 encoded SQL statement. */
104143 int nBytes, /* Length of zSql in bytes. */
104144 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
104145 const char **pzTail /* OUT: End of parsed string */
104147 int rc;
104148 rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
104149 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
104150 return rc;
104152 SQLITE_API int sqlite3_prepare_v2(
104153 sqlite3 *db, /* Database handle. */
104154 const char *zSql, /* UTF-8 encoded SQL statement. */
104155 int nBytes, /* Length of zSql in bytes. */
104156 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
104157 const char **pzTail /* OUT: End of parsed string */
104159 int rc;
104160 rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
104161 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
104162 return rc;
104166 #ifndef SQLITE_OMIT_UTF16
104168 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
104170 static int sqlite3Prepare16(
104171 sqlite3 *db, /* Database handle. */
104172 const void *zSql, /* UTF-16 encoded SQL statement. */
104173 int nBytes, /* Length of zSql in bytes. */
104174 int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
104175 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
104176 const void **pzTail /* OUT: End of parsed string */
104178 /* This function currently works by first transforming the UTF-16
104179 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
104180 ** tricky bit is figuring out the pointer to return in *pzTail.
104182 char *zSql8;
104183 const char *zTail8 = 0;
104184 int rc = SQLITE_OK;
104186 assert( ppStmt );
104187 *ppStmt = 0;
104188 if( !sqlite3SafetyCheckOk(db) ){
104189 return SQLITE_MISUSE_BKPT;
104191 if( nBytes>=0 ){
104192 int sz;
104193 const char *z = (const char*)zSql;
104194 for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
104195 nBytes = sz;
104197 sqlite3_mutex_enter(db->mutex);
104198 zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
104199 if( zSql8 ){
104200 rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
104203 if( zTail8 && pzTail ){
104204 /* If sqlite3_prepare returns a tail pointer, we calculate the
104205 ** equivalent pointer into the UTF-16 string by counting the unicode
104206 ** characters between zSql8 and zTail8, and then returning a pointer
104207 ** the same number of characters into the UTF-16 string.
104209 int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
104210 *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
104212 sqlite3DbFree(db, zSql8);
104213 rc = sqlite3ApiExit(db, rc);
104214 sqlite3_mutex_leave(db->mutex);
104215 return rc;
104219 ** Two versions of the official API. Legacy and new use. In the legacy
104220 ** version, the original SQL text is not saved in the prepared statement
104221 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
104222 ** sqlite3_step(). In the new version, the original SQL text is retained
104223 ** and the statement is automatically recompiled if an schema change
104224 ** occurs.
104226 SQLITE_API int sqlite3_prepare16(
104227 sqlite3 *db, /* Database handle. */
104228 const void *zSql, /* UTF-16 encoded SQL statement. */
104229 int nBytes, /* Length of zSql in bytes. */
104230 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
104231 const void **pzTail /* OUT: End of parsed string */
104233 int rc;
104234 rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
104235 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
104236 return rc;
104238 SQLITE_API int sqlite3_prepare16_v2(
104239 sqlite3 *db, /* Database handle. */
104240 const void *zSql, /* UTF-16 encoded SQL statement. */
104241 int nBytes, /* Length of zSql in bytes. */
104242 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
104243 const void **pzTail /* OUT: End of parsed string */
104245 int rc;
104246 rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
104247 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
104248 return rc;
104251 #endif /* SQLITE_OMIT_UTF16 */
104253 /************** End of prepare.c *********************************************/
104254 /************** Begin file select.c ******************************************/
104256 ** 2001 September 15
104258 ** The author disclaims copyright to this source code. In place of
104259 ** a legal notice, here is a blessing:
104261 ** May you do good and not evil.
104262 ** May you find forgiveness for yourself and forgive others.
104263 ** May you share freely, never taking more than you give.
104265 *************************************************************************
104266 ** This file contains C code routines that are called by the parser
104267 ** to handle SELECT statements in SQLite.
104271 ** Trace output macros
104273 #if SELECTTRACE_ENABLED
104274 /***/ int sqlite3SelectTrace = 0;
104275 # define SELECTTRACE(K,P,S,X) \
104276 if(sqlite3SelectTrace&(K)) \
104277 sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",(S)->zSelName,(S)),\
104278 sqlite3DebugPrintf X
104279 #else
104280 # define SELECTTRACE(K,P,S,X)
104281 #endif
104285 ** An instance of the following object is used to record information about
104286 ** how to process the DISTINCT keyword, to simplify passing that information
104287 ** into the selectInnerLoop() routine.
104289 typedef struct DistinctCtx DistinctCtx;
104290 struct DistinctCtx {
104291 u8 isTnct; /* True if the DISTINCT keyword is present */
104292 u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
104293 int tabTnct; /* Ephemeral table used for DISTINCT processing */
104294 int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
104298 ** An instance of the following object is used to record information about
104299 ** the ORDER BY (or GROUP BY) clause of query is being coded.
104301 typedef struct SortCtx SortCtx;
104302 struct SortCtx {
104303 ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
104304 int nOBSat; /* Number of ORDER BY terms satisfied by indices */
104305 int iECursor; /* Cursor number for the sorter */
104306 int regReturn; /* Register holding block-output return address */
104307 int labelBkOut; /* Start label for the block-output subroutine */
104308 int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
104309 u8 sortFlags; /* Zero or more SORTFLAG_* bits */
104311 #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
104314 ** Delete all the content of a Select structure but do not deallocate
104315 ** the select structure itself.
104317 static void clearSelect(sqlite3 *db, Select *p){
104318 sqlite3ExprListDelete(db, p->pEList);
104319 sqlite3SrcListDelete(db, p->pSrc);
104320 sqlite3ExprDelete(db, p->pWhere);
104321 sqlite3ExprListDelete(db, p->pGroupBy);
104322 sqlite3ExprDelete(db, p->pHaving);
104323 sqlite3ExprListDelete(db, p->pOrderBy);
104324 sqlite3SelectDelete(db, p->pPrior);
104325 sqlite3ExprDelete(db, p->pLimit);
104326 sqlite3ExprDelete(db, p->pOffset);
104327 sqlite3WithDelete(db, p->pWith);
104331 ** Initialize a SelectDest structure.
104333 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
104334 pDest->eDest = (u8)eDest;
104335 pDest->iSDParm = iParm;
104336 pDest->affSdst = 0;
104337 pDest->iSdst = 0;
104338 pDest->nSdst = 0;
104343 ** Allocate a new Select structure and return a pointer to that
104344 ** structure.
104346 SQLITE_PRIVATE Select *sqlite3SelectNew(
104347 Parse *pParse, /* Parsing context */
104348 ExprList *pEList, /* which columns to include in the result */
104349 SrcList *pSrc, /* the FROM clause -- which tables to scan */
104350 Expr *pWhere, /* the WHERE clause */
104351 ExprList *pGroupBy, /* the GROUP BY clause */
104352 Expr *pHaving, /* the HAVING clause */
104353 ExprList *pOrderBy, /* the ORDER BY clause */
104354 u16 selFlags, /* Flag parameters, such as SF_Distinct */
104355 Expr *pLimit, /* LIMIT value. NULL means not used */
104356 Expr *pOffset /* OFFSET value. NULL means no offset */
104358 Select *pNew;
104359 Select standin;
104360 sqlite3 *db = pParse->db;
104361 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
104362 assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
104363 if( pNew==0 ){
104364 assert( db->mallocFailed );
104365 pNew = &standin;
104366 memset(pNew, 0, sizeof(*pNew));
104368 if( pEList==0 ){
104369 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
104371 pNew->pEList = pEList;
104372 if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
104373 pNew->pSrc = pSrc;
104374 pNew->pWhere = pWhere;
104375 pNew->pGroupBy = pGroupBy;
104376 pNew->pHaving = pHaving;
104377 pNew->pOrderBy = pOrderBy;
104378 pNew->selFlags = selFlags;
104379 pNew->op = TK_SELECT;
104380 pNew->pLimit = pLimit;
104381 pNew->pOffset = pOffset;
104382 assert( pOffset==0 || pLimit!=0 );
104383 pNew->addrOpenEphm[0] = -1;
104384 pNew->addrOpenEphm[1] = -1;
104385 if( db->mallocFailed ) {
104386 clearSelect(db, pNew);
104387 if( pNew!=&standin ) sqlite3DbFree(db, pNew);
104388 pNew = 0;
104389 }else{
104390 assert( pNew->pSrc!=0 || pParse->nErr>0 );
104392 assert( pNew!=&standin );
104393 return pNew;
104396 #if SELECTTRACE_ENABLED
104398 ** Set the name of a Select object
104400 SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
104401 if( p && zName ){
104402 sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
104405 #endif
104409 ** Delete the given Select structure and all of its substructures.
104411 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
104412 if( p ){
104413 clearSelect(db, p);
104414 sqlite3DbFree(db, p);
104419 ** Return a pointer to the right-most SELECT statement in a compound.
104421 static Select *findRightmost(Select *p){
104422 while( p->pNext ) p = p->pNext;
104423 return p;
104427 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
104428 ** type of join. Return an integer constant that expresses that type
104429 ** in terms of the following bit values:
104431 ** JT_INNER
104432 ** JT_CROSS
104433 ** JT_OUTER
104434 ** JT_NATURAL
104435 ** JT_LEFT
104436 ** JT_RIGHT
104438 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
104440 ** If an illegal or unsupported join type is seen, then still return
104441 ** a join type, but put an error in the pParse structure.
104443 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
104444 int jointype = 0;
104445 Token *apAll[3];
104446 Token *p;
104447 /* 0123456789 123456789 123456789 123 */
104448 static const char zKeyText[] = "naturaleftouterightfullinnercross";
104449 static const struct {
104450 u8 i; /* Beginning of keyword text in zKeyText[] */
104451 u8 nChar; /* Length of the keyword in characters */
104452 u8 code; /* Join type mask */
104453 } aKeyword[] = {
104454 /* natural */ { 0, 7, JT_NATURAL },
104455 /* left */ { 6, 4, JT_LEFT|JT_OUTER },
104456 /* outer */ { 10, 5, JT_OUTER },
104457 /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
104458 /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
104459 /* inner */ { 23, 5, JT_INNER },
104460 /* cross */ { 28, 5, JT_INNER|JT_CROSS },
104462 int i, j;
104463 apAll[0] = pA;
104464 apAll[1] = pB;
104465 apAll[2] = pC;
104466 for(i=0; i<3 && apAll[i]; i++){
104467 p = apAll[i];
104468 for(j=0; j<ArraySize(aKeyword); j++){
104469 if( p->n==aKeyword[j].nChar
104470 && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
104471 jointype |= aKeyword[j].code;
104472 break;
104475 testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
104476 if( j>=ArraySize(aKeyword) ){
104477 jointype |= JT_ERROR;
104478 break;
104482 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
104483 (jointype & JT_ERROR)!=0
104485 const char *zSp = " ";
104486 assert( pB!=0 );
104487 if( pC==0 ){ zSp++; }
104488 sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
104489 "%T %T%s%T", pA, pB, zSp, pC);
104490 jointype = JT_INNER;
104491 }else if( (jointype & JT_OUTER)!=0
104492 && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
104493 sqlite3ErrorMsg(pParse,
104494 "RIGHT and FULL OUTER JOINs are not currently supported");
104495 jointype = JT_INNER;
104497 return jointype;
104501 ** Return the index of a column in a table. Return -1 if the column
104502 ** is not contained in the table.
104504 static int columnIndex(Table *pTab, const char *zCol){
104505 int i;
104506 for(i=0; i<pTab->nCol; i++){
104507 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
104509 return -1;
104513 ** Search the first N tables in pSrc, from left to right, looking for a
104514 ** table that has a column named zCol.
104516 ** When found, set *piTab and *piCol to the table index and column index
104517 ** of the matching column and return TRUE.
104519 ** If not found, return FALSE.
104521 static int tableAndColumnIndex(
104522 SrcList *pSrc, /* Array of tables to search */
104523 int N, /* Number of tables in pSrc->a[] to search */
104524 const char *zCol, /* Name of the column we are looking for */
104525 int *piTab, /* Write index of pSrc->a[] here */
104526 int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
104528 int i; /* For looping over tables in pSrc */
104529 int iCol; /* Index of column matching zCol */
104531 assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
104532 for(i=0; i<N; i++){
104533 iCol = columnIndex(pSrc->a[i].pTab, zCol);
104534 if( iCol>=0 ){
104535 if( piTab ){
104536 *piTab = i;
104537 *piCol = iCol;
104539 return 1;
104542 return 0;
104546 ** This function is used to add terms implied by JOIN syntax to the
104547 ** WHERE clause expression of a SELECT statement. The new term, which
104548 ** is ANDed with the existing WHERE clause, is of the form:
104550 ** (tab1.col1 = tab2.col2)
104552 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
104553 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
104554 ** column iColRight of tab2.
104556 static void addWhereTerm(
104557 Parse *pParse, /* Parsing context */
104558 SrcList *pSrc, /* List of tables in FROM clause */
104559 int iLeft, /* Index of first table to join in pSrc */
104560 int iColLeft, /* Index of column in first table */
104561 int iRight, /* Index of second table in pSrc */
104562 int iColRight, /* Index of column in second table */
104563 int isOuterJoin, /* True if this is an OUTER join */
104564 Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
104566 sqlite3 *db = pParse->db;
104567 Expr *pE1;
104568 Expr *pE2;
104569 Expr *pEq;
104571 assert( iLeft<iRight );
104572 assert( pSrc->nSrc>iRight );
104573 assert( pSrc->a[iLeft].pTab );
104574 assert( pSrc->a[iRight].pTab );
104576 pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
104577 pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
104579 pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
104580 if( pEq && isOuterJoin ){
104581 ExprSetProperty(pEq, EP_FromJoin);
104582 assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
104583 ExprSetVVAProperty(pEq, EP_NoReduce);
104584 pEq->iRightJoinTable = (i16)pE2->iTable;
104586 *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
104590 ** Set the EP_FromJoin property on all terms of the given expression.
104591 ** And set the Expr.iRightJoinTable to iTable for every term in the
104592 ** expression.
104594 ** The EP_FromJoin property is used on terms of an expression to tell
104595 ** the LEFT OUTER JOIN processing logic that this term is part of the
104596 ** join restriction specified in the ON or USING clause and not a part
104597 ** of the more general WHERE clause. These terms are moved over to the
104598 ** WHERE clause during join processing but we need to remember that they
104599 ** originated in the ON or USING clause.
104601 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
104602 ** expression depends on table iRightJoinTable even if that table is not
104603 ** explicitly mentioned in the expression. That information is needed
104604 ** for cases like this:
104606 ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
104608 ** The where clause needs to defer the handling of the t1.x=5
104609 ** term until after the t2 loop of the join. In that way, a
104610 ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
104611 ** defer the handling of t1.x=5, it will be processed immediately
104612 ** after the t1 loop and rows with t1.x!=5 will never appear in
104613 ** the output, which is incorrect.
104615 static void setJoinExpr(Expr *p, int iTable){
104616 while( p ){
104617 ExprSetProperty(p, EP_FromJoin);
104618 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
104619 ExprSetVVAProperty(p, EP_NoReduce);
104620 p->iRightJoinTable = (i16)iTable;
104621 setJoinExpr(p->pLeft, iTable);
104622 p = p->pRight;
104627 ** This routine processes the join information for a SELECT statement.
104628 ** ON and USING clauses are converted into extra terms of the WHERE clause.
104629 ** NATURAL joins also create extra WHERE clause terms.
104631 ** The terms of a FROM clause are contained in the Select.pSrc structure.
104632 ** The left most table is the first entry in Select.pSrc. The right-most
104633 ** table is the last entry. The join operator is held in the entry to
104634 ** the left. Thus entry 0 contains the join operator for the join between
104635 ** entries 0 and 1. Any ON or USING clauses associated with the join are
104636 ** also attached to the left entry.
104638 ** This routine returns the number of errors encountered.
104640 static int sqliteProcessJoin(Parse *pParse, Select *p){
104641 SrcList *pSrc; /* All tables in the FROM clause */
104642 int i, j; /* Loop counters */
104643 struct SrcList_item *pLeft; /* Left table being joined */
104644 struct SrcList_item *pRight; /* Right table being joined */
104646 pSrc = p->pSrc;
104647 pLeft = &pSrc->a[0];
104648 pRight = &pLeft[1];
104649 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
104650 Table *pLeftTab = pLeft->pTab;
104651 Table *pRightTab = pRight->pTab;
104652 int isOuter;
104654 if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
104655 isOuter = (pRight->jointype & JT_OUTER)!=0;
104657 /* When the NATURAL keyword is present, add WHERE clause terms for
104658 ** every column that the two tables have in common.
104660 if( pRight->jointype & JT_NATURAL ){
104661 if( pRight->pOn || pRight->pUsing ){
104662 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
104663 "an ON or USING clause", 0);
104664 return 1;
104666 for(j=0; j<pRightTab->nCol; j++){
104667 char *zName; /* Name of column in the right table */
104668 int iLeft; /* Matching left table */
104669 int iLeftCol; /* Matching column in the left table */
104671 zName = pRightTab->aCol[j].zName;
104672 if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
104673 addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
104674 isOuter, &p->pWhere);
104679 /* Disallow both ON and USING clauses in the same join
104681 if( pRight->pOn && pRight->pUsing ){
104682 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
104683 "clauses in the same join");
104684 return 1;
104687 /* Add the ON clause to the end of the WHERE clause, connected by
104688 ** an AND operator.
104690 if( pRight->pOn ){
104691 if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
104692 p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
104693 pRight->pOn = 0;
104696 /* Create extra terms on the WHERE clause for each column named
104697 ** in the USING clause. Example: If the two tables to be joined are
104698 ** A and B and the USING clause names X, Y, and Z, then add this
104699 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
104700 ** Report an error if any column mentioned in the USING clause is
104701 ** not contained in both tables to be joined.
104703 if( pRight->pUsing ){
104704 IdList *pList = pRight->pUsing;
104705 for(j=0; j<pList->nId; j++){
104706 char *zName; /* Name of the term in the USING clause */
104707 int iLeft; /* Table on the left with matching column name */
104708 int iLeftCol; /* Column number of matching column on the left */
104709 int iRightCol; /* Column number of matching column on the right */
104711 zName = pList->a[j].zName;
104712 iRightCol = columnIndex(pRightTab, zName);
104713 if( iRightCol<0
104714 || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
104716 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
104717 "not present in both tables", zName);
104718 return 1;
104720 addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
104721 isOuter, &p->pWhere);
104725 return 0;
104728 /* Forward reference */
104729 static KeyInfo *keyInfoFromExprList(
104730 Parse *pParse, /* Parsing context */
104731 ExprList *pList, /* Form the KeyInfo object from this ExprList */
104732 int iStart, /* Begin with this column of pList */
104733 int nExtra /* Add this many extra columns to the end */
104737 ** Generate code that will push the record in registers regData
104738 ** through regData+nData-1 onto the sorter.
104740 static void pushOntoSorter(
104741 Parse *pParse, /* Parser context */
104742 SortCtx *pSort, /* Information about the ORDER BY clause */
104743 Select *pSelect, /* The whole SELECT statement */
104744 int regData, /* First register holding data to be sorted */
104745 int nData, /* Number of elements in the data array */
104746 int nPrefixReg /* No. of reg prior to regData available for use */
104748 Vdbe *v = pParse->pVdbe; /* Stmt under construction */
104749 int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
104750 int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
104751 int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
104752 int regBase; /* Regs for sorter record */
104753 int regRecord = ++pParse->nMem; /* Assembled sorter record */
104754 int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
104755 int op; /* Opcode to add sorter record to sorter */
104757 assert( bSeq==0 || bSeq==1 );
104758 if( nPrefixReg ){
104759 assert( nPrefixReg==nExpr+bSeq );
104760 regBase = regData - nExpr - bSeq;
104761 }else{
104762 regBase = pParse->nMem + 1;
104763 pParse->nMem += nBase;
104765 sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, SQLITE_ECEL_DUP);
104766 if( bSeq ){
104767 sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
104769 if( nPrefixReg==0 ){
104770 sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
104773 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
104774 if( nOBSat>0 ){
104775 int regPrevKey; /* The first nOBSat columns of the previous row */
104776 int addrFirst; /* Address of the OP_IfNot opcode */
104777 int addrJmp; /* Address of the OP_Jump opcode */
104778 VdbeOp *pOp; /* Opcode that opens the sorter */
104779 int nKey; /* Number of sorting key columns, including OP_Sequence */
104780 KeyInfo *pKI; /* Original KeyInfo on the sorter table */
104782 regPrevKey = pParse->nMem+1;
104783 pParse->nMem += pSort->nOBSat;
104784 nKey = nExpr - pSort->nOBSat + bSeq;
104785 if( bSeq ){
104786 addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
104787 }else{
104788 addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
104790 VdbeCoverage(v);
104791 sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
104792 pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
104793 if( pParse->db->mallocFailed ) return;
104794 pOp->p2 = nKey + nData;
104795 pKI = pOp->p4.pKeyInfo;
104796 memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
104797 sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
104798 pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat, 1);
104799 addrJmp = sqlite3VdbeCurrentAddr(v);
104800 sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
104801 pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
104802 pSort->regReturn = ++pParse->nMem;
104803 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
104804 sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
104805 sqlite3VdbeJumpHere(v, addrFirst);
104806 sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
104807 sqlite3VdbeJumpHere(v, addrJmp);
104809 if( pSort->sortFlags & SORTFLAG_UseSorter ){
104810 op = OP_SorterInsert;
104811 }else{
104812 op = OP_IdxInsert;
104814 sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
104815 if( pSelect->iLimit ){
104816 int addr1, addr2;
104817 int iLimit;
104818 if( pSelect->iOffset ){
104819 iLimit = pSelect->iOffset+1;
104820 }else{
104821 iLimit = pSelect->iLimit;
104823 addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); VdbeCoverage(v);
104824 sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
104825 addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
104826 sqlite3VdbeJumpHere(v, addr1);
104827 sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
104828 sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
104829 sqlite3VdbeJumpHere(v, addr2);
104834 ** Add code to implement the OFFSET
104836 static void codeOffset(
104837 Vdbe *v, /* Generate code into this VM */
104838 int iOffset, /* Register holding the offset counter */
104839 int iContinue /* Jump here to skip the current record */
104841 if( iOffset>0 ){
104842 int addr;
104843 addr = sqlite3VdbeAddOp3(v, OP_IfNeg, iOffset, 0, -1); VdbeCoverage(v);
104844 sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
104845 VdbeComment((v, "skip OFFSET records"));
104846 sqlite3VdbeJumpHere(v, addr);
104851 ** Add code that will check to make sure the N registers starting at iMem
104852 ** form a distinct entry. iTab is a sorting index that holds previously
104853 ** seen combinations of the N values. A new entry is made in iTab
104854 ** if the current N values are new.
104856 ** A jump to addrRepeat is made and the N+1 values are popped from the
104857 ** stack if the top N elements are not distinct.
104859 static void codeDistinct(
104860 Parse *pParse, /* Parsing and code generating context */
104861 int iTab, /* A sorting index used to test for distinctness */
104862 int addrRepeat, /* Jump to here if not distinct */
104863 int N, /* Number of elements */
104864 int iMem /* First element */
104866 Vdbe *v;
104867 int r1;
104869 v = pParse->pVdbe;
104870 r1 = sqlite3GetTempReg(pParse);
104871 sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
104872 sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
104873 sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
104874 sqlite3ReleaseTempReg(pParse, r1);
104877 #ifndef SQLITE_OMIT_SUBQUERY
104879 ** Generate an error message when a SELECT is used within a subexpression
104880 ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
104881 ** column. We do this in a subroutine because the error used to occur
104882 ** in multiple places. (The error only occurs in one place now, but we
104883 ** retain the subroutine to minimize code disruption.)
104885 static int checkForMultiColumnSelectError(
104886 Parse *pParse, /* Parse context. */
104887 SelectDest *pDest, /* Destination of SELECT results */
104888 int nExpr /* Number of result columns returned by SELECT */
104890 int eDest = pDest->eDest;
104891 if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
104892 sqlite3ErrorMsg(pParse, "only a single result allowed for "
104893 "a SELECT that is part of an expression");
104894 return 1;
104895 }else{
104896 return 0;
104899 #endif
104902 ** This routine generates the code for the inside of the inner loop
104903 ** of a SELECT.
104905 ** If srcTab is negative, then the pEList expressions
104906 ** are evaluated in order to get the data for this row. If srcTab is
104907 ** zero or more, then data is pulled from srcTab and pEList is used only
104908 ** to get number columns and the datatype for each column.
104910 static void selectInnerLoop(
104911 Parse *pParse, /* The parser context */
104912 Select *p, /* The complete select statement being coded */
104913 ExprList *pEList, /* List of values being extracted */
104914 int srcTab, /* Pull data from this table */
104915 SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
104916 DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
104917 SelectDest *pDest, /* How to dispose of the results */
104918 int iContinue, /* Jump here to continue with next row */
104919 int iBreak /* Jump here to break out of the inner loop */
104921 Vdbe *v = pParse->pVdbe;
104922 int i;
104923 int hasDistinct; /* True if the DISTINCT keyword is present */
104924 int regResult; /* Start of memory holding result set */
104925 int eDest = pDest->eDest; /* How to dispose of results */
104926 int iParm = pDest->iSDParm; /* First argument to disposal method */
104927 int nResultCol; /* Number of result columns */
104928 int nPrefixReg = 0; /* Number of extra registers before regResult */
104930 assert( v );
104931 assert( pEList!=0 );
104932 hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
104933 if( pSort && pSort->pOrderBy==0 ) pSort = 0;
104934 if( pSort==0 && !hasDistinct ){
104935 assert( iContinue!=0 );
104936 codeOffset(v, p->iOffset, iContinue);
104939 /* Pull the requested columns.
104941 nResultCol = pEList->nExpr;
104943 if( pDest->iSdst==0 ){
104944 if( pSort ){
104945 nPrefixReg = pSort->pOrderBy->nExpr;
104946 if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
104947 pParse->nMem += nPrefixReg;
104949 pDest->iSdst = pParse->nMem+1;
104950 pParse->nMem += nResultCol;
104951 }else if( pDest->iSdst+nResultCol > pParse->nMem ){
104952 /* This is an error condition that can result, for example, when a SELECT
104953 ** on the right-hand side of an INSERT contains more result columns than
104954 ** there are columns in the table on the left. The error will be caught
104955 ** and reported later. But we need to make sure enough memory is allocated
104956 ** to avoid other spurious errors in the meantime. */
104957 pParse->nMem += nResultCol;
104959 pDest->nSdst = nResultCol;
104960 regResult = pDest->iSdst;
104961 if( srcTab>=0 ){
104962 for(i=0; i<nResultCol; i++){
104963 sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
104964 VdbeComment((v, "%s", pEList->a[i].zName));
104966 }else if( eDest!=SRT_Exists ){
104967 /* If the destination is an EXISTS(...) expression, the actual
104968 ** values returned by the SELECT are not required.
104970 sqlite3ExprCodeExprList(pParse, pEList, regResult,
104971 (eDest==SRT_Output||eDest==SRT_Coroutine)?SQLITE_ECEL_DUP:0);
104974 /* If the DISTINCT keyword was present on the SELECT statement
104975 ** and this row has been seen before, then do not make this row
104976 ** part of the result.
104978 if( hasDistinct ){
104979 switch( pDistinct->eTnctType ){
104980 case WHERE_DISTINCT_ORDERED: {
104981 VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
104982 int iJump; /* Jump destination */
104983 int regPrev; /* Previous row content */
104985 /* Allocate space for the previous row */
104986 regPrev = pParse->nMem+1;
104987 pParse->nMem += nResultCol;
104989 /* Change the OP_OpenEphemeral coded earlier to an OP_Null
104990 ** sets the MEM_Cleared bit on the first register of the
104991 ** previous value. This will cause the OP_Ne below to always
104992 ** fail on the first iteration of the loop even if the first
104993 ** row is all NULLs.
104995 sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
104996 pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
104997 pOp->opcode = OP_Null;
104998 pOp->p1 = 1;
104999 pOp->p2 = regPrev;
105001 iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
105002 for(i=0; i<nResultCol; i++){
105003 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
105004 if( i<nResultCol-1 ){
105005 sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
105006 VdbeCoverage(v);
105007 }else{
105008 sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
105009 VdbeCoverage(v);
105011 sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
105012 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
105014 assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
105015 sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
105016 break;
105019 case WHERE_DISTINCT_UNIQUE: {
105020 sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
105021 break;
105024 default: {
105025 assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
105026 codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult);
105027 break;
105030 if( pSort==0 ){
105031 codeOffset(v, p->iOffset, iContinue);
105035 switch( eDest ){
105036 /* In this mode, write each query result to the key of the temporary
105037 ** table iParm.
105039 #ifndef SQLITE_OMIT_COMPOUND_SELECT
105040 case SRT_Union: {
105041 int r1;
105042 r1 = sqlite3GetTempReg(pParse);
105043 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
105044 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
105045 sqlite3ReleaseTempReg(pParse, r1);
105046 break;
105049 /* Construct a record from the query result, but instead of
105050 ** saving that record, use it as a key to delete elements from
105051 ** the temporary table iParm.
105053 case SRT_Except: {
105054 sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
105055 break;
105057 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
105059 /* Store the result as data using a unique key.
105061 case SRT_Fifo:
105062 case SRT_DistFifo:
105063 case SRT_Table:
105064 case SRT_EphemTab: {
105065 int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
105066 testcase( eDest==SRT_Table );
105067 testcase( eDest==SRT_EphemTab );
105068 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
105069 #ifndef SQLITE_OMIT_CTE
105070 if( eDest==SRT_DistFifo ){
105071 /* If the destination is DistFifo, then cursor (iParm+1) is open
105072 ** on an ephemeral index. If the current row is already present
105073 ** in the index, do not write it to the output. If not, add the
105074 ** current row to the index and proceed with writing it to the
105075 ** output table as well. */
105076 int addr = sqlite3VdbeCurrentAddr(v) + 4;
105077 sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v);
105078 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
105079 assert( pSort==0 );
105081 #endif
105082 if( pSort ){
105083 pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, 1, nPrefixReg);
105084 }else{
105085 int r2 = sqlite3GetTempReg(pParse);
105086 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
105087 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
105088 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
105089 sqlite3ReleaseTempReg(pParse, r2);
105091 sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
105092 break;
105095 #ifndef SQLITE_OMIT_SUBQUERY
105096 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
105097 ** then there should be a single item on the stack. Write this
105098 ** item into the set table with bogus data.
105100 case SRT_Set: {
105101 assert( nResultCol==1 );
105102 pDest->affSdst =
105103 sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
105104 if( pSort ){
105105 /* At first glance you would think we could optimize out the
105106 ** ORDER BY in this case since the order of entries in the set
105107 ** does not matter. But there might be a LIMIT clause, in which
105108 ** case the order does matter */
105109 pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg);
105110 }else{
105111 int r1 = sqlite3GetTempReg(pParse);
105112 sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
105113 sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
105114 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
105115 sqlite3ReleaseTempReg(pParse, r1);
105117 break;
105120 /* If any row exist in the result set, record that fact and abort.
105122 case SRT_Exists: {
105123 sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
105124 /* The LIMIT clause will terminate the loop for us */
105125 break;
105128 /* If this is a scalar select that is part of an expression, then
105129 ** store the results in the appropriate memory cell and break out
105130 ** of the scan loop.
105132 case SRT_Mem: {
105133 assert( nResultCol==1 );
105134 if( pSort ){
105135 pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg);
105136 }else{
105137 assert( regResult==iParm );
105138 /* The LIMIT clause will jump out of the loop for us */
105140 break;
105142 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
105144 case SRT_Coroutine: /* Send data to a co-routine */
105145 case SRT_Output: { /* Return the results */
105146 testcase( eDest==SRT_Coroutine );
105147 testcase( eDest==SRT_Output );
105148 if( pSort ){
105149 pushOntoSorter(pParse, pSort, p, regResult, nResultCol, nPrefixReg);
105150 }else if( eDest==SRT_Coroutine ){
105151 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
105152 }else{
105153 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
105154 sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
105156 break;
105159 #ifndef SQLITE_OMIT_CTE
105160 /* Write the results into a priority queue that is order according to
105161 ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
105162 ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
105163 ** pSO->nExpr columns, then make sure all keys are unique by adding a
105164 ** final OP_Sequence column. The last column is the record as a blob.
105166 case SRT_DistQueue:
105167 case SRT_Queue: {
105168 int nKey;
105169 int r1, r2, r3;
105170 int addrTest = 0;
105171 ExprList *pSO;
105172 pSO = pDest->pOrderBy;
105173 assert( pSO );
105174 nKey = pSO->nExpr;
105175 r1 = sqlite3GetTempReg(pParse);
105176 r2 = sqlite3GetTempRange(pParse, nKey+2);
105177 r3 = r2+nKey+1;
105178 if( eDest==SRT_DistQueue ){
105179 /* If the destination is DistQueue, then cursor (iParm+1) is open
105180 ** on a second ephemeral index that holds all values every previously
105181 ** added to the queue. */
105182 addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
105183 regResult, nResultCol);
105184 VdbeCoverage(v);
105186 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
105187 if( eDest==SRT_DistQueue ){
105188 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
105189 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
105191 for(i=0; i<nKey; i++){
105192 sqlite3VdbeAddOp2(v, OP_SCopy,
105193 regResult + pSO->a[i].u.x.iOrderByCol - 1,
105194 r2+i);
105196 sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
105197 sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
105198 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
105199 if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
105200 sqlite3ReleaseTempReg(pParse, r1);
105201 sqlite3ReleaseTempRange(pParse, r2, nKey+2);
105202 break;
105204 #endif /* SQLITE_OMIT_CTE */
105208 #if !defined(SQLITE_OMIT_TRIGGER)
105209 /* Discard the results. This is used for SELECT statements inside
105210 ** the body of a TRIGGER. The purpose of such selects is to call
105211 ** user-defined functions that have side effects. We do not care
105212 ** about the actual results of the select.
105214 default: {
105215 assert( eDest==SRT_Discard );
105216 break;
105218 #endif
105221 /* Jump to the end of the loop if the LIMIT is reached. Except, if
105222 ** there is a sorter, in which case the sorter has already limited
105223 ** the output for us.
105225 if( pSort==0 && p->iLimit ){
105226 sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
105231 ** Allocate a KeyInfo object sufficient for an index of N key columns and
105232 ** X extra columns.
105234 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
105235 KeyInfo *p = sqlite3DbMallocZero(0,
105236 sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
105237 if( p ){
105238 p->aSortOrder = (u8*)&p->aColl[N+X];
105239 p->nField = (u16)N;
105240 p->nXField = (u16)X;
105241 p->enc = ENC(db);
105242 p->db = db;
105243 p->nRef = 1;
105244 }else{
105245 db->mallocFailed = 1;
105247 return p;
105251 ** Deallocate a KeyInfo object
105253 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
105254 if( p ){
105255 assert( p->nRef>0 );
105256 p->nRef--;
105257 if( p->nRef==0 ) sqlite3DbFree(0, p);
105262 ** Make a new pointer to a KeyInfo object
105264 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
105265 if( p ){
105266 assert( p->nRef>0 );
105267 p->nRef++;
105269 return p;
105272 #ifdef SQLITE_DEBUG
105274 ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
105275 ** can only be changed if this is just a single reference to the object.
105277 ** This routine is used only inside of assert() statements.
105279 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
105280 #endif /* SQLITE_DEBUG */
105283 ** Given an expression list, generate a KeyInfo structure that records
105284 ** the collating sequence for each expression in that expression list.
105286 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
105287 ** KeyInfo structure is appropriate for initializing a virtual index to
105288 ** implement that clause. If the ExprList is the result set of a SELECT
105289 ** then the KeyInfo structure is appropriate for initializing a virtual
105290 ** index to implement a DISTINCT test.
105292 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
105293 ** function is responsible for seeing that this structure is eventually
105294 ** freed.
105296 static KeyInfo *keyInfoFromExprList(
105297 Parse *pParse, /* Parsing context */
105298 ExprList *pList, /* Form the KeyInfo object from this ExprList */
105299 int iStart, /* Begin with this column of pList */
105300 int nExtra /* Add this many extra columns to the end */
105302 int nExpr;
105303 KeyInfo *pInfo;
105304 struct ExprList_item *pItem;
105305 sqlite3 *db = pParse->db;
105306 int i;
105308 nExpr = pList->nExpr;
105309 pInfo = sqlite3KeyInfoAlloc(db, nExpr+nExtra-iStart, 1);
105310 if( pInfo ){
105311 assert( sqlite3KeyInfoIsWriteable(pInfo) );
105312 for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
105313 CollSeq *pColl;
105314 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
105315 if( !pColl ) pColl = db->pDfltColl;
105316 pInfo->aColl[i-iStart] = pColl;
105317 pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
105320 return pInfo;
105323 #ifndef SQLITE_OMIT_COMPOUND_SELECT
105325 ** Name of the connection operator, used for error messages.
105327 static const char *selectOpName(int id){
105328 char *z;
105329 switch( id ){
105330 case TK_ALL: z = "UNION ALL"; break;
105331 case TK_INTERSECT: z = "INTERSECT"; break;
105332 case TK_EXCEPT: z = "EXCEPT"; break;
105333 default: z = "UNION"; break;
105335 return z;
105337 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
105339 #ifndef SQLITE_OMIT_EXPLAIN
105341 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
105342 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
105343 ** where the caption is of the form:
105345 ** "USE TEMP B-TREE FOR xxx"
105347 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
105348 ** is determined by the zUsage argument.
105350 static void explainTempTable(Parse *pParse, const char *zUsage){
105351 if( pParse->explain==2 ){
105352 Vdbe *v = pParse->pVdbe;
105353 char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
105354 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
105359 ** Assign expression b to lvalue a. A second, no-op, version of this macro
105360 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
105361 ** in sqlite3Select() to assign values to structure member variables that
105362 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
105363 ** code with #ifndef directives.
105365 # define explainSetInteger(a, b) a = b
105367 #else
105368 /* No-op versions of the explainXXX() functions and macros. */
105369 # define explainTempTable(y,z)
105370 # define explainSetInteger(y,z)
105371 #endif
105373 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
105375 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
105376 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
105377 ** where the caption is of one of the two forms:
105379 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
105380 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
105382 ** where iSub1 and iSub2 are the integers passed as the corresponding
105383 ** function parameters, and op is the text representation of the parameter
105384 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
105385 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
105386 ** false, or the second form if it is true.
105388 static void explainComposite(
105389 Parse *pParse, /* Parse context */
105390 int op, /* One of TK_UNION, TK_EXCEPT etc. */
105391 int iSub1, /* Subquery id 1 */
105392 int iSub2, /* Subquery id 2 */
105393 int bUseTmp /* True if a temp table was used */
105395 assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
105396 if( pParse->explain==2 ){
105397 Vdbe *v = pParse->pVdbe;
105398 char *zMsg = sqlite3MPrintf(
105399 pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
105400 bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
105402 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
105405 #else
105406 /* No-op versions of the explainXXX() functions and macros. */
105407 # define explainComposite(v,w,x,y,z)
105408 #endif
105411 ** If the inner loop was generated using a non-null pOrderBy argument,
105412 ** then the results were placed in a sorter. After the loop is terminated
105413 ** we need to run the sorter and output the results. The following
105414 ** routine generates the code needed to do that.
105416 static void generateSortTail(
105417 Parse *pParse, /* Parsing context */
105418 Select *p, /* The SELECT statement */
105419 SortCtx *pSort, /* Information on the ORDER BY clause */
105420 int nColumn, /* Number of columns of data */
105421 SelectDest *pDest /* Write the sorted results here */
105423 Vdbe *v = pParse->pVdbe; /* The prepared statement */
105424 int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
105425 int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
105426 int addr;
105427 int addrOnce = 0;
105428 int iTab;
105429 ExprList *pOrderBy = pSort->pOrderBy;
105430 int eDest = pDest->eDest;
105431 int iParm = pDest->iSDParm;
105432 int regRow;
105433 int regRowid;
105434 int nKey;
105435 int iSortTab; /* Sorter cursor to read from */
105436 int nSortData; /* Trailing values to read from sorter */
105437 int i;
105438 int bSeq; /* True if sorter record includes seq. no. */
105439 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
105440 struct ExprList_item *aOutEx = p->pEList->a;
105441 #endif
105443 if( pSort->labelBkOut ){
105444 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
105445 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBreak);
105446 sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
105448 iTab = pSort->iECursor;
105449 if( eDest==SRT_Output || eDest==SRT_Coroutine ){
105450 regRowid = 0;
105451 regRow = pDest->iSdst;
105452 nSortData = nColumn;
105453 }else{
105454 regRowid = sqlite3GetTempReg(pParse);
105455 regRow = sqlite3GetTempReg(pParse);
105456 nSortData = 1;
105458 nKey = pOrderBy->nExpr - pSort->nOBSat;
105459 if( pSort->sortFlags & SORTFLAG_UseSorter ){
105460 int regSortOut = ++pParse->nMem;
105461 iSortTab = pParse->nTab++;
105462 if( pSort->labelBkOut ){
105463 addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
105465 sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
105466 if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
105467 addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
105468 VdbeCoverage(v);
105469 codeOffset(v, p->iOffset, addrContinue);
105470 sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
105471 bSeq = 0;
105472 }else{
105473 addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
105474 codeOffset(v, p->iOffset, addrContinue);
105475 iSortTab = iTab;
105476 bSeq = 1;
105478 for(i=0; i<nSortData; i++){
105479 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
105480 VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
105482 switch( eDest ){
105483 case SRT_Table:
105484 case SRT_EphemTab: {
105485 testcase( eDest==SRT_Table );
105486 testcase( eDest==SRT_EphemTab );
105487 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
105488 sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
105489 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
105490 break;
105492 #ifndef SQLITE_OMIT_SUBQUERY
105493 case SRT_Set: {
105494 assert( nColumn==1 );
105495 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
105496 &pDest->affSdst, 1);
105497 sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
105498 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
105499 break;
105501 case SRT_Mem: {
105502 assert( nColumn==1 );
105503 sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
105504 /* The LIMIT clause will terminate the loop for us */
105505 break;
105507 #endif
105508 default: {
105509 assert( eDest==SRT_Output || eDest==SRT_Coroutine );
105510 testcase( eDest==SRT_Output );
105511 testcase( eDest==SRT_Coroutine );
105512 if( eDest==SRT_Output ){
105513 sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
105514 sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
105515 }else{
105516 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
105518 break;
105521 if( regRowid ){
105522 sqlite3ReleaseTempReg(pParse, regRow);
105523 sqlite3ReleaseTempReg(pParse, regRowid);
105525 /* The bottom of the loop
105527 sqlite3VdbeResolveLabel(v, addrContinue);
105528 if( pSort->sortFlags & SORTFLAG_UseSorter ){
105529 sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
105530 }else{
105531 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
105533 if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
105534 sqlite3VdbeResolveLabel(v, addrBreak);
105538 ** Return a pointer to a string containing the 'declaration type' of the
105539 ** expression pExpr. The string may be treated as static by the caller.
105541 ** Also try to estimate the size of the returned value and return that
105542 ** result in *pEstWidth.
105544 ** The declaration type is the exact datatype definition extracted from the
105545 ** original CREATE TABLE statement if the expression is a column. The
105546 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
105547 ** is considered a column can be complex in the presence of subqueries. The
105548 ** result-set expression in all of the following SELECT statements is
105549 ** considered a column by this function.
105551 ** SELECT col FROM tbl;
105552 ** SELECT (SELECT col FROM tbl;
105553 ** SELECT (SELECT col FROM tbl);
105554 ** SELECT abc FROM (SELECT col AS abc FROM tbl);
105556 ** The declaration type for any expression other than a column is NULL.
105558 ** This routine has either 3 or 6 parameters depending on whether or not
105559 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
105561 #ifdef SQLITE_ENABLE_COLUMN_METADATA
105562 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
105563 static const char *columnTypeImpl(
105564 NameContext *pNC,
105565 Expr *pExpr,
105566 const char **pzOrigDb,
105567 const char **pzOrigTab,
105568 const char **pzOrigCol,
105569 u8 *pEstWidth
105571 char const *zOrigDb = 0;
105572 char const *zOrigTab = 0;
105573 char const *zOrigCol = 0;
105574 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
105575 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
105576 static const char *columnTypeImpl(
105577 NameContext *pNC,
105578 Expr *pExpr,
105579 u8 *pEstWidth
105581 #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
105582 char const *zType = 0;
105583 int j;
105584 u8 estWidth = 1;
105586 if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
105587 switch( pExpr->op ){
105588 case TK_AGG_COLUMN:
105589 case TK_COLUMN: {
105590 /* The expression is a column. Locate the table the column is being
105591 ** extracted from in NameContext.pSrcList. This table may be real
105592 ** database table or a subquery.
105594 Table *pTab = 0; /* Table structure column is extracted from */
105595 Select *pS = 0; /* Select the column is extracted from */
105596 int iCol = pExpr->iColumn; /* Index of column in pTab */
105597 testcase( pExpr->op==TK_AGG_COLUMN );
105598 testcase( pExpr->op==TK_COLUMN );
105599 while( pNC && !pTab ){
105600 SrcList *pTabList = pNC->pSrcList;
105601 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
105602 if( j<pTabList->nSrc ){
105603 pTab = pTabList->a[j].pTab;
105604 pS = pTabList->a[j].pSelect;
105605 }else{
105606 pNC = pNC->pNext;
105610 if( pTab==0 ){
105611 /* At one time, code such as "SELECT new.x" within a trigger would
105612 ** cause this condition to run. Since then, we have restructured how
105613 ** trigger code is generated and so this condition is no longer
105614 ** possible. However, it can still be true for statements like
105615 ** the following:
105617 ** CREATE TABLE t1(col INTEGER);
105618 ** SELECT (SELECT t1.col) FROM FROM t1;
105620 ** when columnType() is called on the expression "t1.col" in the
105621 ** sub-select. In this case, set the column type to NULL, even
105622 ** though it should really be "INTEGER".
105624 ** This is not a problem, as the column type of "t1.col" is never
105625 ** used. When columnType() is called on the expression
105626 ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
105627 ** branch below. */
105628 break;
105631 assert( pTab && pExpr->pTab==pTab );
105632 if( pS ){
105633 /* The "table" is actually a sub-select or a view in the FROM clause
105634 ** of the SELECT statement. Return the declaration type and origin
105635 ** data for the result-set column of the sub-select.
105637 if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
105638 /* If iCol is less than zero, then the expression requests the
105639 ** rowid of the sub-select or view. This expression is legal (see
105640 ** test case misc2.2.2) - it always evaluates to NULL.
105642 NameContext sNC;
105643 Expr *p = pS->pEList->a[iCol].pExpr;
105644 sNC.pSrcList = pS->pSrc;
105645 sNC.pNext = pNC;
105646 sNC.pParse = pNC->pParse;
105647 zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
105649 }else if( pTab->pSchema ){
105650 /* A real table */
105651 assert( !pS );
105652 if( iCol<0 ) iCol = pTab->iPKey;
105653 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
105654 #ifdef SQLITE_ENABLE_COLUMN_METADATA
105655 if( iCol<0 ){
105656 zType = "INTEGER";
105657 zOrigCol = "rowid";
105658 }else{
105659 zType = pTab->aCol[iCol].zType;
105660 zOrigCol = pTab->aCol[iCol].zName;
105661 estWidth = pTab->aCol[iCol].szEst;
105663 zOrigTab = pTab->zName;
105664 if( pNC->pParse ){
105665 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
105666 zOrigDb = pNC->pParse->db->aDb[iDb].zName;
105668 #else
105669 if( iCol<0 ){
105670 zType = "INTEGER";
105671 }else{
105672 zType = pTab->aCol[iCol].zType;
105673 estWidth = pTab->aCol[iCol].szEst;
105675 #endif
105677 break;
105679 #ifndef SQLITE_OMIT_SUBQUERY
105680 case TK_SELECT: {
105681 /* The expression is a sub-select. Return the declaration type and
105682 ** origin info for the single column in the result set of the SELECT
105683 ** statement.
105685 NameContext sNC;
105686 Select *pS = pExpr->x.pSelect;
105687 Expr *p = pS->pEList->a[0].pExpr;
105688 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
105689 sNC.pSrcList = pS->pSrc;
105690 sNC.pNext = pNC;
105691 sNC.pParse = pNC->pParse;
105692 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
105693 break;
105695 #endif
105698 #ifdef SQLITE_ENABLE_COLUMN_METADATA
105699 if( pzOrigDb ){
105700 assert( pzOrigTab && pzOrigCol );
105701 *pzOrigDb = zOrigDb;
105702 *pzOrigTab = zOrigTab;
105703 *pzOrigCol = zOrigCol;
105705 #endif
105706 if( pEstWidth ) *pEstWidth = estWidth;
105707 return zType;
105711 ** Generate code that will tell the VDBE the declaration types of columns
105712 ** in the result set.
105714 static void generateColumnTypes(
105715 Parse *pParse, /* Parser context */
105716 SrcList *pTabList, /* List of tables */
105717 ExprList *pEList /* Expressions defining the result set */
105719 #ifndef SQLITE_OMIT_DECLTYPE
105720 Vdbe *v = pParse->pVdbe;
105721 int i;
105722 NameContext sNC;
105723 sNC.pSrcList = pTabList;
105724 sNC.pParse = pParse;
105725 for(i=0; i<pEList->nExpr; i++){
105726 Expr *p = pEList->a[i].pExpr;
105727 const char *zType;
105728 #ifdef SQLITE_ENABLE_COLUMN_METADATA
105729 const char *zOrigDb = 0;
105730 const char *zOrigTab = 0;
105731 const char *zOrigCol = 0;
105732 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
105734 /* The vdbe must make its own copy of the column-type and other
105735 ** column specific strings, in case the schema is reset before this
105736 ** virtual machine is deleted.
105738 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
105739 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
105740 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
105741 #else
105742 zType = columnType(&sNC, p, 0, 0, 0, 0);
105743 #endif
105744 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
105746 #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
105750 ** Generate code that will tell the VDBE the names of columns
105751 ** in the result set. This information is used to provide the
105752 ** azCol[] values in the callback.
105754 static void generateColumnNames(
105755 Parse *pParse, /* Parser context */
105756 SrcList *pTabList, /* List of tables */
105757 ExprList *pEList /* Expressions defining the result set */
105759 Vdbe *v = pParse->pVdbe;
105760 int i, j;
105761 sqlite3 *db = pParse->db;
105762 int fullNames, shortNames;
105764 #ifndef SQLITE_OMIT_EXPLAIN
105765 /* If this is an EXPLAIN, skip this step */
105766 if( pParse->explain ){
105767 return;
105769 #endif
105771 if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
105772 pParse->colNamesSet = 1;
105773 fullNames = (db->flags & SQLITE_FullColNames)!=0;
105774 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
105775 sqlite3VdbeSetNumCols(v, pEList->nExpr);
105776 for(i=0; i<pEList->nExpr; i++){
105777 Expr *p;
105778 p = pEList->a[i].pExpr;
105779 if( NEVER(p==0) ) continue;
105780 if( pEList->a[i].zName ){
105781 char *zName = pEList->a[i].zName;
105782 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
105783 }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
105784 Table *pTab;
105785 char *zCol;
105786 int iCol = p->iColumn;
105787 for(j=0; ALWAYS(j<pTabList->nSrc); j++){
105788 if( pTabList->a[j].iCursor==p->iTable ) break;
105790 assert( j<pTabList->nSrc );
105791 pTab = pTabList->a[j].pTab;
105792 if( iCol<0 ) iCol = pTab->iPKey;
105793 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
105794 if( iCol<0 ){
105795 zCol = "rowid";
105796 }else{
105797 zCol = pTab->aCol[iCol].zName;
105799 if( !shortNames && !fullNames ){
105800 sqlite3VdbeSetColName(v, i, COLNAME_NAME,
105801 sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
105802 }else if( fullNames ){
105803 char *zName = 0;
105804 zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
105805 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
105806 }else{
105807 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
105809 }else{
105810 const char *z = pEList->a[i].zSpan;
105811 z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
105812 sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
105815 generateColumnTypes(pParse, pTabList, pEList);
105819 ** Given an expression list (which is really the list of expressions
105820 ** that form the result set of a SELECT statement) compute appropriate
105821 ** column names for a table that would hold the expression list.
105823 ** All column names will be unique.
105825 ** Only the column names are computed. Column.zType, Column.zColl,
105826 ** and other fields of Column are zeroed.
105828 ** Return SQLITE_OK on success. If a memory allocation error occurs,
105829 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
105831 static int selectColumnsFromExprList(
105832 Parse *pParse, /* Parsing context */
105833 ExprList *pEList, /* Expr list from which to derive column names */
105834 i16 *pnCol, /* Write the number of columns here */
105835 Column **paCol /* Write the new column list here */
105837 sqlite3 *db = pParse->db; /* Database connection */
105838 int i, j; /* Loop counters */
105839 int cnt; /* Index added to make the name unique */
105840 Column *aCol, *pCol; /* For looping over result columns */
105841 int nCol; /* Number of columns in the result set */
105842 Expr *p; /* Expression for a single result column */
105843 char *zName; /* Column name */
105844 int nName; /* Size of name in zName[] */
105846 if( pEList ){
105847 nCol = pEList->nExpr;
105848 aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
105849 testcase( aCol==0 );
105850 }else{
105851 nCol = 0;
105852 aCol = 0;
105854 *pnCol = nCol;
105855 *paCol = aCol;
105857 for(i=0, pCol=aCol; i<nCol; i++, pCol++){
105858 /* Get an appropriate name for the column
105860 p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
105861 if( (zName = pEList->a[i].zName)!=0 ){
105862 /* If the column contains an "AS <name>" phrase, use <name> as the name */
105863 zName = sqlite3DbStrDup(db, zName);
105864 }else{
105865 Expr *pColExpr = p; /* The expression that is the result column name */
105866 Table *pTab; /* Table associated with this expression */
105867 while( pColExpr->op==TK_DOT ){
105868 pColExpr = pColExpr->pRight;
105869 assert( pColExpr!=0 );
105871 if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
105872 /* For columns use the column name name */
105873 int iCol = pColExpr->iColumn;
105874 pTab = pColExpr->pTab;
105875 if( iCol<0 ) iCol = pTab->iPKey;
105876 zName = sqlite3MPrintf(db, "%s",
105877 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
105878 }else if( pColExpr->op==TK_ID ){
105879 assert( !ExprHasProperty(pColExpr, EP_IntValue) );
105880 zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
105881 }else{
105882 /* Use the original text of the column expression as its name */
105883 zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
105886 if( db->mallocFailed ){
105887 sqlite3DbFree(db, zName);
105888 break;
105891 /* Make sure the column name is unique. If the name is not unique,
105892 ** append an integer to the name so that it becomes unique.
105894 nName = sqlite3Strlen30(zName);
105895 for(j=cnt=0; j<i; j++){
105896 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
105897 char *zNewName;
105898 int k;
105899 for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
105900 if( k>=0 && zName[k]==':' ) nName = k;
105901 zName[nName] = 0;
105902 zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
105903 sqlite3DbFree(db, zName);
105904 zName = zNewName;
105905 j = -1;
105906 if( zName==0 ) break;
105909 pCol->zName = zName;
105911 if( db->mallocFailed ){
105912 for(j=0; j<i; j++){
105913 sqlite3DbFree(db, aCol[j].zName);
105915 sqlite3DbFree(db, aCol);
105916 *paCol = 0;
105917 *pnCol = 0;
105918 return SQLITE_NOMEM;
105920 return SQLITE_OK;
105924 ** Add type and collation information to a column list based on
105925 ** a SELECT statement.
105927 ** The column list presumably came from selectColumnNamesFromExprList().
105928 ** The column list has only names, not types or collations. This
105929 ** routine goes through and adds the types and collations.
105931 ** This routine requires that all identifiers in the SELECT
105932 ** statement be resolved.
105934 static void selectAddColumnTypeAndCollation(
105935 Parse *pParse, /* Parsing contexts */
105936 Table *pTab, /* Add column type information to this table */
105937 Select *pSelect /* SELECT used to determine types and collations */
105939 sqlite3 *db = pParse->db;
105940 NameContext sNC;
105941 Column *pCol;
105942 CollSeq *pColl;
105943 int i;
105944 Expr *p;
105945 struct ExprList_item *a;
105946 u64 szAll = 0;
105948 assert( pSelect!=0 );
105949 assert( (pSelect->selFlags & SF_Resolved)!=0 );
105950 assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
105951 if( db->mallocFailed ) return;
105952 memset(&sNC, 0, sizeof(sNC));
105953 sNC.pSrcList = pSelect->pSrc;
105954 a = pSelect->pEList->a;
105955 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
105956 p = a[i].pExpr;
105957 pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
105958 szAll += pCol->szEst;
105959 pCol->affinity = sqlite3ExprAffinity(p);
105960 if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
105961 pColl = sqlite3ExprCollSeq(pParse, p);
105962 if( pColl ){
105963 pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
105966 pTab->szTabRow = sqlite3LogEst(szAll*4);
105970 ** Given a SELECT statement, generate a Table structure that describes
105971 ** the result set of that SELECT.
105973 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
105974 Table *pTab;
105975 sqlite3 *db = pParse->db;
105976 int savedFlags;
105978 savedFlags = db->flags;
105979 db->flags &= ~SQLITE_FullColNames;
105980 db->flags |= SQLITE_ShortColNames;
105981 sqlite3SelectPrep(pParse, pSelect, 0);
105982 if( pParse->nErr ) return 0;
105983 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
105984 db->flags = savedFlags;
105985 pTab = sqlite3DbMallocZero(db, sizeof(Table) );
105986 if( pTab==0 ){
105987 return 0;
105989 /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
105990 ** is disabled */
105991 assert( db->lookaside.bEnabled==0 );
105992 pTab->nRef = 1;
105993 pTab->zName = 0;
105994 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
105995 selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
105996 selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
105997 pTab->iPKey = -1;
105998 if( db->mallocFailed ){
105999 sqlite3DeleteTable(db, pTab);
106000 return 0;
106002 return pTab;
106006 ** Get a VDBE for the given parser context. Create a new one if necessary.
106007 ** If an error occurs, return NULL and leave a message in pParse.
106009 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
106010 Vdbe *v = pParse->pVdbe;
106011 if( v==0 ){
106012 v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
106013 if( v ) sqlite3VdbeAddOp0(v, OP_Init);
106014 if( pParse->pToplevel==0
106015 && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
106017 pParse->okConstFactor = 1;
106021 return v;
106026 ** Compute the iLimit and iOffset fields of the SELECT based on the
106027 ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
106028 ** that appear in the original SQL statement after the LIMIT and OFFSET
106029 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
106030 ** are the integer memory register numbers for counters used to compute
106031 ** the limit and offset. If there is no limit and/or offset, then
106032 ** iLimit and iOffset are negative.
106034 ** This routine changes the values of iLimit and iOffset only if
106035 ** a limit or offset is defined by pLimit and pOffset. iLimit and
106036 ** iOffset should have been preset to appropriate default values (zero)
106037 ** prior to calling this routine.
106039 ** The iOffset register (if it exists) is initialized to the value
106040 ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
106041 ** iOffset+1 is initialized to LIMIT+OFFSET.
106043 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
106044 ** redefined. The UNION ALL operator uses this property to force
106045 ** the reuse of the same limit and offset registers across multiple
106046 ** SELECT statements.
106048 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
106049 Vdbe *v = 0;
106050 int iLimit = 0;
106051 int iOffset;
106052 int addr1, n;
106053 if( p->iLimit ) return;
106056 ** "LIMIT -1" always shows all rows. There is some
106057 ** controversy about what the correct behavior should be.
106058 ** The current implementation interprets "LIMIT 0" to mean
106059 ** no rows.
106061 sqlite3ExprCacheClear(pParse);
106062 assert( p->pOffset==0 || p->pLimit!=0 );
106063 if( p->pLimit ){
106064 p->iLimit = iLimit = ++pParse->nMem;
106065 v = sqlite3GetVdbe(pParse);
106066 assert( v!=0 );
106067 if( sqlite3ExprIsInteger(p->pLimit, &n) ){
106068 sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
106069 VdbeComment((v, "LIMIT counter"));
106070 if( n==0 ){
106071 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
106072 }else if( n>=0 && p->nSelectRow>(u64)n ){
106073 p->nSelectRow = n;
106075 }else{
106076 sqlite3ExprCode(pParse, p->pLimit, iLimit);
106077 sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
106078 VdbeComment((v, "LIMIT counter"));
106079 sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); VdbeCoverage(v);
106081 if( p->pOffset ){
106082 p->iOffset = iOffset = ++pParse->nMem;
106083 pParse->nMem++; /* Allocate an extra register for limit+offset */
106084 sqlite3ExprCode(pParse, p->pOffset, iOffset);
106085 sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
106086 VdbeComment((v, "OFFSET counter"));
106087 addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); VdbeCoverage(v);
106088 sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
106089 sqlite3VdbeJumpHere(v, addr1);
106090 sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
106091 VdbeComment((v, "LIMIT+OFFSET"));
106092 addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); VdbeCoverage(v);
106093 sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
106094 sqlite3VdbeJumpHere(v, addr1);
106099 #ifndef SQLITE_OMIT_COMPOUND_SELECT
106101 ** Return the appropriate collating sequence for the iCol-th column of
106102 ** the result set for the compound-select statement "p". Return NULL if
106103 ** the column has no default collating sequence.
106105 ** The collating sequence for the compound select is taken from the
106106 ** left-most term of the select that has a collating sequence.
106108 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
106109 CollSeq *pRet;
106110 if( p->pPrior ){
106111 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
106112 }else{
106113 pRet = 0;
106115 assert( iCol>=0 );
106116 if( pRet==0 && iCol<p->pEList->nExpr ){
106117 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
106119 return pRet;
106123 ** The select statement passed as the second parameter is a compound SELECT
106124 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
106125 ** structure suitable for implementing the ORDER BY.
106127 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
106128 ** function is responsible for ensuring that this structure is eventually
106129 ** freed.
106131 static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
106132 ExprList *pOrderBy = p->pOrderBy;
106133 int nOrderBy = p->pOrderBy->nExpr;
106134 sqlite3 *db = pParse->db;
106135 KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
106136 if( pRet ){
106137 int i;
106138 for(i=0; i<nOrderBy; i++){
106139 struct ExprList_item *pItem = &pOrderBy->a[i];
106140 Expr *pTerm = pItem->pExpr;
106141 CollSeq *pColl;
106143 if( pTerm->flags & EP_Collate ){
106144 pColl = sqlite3ExprCollSeq(pParse, pTerm);
106145 }else{
106146 pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
106147 if( pColl==0 ) pColl = db->pDfltColl;
106148 pOrderBy->a[i].pExpr =
106149 sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
106151 assert( sqlite3KeyInfoIsWriteable(pRet) );
106152 pRet->aColl[i] = pColl;
106153 pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
106157 return pRet;
106160 #ifndef SQLITE_OMIT_CTE
106162 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
106163 ** query of the form:
106165 ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
106166 ** \___________/ \_______________/
106167 ** p->pPrior p
106170 ** There is exactly one reference to the recursive-table in the FROM clause
106171 ** of recursive-query, marked with the SrcList->a[].isRecursive flag.
106173 ** The setup-query runs once to generate an initial set of rows that go
106174 ** into a Queue table. Rows are extracted from the Queue table one by
106175 ** one. Each row extracted from Queue is output to pDest. Then the single
106176 ** extracted row (now in the iCurrent table) becomes the content of the
106177 ** recursive-table for a recursive-query run. The output of the recursive-query
106178 ** is added back into the Queue table. Then another row is extracted from Queue
106179 ** and the iteration continues until the Queue table is empty.
106181 ** If the compound query operator is UNION then no duplicate rows are ever
106182 ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
106183 ** that have ever been inserted into Queue and causes duplicates to be
106184 ** discarded. If the operator is UNION ALL, then duplicates are allowed.
106186 ** If the query has an ORDER BY, then entries in the Queue table are kept in
106187 ** ORDER BY order and the first entry is extracted for each cycle. Without
106188 ** an ORDER BY, the Queue table is just a FIFO.
106190 ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
106191 ** have been output to pDest. A LIMIT of zero means to output no rows and a
106192 ** negative LIMIT means to output all rows. If there is also an OFFSET clause
106193 ** with a positive value, then the first OFFSET outputs are discarded rather
106194 ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
106195 ** rows have been skipped.
106197 static void generateWithRecursiveQuery(
106198 Parse *pParse, /* Parsing context */
106199 Select *p, /* The recursive SELECT to be coded */
106200 SelectDest *pDest /* What to do with query results */
106202 SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
106203 int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
106204 Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
106205 Select *pSetup = p->pPrior; /* The setup query */
106206 int addrTop; /* Top of the loop */
106207 int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
106208 int iCurrent = 0; /* The Current table */
106209 int regCurrent; /* Register holding Current table */
106210 int iQueue; /* The Queue table */
106211 int iDistinct = 0; /* To ensure unique results if UNION */
106212 int eDest = SRT_Fifo; /* How to write to Queue */
106213 SelectDest destQueue; /* SelectDest targetting the Queue table */
106214 int i; /* Loop counter */
106215 int rc; /* Result code */
106216 ExprList *pOrderBy; /* The ORDER BY clause */
106217 Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */
106218 int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
106220 /* Obtain authorization to do a recursive query */
106221 if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
106223 /* Process the LIMIT and OFFSET clauses, if they exist */
106224 addrBreak = sqlite3VdbeMakeLabel(v);
106225 computeLimitRegisters(pParse, p, addrBreak);
106226 pLimit = p->pLimit;
106227 pOffset = p->pOffset;
106228 regLimit = p->iLimit;
106229 regOffset = p->iOffset;
106230 p->pLimit = p->pOffset = 0;
106231 p->iLimit = p->iOffset = 0;
106232 pOrderBy = p->pOrderBy;
106234 /* Locate the cursor number of the Current table */
106235 for(i=0; ALWAYS(i<pSrc->nSrc); i++){
106236 if( pSrc->a[i].isRecursive ){
106237 iCurrent = pSrc->a[i].iCursor;
106238 break;
106242 /* Allocate cursors numbers for Queue and Distinct. The cursor number for
106243 ** the Distinct table must be exactly one greater than Queue in order
106244 ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
106245 iQueue = pParse->nTab++;
106246 if( p->op==TK_UNION ){
106247 eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
106248 iDistinct = pParse->nTab++;
106249 }else{
106250 eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
106252 sqlite3SelectDestInit(&destQueue, eDest, iQueue);
106254 /* Allocate cursors for Current, Queue, and Distinct. */
106255 regCurrent = ++pParse->nMem;
106256 sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
106257 if( pOrderBy ){
106258 KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
106259 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
106260 (char*)pKeyInfo, P4_KEYINFO);
106261 destQueue.pOrderBy = pOrderBy;
106262 }else{
106263 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
106265 VdbeComment((v, "Queue table"));
106266 if( iDistinct ){
106267 p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
106268 p->selFlags |= SF_UsesEphemeral;
106271 /* Detach the ORDER BY clause from the compound SELECT */
106272 p->pOrderBy = 0;
106274 /* Store the results of the setup-query in Queue. */
106275 pSetup->pNext = 0;
106276 rc = sqlite3Select(pParse, pSetup, &destQueue);
106277 pSetup->pNext = p;
106278 if( rc ) goto end_of_recursive_query;
106280 /* Find the next row in the Queue and output that row */
106281 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
106283 /* Transfer the next row in Queue over to Current */
106284 sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
106285 if( pOrderBy ){
106286 sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
106287 }else{
106288 sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
106290 sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
106292 /* Output the single row in Current */
106293 addrCont = sqlite3VdbeMakeLabel(v);
106294 codeOffset(v, regOffset, addrCont);
106295 selectInnerLoop(pParse, p, p->pEList, iCurrent,
106296 0, 0, pDest, addrCont, addrBreak);
106297 if( regLimit ){
106298 sqlite3VdbeAddOp3(v, OP_IfZero, regLimit, addrBreak, -1);
106299 VdbeCoverage(v);
106301 sqlite3VdbeResolveLabel(v, addrCont);
106303 /* Execute the recursive SELECT taking the single row in Current as
106304 ** the value for the recursive-table. Store the results in the Queue.
106306 p->pPrior = 0;
106307 sqlite3Select(pParse, p, &destQueue);
106308 assert( p->pPrior==0 );
106309 p->pPrior = pSetup;
106311 /* Keep running the loop until the Queue is empty */
106312 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
106313 sqlite3VdbeResolveLabel(v, addrBreak);
106315 end_of_recursive_query:
106316 sqlite3ExprListDelete(pParse->db, p->pOrderBy);
106317 p->pOrderBy = pOrderBy;
106318 p->pLimit = pLimit;
106319 p->pOffset = pOffset;
106320 return;
106322 #endif /* SQLITE_OMIT_CTE */
106324 /* Forward references */
106325 static int multiSelectOrderBy(
106326 Parse *pParse, /* Parsing context */
106327 Select *p, /* The right-most of SELECTs to be coded */
106328 SelectDest *pDest /* What to do with query results */
106333 ** This routine is called to process a compound query form from
106334 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
106335 ** INTERSECT
106337 ** "p" points to the right-most of the two queries. the query on the
106338 ** left is p->pPrior. The left query could also be a compound query
106339 ** in which case this routine will be called recursively.
106341 ** The results of the total query are to be written into a destination
106342 ** of type eDest with parameter iParm.
106344 ** Example 1: Consider a three-way compound SQL statement.
106346 ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
106348 ** This statement is parsed up as follows:
106350 ** SELECT c FROM t3
106352 ** `-----> SELECT b FROM t2
106354 ** `------> SELECT a FROM t1
106356 ** The arrows in the diagram above represent the Select.pPrior pointer.
106357 ** So if this routine is called with p equal to the t3 query, then
106358 ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
106360 ** Notice that because of the way SQLite parses compound SELECTs, the
106361 ** individual selects always group from left to right.
106363 static int multiSelect(
106364 Parse *pParse, /* Parsing context */
106365 Select *p, /* The right-most of SELECTs to be coded */
106366 SelectDest *pDest /* What to do with query results */
106368 int rc = SQLITE_OK; /* Success code from a subroutine */
106369 Select *pPrior; /* Another SELECT immediately to our left */
106370 Vdbe *v; /* Generate code to this VDBE */
106371 SelectDest dest; /* Alternative data destination */
106372 Select *pDelete = 0; /* Chain of simple selects to delete */
106373 sqlite3 *db; /* Database connection */
106374 #ifndef SQLITE_OMIT_EXPLAIN
106375 int iSub1 = 0; /* EQP id of left-hand query */
106376 int iSub2 = 0; /* EQP id of right-hand query */
106377 #endif
106379 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
106380 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
106382 assert( p && p->pPrior ); /* Calling function guarantees this much */
106383 assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
106384 db = pParse->db;
106385 pPrior = p->pPrior;
106386 dest = *pDest;
106387 if( pPrior->pOrderBy ){
106388 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
106389 selectOpName(p->op));
106390 rc = 1;
106391 goto multi_select_end;
106393 if( pPrior->pLimit ){
106394 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
106395 selectOpName(p->op));
106396 rc = 1;
106397 goto multi_select_end;
106400 v = sqlite3GetVdbe(pParse);
106401 assert( v!=0 ); /* The VDBE already created by calling function */
106403 /* Create the destination temporary table if necessary
106405 if( dest.eDest==SRT_EphemTab ){
106406 assert( p->pEList );
106407 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
106408 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
106409 dest.eDest = SRT_Table;
106412 /* Make sure all SELECTs in the statement have the same number of elements
106413 ** in their result sets.
106415 assert( p->pEList && pPrior->pEList );
106416 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
106417 if( p->selFlags & SF_Values ){
106418 sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
106419 }else{
106420 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
106421 " do not have the same number of result columns", selectOpName(p->op));
106423 rc = 1;
106424 goto multi_select_end;
106427 #ifndef SQLITE_OMIT_CTE
106428 if( p->selFlags & SF_Recursive ){
106429 generateWithRecursiveQuery(pParse, p, &dest);
106430 }else
106431 #endif
106433 /* Compound SELECTs that have an ORDER BY clause are handled separately.
106435 if( p->pOrderBy ){
106436 return multiSelectOrderBy(pParse, p, pDest);
106437 }else
106439 /* Generate code for the left and right SELECT statements.
106441 switch( p->op ){
106442 case TK_ALL: {
106443 int addr = 0;
106444 int nLimit;
106445 assert( !pPrior->pLimit );
106446 pPrior->iLimit = p->iLimit;
106447 pPrior->iOffset = p->iOffset;
106448 pPrior->pLimit = p->pLimit;
106449 pPrior->pOffset = p->pOffset;
106450 explainSetInteger(iSub1, pParse->iNextSelectId);
106451 rc = sqlite3Select(pParse, pPrior, &dest);
106452 p->pLimit = 0;
106453 p->pOffset = 0;
106454 if( rc ){
106455 goto multi_select_end;
106457 p->pPrior = 0;
106458 p->iLimit = pPrior->iLimit;
106459 p->iOffset = pPrior->iOffset;
106460 if( p->iLimit ){
106461 addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); VdbeCoverage(v);
106462 VdbeComment((v, "Jump ahead if LIMIT reached"));
106464 explainSetInteger(iSub2, pParse->iNextSelectId);
106465 rc = sqlite3Select(pParse, p, &dest);
106466 testcase( rc!=SQLITE_OK );
106467 pDelete = p->pPrior;
106468 p->pPrior = pPrior;
106469 p->nSelectRow += pPrior->nSelectRow;
106470 if( pPrior->pLimit
106471 && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
106472 && nLimit>0 && p->nSelectRow > (u64)nLimit
106474 p->nSelectRow = nLimit;
106476 if( addr ){
106477 sqlite3VdbeJumpHere(v, addr);
106479 break;
106481 case TK_EXCEPT:
106482 case TK_UNION: {
106483 int unionTab; /* Cursor number of the temporary table holding result */
106484 u8 op = 0; /* One of the SRT_ operations to apply to self */
106485 int priorOp; /* The SRT_ operation to apply to prior selects */
106486 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
106487 int addr;
106488 SelectDest uniondest;
106490 testcase( p->op==TK_EXCEPT );
106491 testcase( p->op==TK_UNION );
106492 priorOp = SRT_Union;
106493 if( dest.eDest==priorOp ){
106494 /* We can reuse a temporary table generated by a SELECT to our
106495 ** right.
106497 assert( p->pLimit==0 ); /* Not allowed on leftward elements */
106498 assert( p->pOffset==0 ); /* Not allowed on leftward elements */
106499 unionTab = dest.iSDParm;
106500 }else{
106501 /* We will need to create our own temporary table to hold the
106502 ** intermediate results.
106504 unionTab = pParse->nTab++;
106505 assert( p->pOrderBy==0 );
106506 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
106507 assert( p->addrOpenEphm[0] == -1 );
106508 p->addrOpenEphm[0] = addr;
106509 findRightmost(p)->selFlags |= SF_UsesEphemeral;
106510 assert( p->pEList );
106513 /* Code the SELECT statements to our left
106515 assert( !pPrior->pOrderBy );
106516 sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
106517 explainSetInteger(iSub1, pParse->iNextSelectId);
106518 rc = sqlite3Select(pParse, pPrior, &uniondest);
106519 if( rc ){
106520 goto multi_select_end;
106523 /* Code the current SELECT statement
106525 if( p->op==TK_EXCEPT ){
106526 op = SRT_Except;
106527 }else{
106528 assert( p->op==TK_UNION );
106529 op = SRT_Union;
106531 p->pPrior = 0;
106532 pLimit = p->pLimit;
106533 p->pLimit = 0;
106534 pOffset = p->pOffset;
106535 p->pOffset = 0;
106536 uniondest.eDest = op;
106537 explainSetInteger(iSub2, pParse->iNextSelectId);
106538 rc = sqlite3Select(pParse, p, &uniondest);
106539 testcase( rc!=SQLITE_OK );
106540 /* Query flattening in sqlite3Select() might refill p->pOrderBy.
106541 ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
106542 sqlite3ExprListDelete(db, p->pOrderBy);
106543 pDelete = p->pPrior;
106544 p->pPrior = pPrior;
106545 p->pOrderBy = 0;
106546 if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
106547 sqlite3ExprDelete(db, p->pLimit);
106548 p->pLimit = pLimit;
106549 p->pOffset = pOffset;
106550 p->iLimit = 0;
106551 p->iOffset = 0;
106553 /* Convert the data in the temporary table into whatever form
106554 ** it is that we currently need.
106556 assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
106557 if( dest.eDest!=priorOp ){
106558 int iCont, iBreak, iStart;
106559 assert( p->pEList );
106560 if( dest.eDest==SRT_Output ){
106561 Select *pFirst = p;
106562 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
106563 generateColumnNames(pParse, 0, pFirst->pEList);
106565 iBreak = sqlite3VdbeMakeLabel(v);
106566 iCont = sqlite3VdbeMakeLabel(v);
106567 computeLimitRegisters(pParse, p, iBreak);
106568 sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
106569 iStart = sqlite3VdbeCurrentAddr(v);
106570 selectInnerLoop(pParse, p, p->pEList, unionTab,
106571 0, 0, &dest, iCont, iBreak);
106572 sqlite3VdbeResolveLabel(v, iCont);
106573 sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
106574 sqlite3VdbeResolveLabel(v, iBreak);
106575 sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
106577 break;
106579 default: assert( p->op==TK_INTERSECT ); {
106580 int tab1, tab2;
106581 int iCont, iBreak, iStart;
106582 Expr *pLimit, *pOffset;
106583 int addr;
106584 SelectDest intersectdest;
106585 int r1;
106587 /* INTERSECT is different from the others since it requires
106588 ** two temporary tables. Hence it has its own case. Begin
106589 ** by allocating the tables we will need.
106591 tab1 = pParse->nTab++;
106592 tab2 = pParse->nTab++;
106593 assert( p->pOrderBy==0 );
106595 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
106596 assert( p->addrOpenEphm[0] == -1 );
106597 p->addrOpenEphm[0] = addr;
106598 findRightmost(p)->selFlags |= SF_UsesEphemeral;
106599 assert( p->pEList );
106601 /* Code the SELECTs to our left into temporary table "tab1".
106603 sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
106604 explainSetInteger(iSub1, pParse->iNextSelectId);
106605 rc = sqlite3Select(pParse, pPrior, &intersectdest);
106606 if( rc ){
106607 goto multi_select_end;
106610 /* Code the current SELECT into temporary table "tab2"
106612 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
106613 assert( p->addrOpenEphm[1] == -1 );
106614 p->addrOpenEphm[1] = addr;
106615 p->pPrior = 0;
106616 pLimit = p->pLimit;
106617 p->pLimit = 0;
106618 pOffset = p->pOffset;
106619 p->pOffset = 0;
106620 intersectdest.iSDParm = tab2;
106621 explainSetInteger(iSub2, pParse->iNextSelectId);
106622 rc = sqlite3Select(pParse, p, &intersectdest);
106623 testcase( rc!=SQLITE_OK );
106624 pDelete = p->pPrior;
106625 p->pPrior = pPrior;
106626 if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
106627 sqlite3ExprDelete(db, p->pLimit);
106628 p->pLimit = pLimit;
106629 p->pOffset = pOffset;
106631 /* Generate code to take the intersection of the two temporary
106632 ** tables.
106634 assert( p->pEList );
106635 if( dest.eDest==SRT_Output ){
106636 Select *pFirst = p;
106637 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
106638 generateColumnNames(pParse, 0, pFirst->pEList);
106640 iBreak = sqlite3VdbeMakeLabel(v);
106641 iCont = sqlite3VdbeMakeLabel(v);
106642 computeLimitRegisters(pParse, p, iBreak);
106643 sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
106644 r1 = sqlite3GetTempReg(pParse);
106645 iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
106646 sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
106647 sqlite3ReleaseTempReg(pParse, r1);
106648 selectInnerLoop(pParse, p, p->pEList, tab1,
106649 0, 0, &dest, iCont, iBreak);
106650 sqlite3VdbeResolveLabel(v, iCont);
106651 sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
106652 sqlite3VdbeResolveLabel(v, iBreak);
106653 sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
106654 sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
106655 break;
106659 explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
106661 /* Compute collating sequences used by
106662 ** temporary tables needed to implement the compound select.
106663 ** Attach the KeyInfo structure to all temporary tables.
106665 ** This section is run by the right-most SELECT statement only.
106666 ** SELECT statements to the left always skip this part. The right-most
106667 ** SELECT might also skip this part if it has no ORDER BY clause and
106668 ** no temp tables are required.
106670 if( p->selFlags & SF_UsesEphemeral ){
106671 int i; /* Loop counter */
106672 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
106673 Select *pLoop; /* For looping through SELECT statements */
106674 CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
106675 int nCol; /* Number of columns in result set */
106677 assert( p->pNext==0 );
106678 nCol = p->pEList->nExpr;
106679 pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
106680 if( !pKeyInfo ){
106681 rc = SQLITE_NOMEM;
106682 goto multi_select_end;
106684 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
106685 *apColl = multiSelectCollSeq(pParse, p, i);
106686 if( 0==*apColl ){
106687 *apColl = db->pDfltColl;
106691 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
106692 for(i=0; i<2; i++){
106693 int addr = pLoop->addrOpenEphm[i];
106694 if( addr<0 ){
106695 /* If [0] is unused then [1] is also unused. So we can
106696 ** always safely abort as soon as the first unused slot is found */
106697 assert( pLoop->addrOpenEphm[1]<0 );
106698 break;
106700 sqlite3VdbeChangeP2(v, addr, nCol);
106701 sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
106702 P4_KEYINFO);
106703 pLoop->addrOpenEphm[i] = -1;
106706 sqlite3KeyInfoUnref(pKeyInfo);
106709 multi_select_end:
106710 pDest->iSdst = dest.iSdst;
106711 pDest->nSdst = dest.nSdst;
106712 sqlite3SelectDelete(db, pDelete);
106713 return rc;
106715 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
106718 ** Code an output subroutine for a coroutine implementation of a
106719 ** SELECT statment.
106721 ** The data to be output is contained in pIn->iSdst. There are
106722 ** pIn->nSdst columns to be output. pDest is where the output should
106723 ** be sent.
106725 ** regReturn is the number of the register holding the subroutine
106726 ** return address.
106728 ** If regPrev>0 then it is the first register in a vector that
106729 ** records the previous output. mem[regPrev] is a flag that is false
106730 ** if there has been no previous output. If regPrev>0 then code is
106731 ** generated to suppress duplicates. pKeyInfo is used for comparing
106732 ** keys.
106734 ** If the LIMIT found in p->iLimit is reached, jump immediately to
106735 ** iBreak.
106737 static int generateOutputSubroutine(
106738 Parse *pParse, /* Parsing context */
106739 Select *p, /* The SELECT statement */
106740 SelectDest *pIn, /* Coroutine supplying data */
106741 SelectDest *pDest, /* Where to send the data */
106742 int regReturn, /* The return address register */
106743 int regPrev, /* Previous result register. No uniqueness if 0 */
106744 KeyInfo *pKeyInfo, /* For comparing with previous entry */
106745 int iBreak /* Jump here if we hit the LIMIT */
106747 Vdbe *v = pParse->pVdbe;
106748 int iContinue;
106749 int addr;
106751 addr = sqlite3VdbeCurrentAddr(v);
106752 iContinue = sqlite3VdbeMakeLabel(v);
106754 /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
106756 if( regPrev ){
106757 int j1, j2;
106758 j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
106759 j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
106760 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
106761 sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); VdbeCoverage(v);
106762 sqlite3VdbeJumpHere(v, j1);
106763 sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
106764 sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
106766 if( pParse->db->mallocFailed ) return 0;
106768 /* Suppress the first OFFSET entries if there is an OFFSET clause
106770 codeOffset(v, p->iOffset, iContinue);
106772 switch( pDest->eDest ){
106773 /* Store the result as data using a unique key.
106775 case SRT_Table:
106776 case SRT_EphemTab: {
106777 int r1 = sqlite3GetTempReg(pParse);
106778 int r2 = sqlite3GetTempReg(pParse);
106779 testcase( pDest->eDest==SRT_Table );
106780 testcase( pDest->eDest==SRT_EphemTab );
106781 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
106782 sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
106783 sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
106784 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
106785 sqlite3ReleaseTempReg(pParse, r2);
106786 sqlite3ReleaseTempReg(pParse, r1);
106787 break;
106790 #ifndef SQLITE_OMIT_SUBQUERY
106791 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
106792 ** then there should be a single item on the stack. Write this
106793 ** item into the set table with bogus data.
106795 case SRT_Set: {
106796 int r1;
106797 assert( pIn->nSdst==1 );
106798 pDest->affSdst =
106799 sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
106800 r1 = sqlite3GetTempReg(pParse);
106801 sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
106802 sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
106803 sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
106804 sqlite3ReleaseTempReg(pParse, r1);
106805 break;
106808 #if 0 /* Never occurs on an ORDER BY query */
106809 /* If any row exist in the result set, record that fact and abort.
106811 case SRT_Exists: {
106812 sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
106813 /* The LIMIT clause will terminate the loop for us */
106814 break;
106816 #endif
106818 /* If this is a scalar select that is part of an expression, then
106819 ** store the results in the appropriate memory cell and break out
106820 ** of the scan loop.
106822 case SRT_Mem: {
106823 assert( pIn->nSdst==1 );
106824 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
106825 /* The LIMIT clause will jump out of the loop for us */
106826 break;
106828 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
106830 /* The results are stored in a sequence of registers
106831 ** starting at pDest->iSdst. Then the co-routine yields.
106833 case SRT_Coroutine: {
106834 if( pDest->iSdst==0 ){
106835 pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
106836 pDest->nSdst = pIn->nSdst;
106838 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
106839 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
106840 break;
106843 /* If none of the above, then the result destination must be
106844 ** SRT_Output. This routine is never called with any other
106845 ** destination other than the ones handled above or SRT_Output.
106847 ** For SRT_Output, results are stored in a sequence of registers.
106848 ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
106849 ** return the next row of result.
106851 default: {
106852 assert( pDest->eDest==SRT_Output );
106853 sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
106854 sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
106855 break;
106859 /* Jump to the end of the loop if the LIMIT is reached.
106861 if( p->iLimit ){
106862 sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
106865 /* Generate the subroutine return
106867 sqlite3VdbeResolveLabel(v, iContinue);
106868 sqlite3VdbeAddOp1(v, OP_Return, regReturn);
106870 return addr;
106874 ** Alternative compound select code generator for cases when there
106875 ** is an ORDER BY clause.
106877 ** We assume a query of the following form:
106879 ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
106881 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
106882 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
106883 ** co-routines. Then run the co-routines in parallel and merge the results
106884 ** into the output. In addition to the two coroutines (called selectA and
106885 ** selectB) there are 7 subroutines:
106887 ** outA: Move the output of the selectA coroutine into the output
106888 ** of the compound query.
106890 ** outB: Move the output of the selectB coroutine into the output
106891 ** of the compound query. (Only generated for UNION and
106892 ** UNION ALL. EXCEPT and INSERTSECT never output a row that
106893 ** appears only in B.)
106895 ** AltB: Called when there is data from both coroutines and A<B.
106897 ** AeqB: Called when there is data from both coroutines and A==B.
106899 ** AgtB: Called when there is data from both coroutines and A>B.
106901 ** EofA: Called when data is exhausted from selectA.
106903 ** EofB: Called when data is exhausted from selectB.
106905 ** The implementation of the latter five subroutines depend on which
106906 ** <operator> is used:
106909 ** UNION ALL UNION EXCEPT INTERSECT
106910 ** ------------- ----------------- -------------- -----------------
106911 ** AltB: outA, nextA outA, nextA outA, nextA nextA
106913 ** AeqB: outA, nextA nextA nextA outA, nextA
106915 ** AgtB: outB, nextB outB, nextB nextB nextB
106917 ** EofA: outB, nextB outB, nextB halt halt
106919 ** EofB: outA, nextA outA, nextA outA, nextA halt
106921 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
106922 ** causes an immediate jump to EofA and an EOF on B following nextB causes
106923 ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
106924 ** following nextX causes a jump to the end of the select processing.
106926 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
106927 ** within the output subroutine. The regPrev register set holds the previously
106928 ** output value. A comparison is made against this value and the output
106929 ** is skipped if the next results would be the same as the previous.
106931 ** The implementation plan is to implement the two coroutines and seven
106932 ** subroutines first, then put the control logic at the bottom. Like this:
106934 ** goto Init
106935 ** coA: coroutine for left query (A)
106936 ** coB: coroutine for right query (B)
106937 ** outA: output one row of A
106938 ** outB: output one row of B (UNION and UNION ALL only)
106939 ** EofA: ...
106940 ** EofB: ...
106941 ** AltB: ...
106942 ** AeqB: ...
106943 ** AgtB: ...
106944 ** Init: initialize coroutine registers
106945 ** yield coA
106946 ** if eof(A) goto EofA
106947 ** yield coB
106948 ** if eof(B) goto EofB
106949 ** Cmpr: Compare A, B
106950 ** Jump AltB, AeqB, AgtB
106951 ** End: ...
106953 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
106954 ** actually called using Gosub and they do not Return. EofA and EofB loop
106955 ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
106956 ** and AgtB jump to either L2 or to one of EofA or EofB.
106958 #ifndef SQLITE_OMIT_COMPOUND_SELECT
106959 static int multiSelectOrderBy(
106960 Parse *pParse, /* Parsing context */
106961 Select *p, /* The right-most of SELECTs to be coded */
106962 SelectDest *pDest /* What to do with query results */
106964 int i, j; /* Loop counters */
106965 Select *pPrior; /* Another SELECT immediately to our left */
106966 Vdbe *v; /* Generate code to this VDBE */
106967 SelectDest destA; /* Destination for coroutine A */
106968 SelectDest destB; /* Destination for coroutine B */
106969 int regAddrA; /* Address register for select-A coroutine */
106970 int regAddrB; /* Address register for select-B coroutine */
106971 int addrSelectA; /* Address of the select-A coroutine */
106972 int addrSelectB; /* Address of the select-B coroutine */
106973 int regOutA; /* Address register for the output-A subroutine */
106974 int regOutB; /* Address register for the output-B subroutine */
106975 int addrOutA; /* Address of the output-A subroutine */
106976 int addrOutB = 0; /* Address of the output-B subroutine */
106977 int addrEofA; /* Address of the select-A-exhausted subroutine */
106978 int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
106979 int addrEofB; /* Address of the select-B-exhausted subroutine */
106980 int addrAltB; /* Address of the A<B subroutine */
106981 int addrAeqB; /* Address of the A==B subroutine */
106982 int addrAgtB; /* Address of the A>B subroutine */
106983 int regLimitA; /* Limit register for select-A */
106984 int regLimitB; /* Limit register for select-A */
106985 int regPrev; /* A range of registers to hold previous output */
106986 int savedLimit; /* Saved value of p->iLimit */
106987 int savedOffset; /* Saved value of p->iOffset */
106988 int labelCmpr; /* Label for the start of the merge algorithm */
106989 int labelEnd; /* Label for the end of the overall SELECT stmt */
106990 int j1; /* Jump instructions that get retargetted */
106991 int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
106992 KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
106993 KeyInfo *pKeyMerge; /* Comparison information for merging rows */
106994 sqlite3 *db; /* Database connection */
106995 ExprList *pOrderBy; /* The ORDER BY clause */
106996 int nOrderBy; /* Number of terms in the ORDER BY clause */
106997 int *aPermute; /* Mapping from ORDER BY terms to result set columns */
106998 #ifndef SQLITE_OMIT_EXPLAIN
106999 int iSub1; /* EQP id of left-hand query */
107000 int iSub2; /* EQP id of right-hand query */
107001 #endif
107003 assert( p->pOrderBy!=0 );
107004 assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
107005 db = pParse->db;
107006 v = pParse->pVdbe;
107007 assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
107008 labelEnd = sqlite3VdbeMakeLabel(v);
107009 labelCmpr = sqlite3VdbeMakeLabel(v);
107012 /* Patch up the ORDER BY clause
107014 op = p->op;
107015 pPrior = p->pPrior;
107016 assert( pPrior->pOrderBy==0 );
107017 pOrderBy = p->pOrderBy;
107018 assert( pOrderBy );
107019 nOrderBy = pOrderBy->nExpr;
107021 /* For operators other than UNION ALL we have to make sure that
107022 ** the ORDER BY clause covers every term of the result set. Add
107023 ** terms to the ORDER BY clause as necessary.
107025 if( op!=TK_ALL ){
107026 for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
107027 struct ExprList_item *pItem;
107028 for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
107029 assert( pItem->u.x.iOrderByCol>0 );
107030 if( pItem->u.x.iOrderByCol==i ) break;
107032 if( j==nOrderBy ){
107033 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
107034 if( pNew==0 ) return SQLITE_NOMEM;
107035 pNew->flags |= EP_IntValue;
107036 pNew->u.iValue = i;
107037 pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
107038 if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
107043 /* Compute the comparison permutation and keyinfo that is used with
107044 ** the permutation used to determine if the next
107045 ** row of results comes from selectA or selectB. Also add explicit
107046 ** collations to the ORDER BY clause terms so that when the subqueries
107047 ** to the right and the left are evaluated, they use the correct
107048 ** collation.
107050 aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
107051 if( aPermute ){
107052 struct ExprList_item *pItem;
107053 for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
107054 assert( pItem->u.x.iOrderByCol>0
107055 && pItem->u.x.iOrderByCol<=p->pEList->nExpr );
107056 aPermute[i] = pItem->u.x.iOrderByCol - 1;
107058 pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
107059 }else{
107060 pKeyMerge = 0;
107063 /* Reattach the ORDER BY clause to the query.
107065 p->pOrderBy = pOrderBy;
107066 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
107068 /* Allocate a range of temporary registers and the KeyInfo needed
107069 ** for the logic that removes duplicate result rows when the
107070 ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
107072 if( op==TK_ALL ){
107073 regPrev = 0;
107074 }else{
107075 int nExpr = p->pEList->nExpr;
107076 assert( nOrderBy>=nExpr || db->mallocFailed );
107077 regPrev = pParse->nMem+1;
107078 pParse->nMem += nExpr+1;
107079 sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
107080 pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
107081 if( pKeyDup ){
107082 assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
107083 for(i=0; i<nExpr; i++){
107084 pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
107085 pKeyDup->aSortOrder[i] = 0;
107090 /* Separate the left and the right query from one another
107092 p->pPrior = 0;
107093 pPrior->pNext = 0;
107094 sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
107095 if( pPrior->pPrior==0 ){
107096 sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
107099 /* Compute the limit registers */
107100 computeLimitRegisters(pParse, p, labelEnd);
107101 if( p->iLimit && op==TK_ALL ){
107102 regLimitA = ++pParse->nMem;
107103 regLimitB = ++pParse->nMem;
107104 sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
107105 regLimitA);
107106 sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
107107 }else{
107108 regLimitA = regLimitB = 0;
107110 sqlite3ExprDelete(db, p->pLimit);
107111 p->pLimit = 0;
107112 sqlite3ExprDelete(db, p->pOffset);
107113 p->pOffset = 0;
107115 regAddrA = ++pParse->nMem;
107116 regAddrB = ++pParse->nMem;
107117 regOutA = ++pParse->nMem;
107118 regOutB = ++pParse->nMem;
107119 sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
107120 sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
107122 /* Generate a coroutine to evaluate the SELECT statement to the
107123 ** left of the compound operator - the "A" select.
107125 addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
107126 j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
107127 VdbeComment((v, "left SELECT"));
107128 pPrior->iLimit = regLimitA;
107129 explainSetInteger(iSub1, pParse->iNextSelectId);
107130 sqlite3Select(pParse, pPrior, &destA);
107131 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
107132 sqlite3VdbeJumpHere(v, j1);
107134 /* Generate a coroutine to evaluate the SELECT statement on
107135 ** the right - the "B" select
107137 addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
107138 j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
107139 VdbeComment((v, "right SELECT"));
107140 savedLimit = p->iLimit;
107141 savedOffset = p->iOffset;
107142 p->iLimit = regLimitB;
107143 p->iOffset = 0;
107144 explainSetInteger(iSub2, pParse->iNextSelectId);
107145 sqlite3Select(pParse, p, &destB);
107146 p->iLimit = savedLimit;
107147 p->iOffset = savedOffset;
107148 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
107150 /* Generate a subroutine that outputs the current row of the A
107151 ** select as the next output row of the compound select.
107153 VdbeNoopComment((v, "Output routine for A"));
107154 addrOutA = generateOutputSubroutine(pParse,
107155 p, &destA, pDest, regOutA,
107156 regPrev, pKeyDup, labelEnd);
107158 /* Generate a subroutine that outputs the current row of the B
107159 ** select as the next output row of the compound select.
107161 if( op==TK_ALL || op==TK_UNION ){
107162 VdbeNoopComment((v, "Output routine for B"));
107163 addrOutB = generateOutputSubroutine(pParse,
107164 p, &destB, pDest, regOutB,
107165 regPrev, pKeyDup, labelEnd);
107167 sqlite3KeyInfoUnref(pKeyDup);
107169 /* Generate a subroutine to run when the results from select A
107170 ** are exhausted and only data in select B remains.
107172 if( op==TK_EXCEPT || op==TK_INTERSECT ){
107173 addrEofA_noB = addrEofA = labelEnd;
107174 }else{
107175 VdbeNoopComment((v, "eof-A subroutine"));
107176 addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
107177 addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
107178 VdbeCoverage(v);
107179 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
107180 p->nSelectRow += pPrior->nSelectRow;
107183 /* Generate a subroutine to run when the results from select B
107184 ** are exhausted and only data in select A remains.
107186 if( op==TK_INTERSECT ){
107187 addrEofB = addrEofA;
107188 if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
107189 }else{
107190 VdbeNoopComment((v, "eof-B subroutine"));
107191 addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
107192 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
107193 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
107196 /* Generate code to handle the case of A<B
107198 VdbeNoopComment((v, "A-lt-B subroutine"));
107199 addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
107200 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
107201 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
107203 /* Generate code to handle the case of A==B
107205 if( op==TK_ALL ){
107206 addrAeqB = addrAltB;
107207 }else if( op==TK_INTERSECT ){
107208 addrAeqB = addrAltB;
107209 addrAltB++;
107210 }else{
107211 VdbeNoopComment((v, "A-eq-B subroutine"));
107212 addrAeqB =
107213 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
107214 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
107217 /* Generate code to handle the case of A>B
107219 VdbeNoopComment((v, "A-gt-B subroutine"));
107220 addrAgtB = sqlite3VdbeCurrentAddr(v);
107221 if( op==TK_ALL || op==TK_UNION ){
107222 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
107224 sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
107225 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
107227 /* This code runs once to initialize everything.
107229 sqlite3VdbeJumpHere(v, j1);
107230 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
107231 sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
107233 /* Implement the main merge loop
107235 sqlite3VdbeResolveLabel(v, labelCmpr);
107236 sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
107237 sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
107238 (char*)pKeyMerge, P4_KEYINFO);
107239 sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
107240 sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
107242 /* Jump to the this point in order to terminate the query.
107244 sqlite3VdbeResolveLabel(v, labelEnd);
107246 /* Set the number of output columns
107248 if( pDest->eDest==SRT_Output ){
107249 Select *pFirst = pPrior;
107250 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
107251 generateColumnNames(pParse, 0, pFirst->pEList);
107254 /* Reassembly the compound query so that it will be freed correctly
107255 ** by the calling function */
107256 if( p->pPrior ){
107257 sqlite3SelectDelete(db, p->pPrior);
107259 p->pPrior = pPrior;
107260 pPrior->pNext = p;
107262 /*** TBD: Insert subroutine calls to close cursors on incomplete
107263 **** subqueries ****/
107264 explainComposite(pParse, p->op, iSub1, iSub2, 0);
107265 return SQLITE_OK;
107267 #endif
107269 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
107270 /* Forward Declarations */
107271 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
107272 static void substSelect(sqlite3*, Select *, int, ExprList *);
107275 ** Scan through the expression pExpr. Replace every reference to
107276 ** a column in table number iTable with a copy of the iColumn-th
107277 ** entry in pEList. (But leave references to the ROWID column
107278 ** unchanged.)
107280 ** This routine is part of the flattening procedure. A subquery
107281 ** whose result set is defined by pEList appears as entry in the
107282 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
107283 ** FORM clause entry is iTable. This routine make the necessary
107284 ** changes to pExpr so that it refers directly to the source table
107285 ** of the subquery rather the result set of the subquery.
107287 static Expr *substExpr(
107288 sqlite3 *db, /* Report malloc errors to this connection */
107289 Expr *pExpr, /* Expr in which substitution occurs */
107290 int iTable, /* Table to be substituted */
107291 ExprList *pEList /* Substitute expressions */
107293 if( pExpr==0 ) return 0;
107294 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
107295 if( pExpr->iColumn<0 ){
107296 pExpr->op = TK_NULL;
107297 }else{
107298 Expr *pNew;
107299 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
107300 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
107301 pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
107302 sqlite3ExprDelete(db, pExpr);
107303 pExpr = pNew;
107305 }else{
107306 pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
107307 pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
107308 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
107309 substSelect(db, pExpr->x.pSelect, iTable, pEList);
107310 }else{
107311 substExprList(db, pExpr->x.pList, iTable, pEList);
107314 return pExpr;
107316 static void substExprList(
107317 sqlite3 *db, /* Report malloc errors here */
107318 ExprList *pList, /* List to scan and in which to make substitutes */
107319 int iTable, /* Table to be substituted */
107320 ExprList *pEList /* Substitute values */
107322 int i;
107323 if( pList==0 ) return;
107324 for(i=0; i<pList->nExpr; i++){
107325 pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
107328 static void substSelect(
107329 sqlite3 *db, /* Report malloc errors here */
107330 Select *p, /* SELECT statement in which to make substitutions */
107331 int iTable, /* Table to be replaced */
107332 ExprList *pEList /* Substitute values */
107334 SrcList *pSrc;
107335 struct SrcList_item *pItem;
107336 int i;
107337 if( !p ) return;
107338 substExprList(db, p->pEList, iTable, pEList);
107339 substExprList(db, p->pGroupBy, iTable, pEList);
107340 substExprList(db, p->pOrderBy, iTable, pEList);
107341 p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
107342 p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
107343 substSelect(db, p->pPrior, iTable, pEList);
107344 pSrc = p->pSrc;
107345 assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
107346 if( ALWAYS(pSrc) ){
107347 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
107348 substSelect(db, pItem->pSelect, iTable, pEList);
107352 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
107354 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
107356 ** This routine attempts to flatten subqueries as a performance optimization.
107357 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
107359 ** To understand the concept of flattening, consider the following
107360 ** query:
107362 ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
107364 ** The default way of implementing this query is to execute the
107365 ** subquery first and store the results in a temporary table, then
107366 ** run the outer query on that temporary table. This requires two
107367 ** passes over the data. Furthermore, because the temporary table
107368 ** has no indices, the WHERE clause on the outer query cannot be
107369 ** optimized.
107371 ** This routine attempts to rewrite queries such as the above into
107372 ** a single flat select, like this:
107374 ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
107376 ** The code generated for this simplification gives the same result
107377 ** but only has to scan the data once. And because indices might
107378 ** exist on the table t1, a complete scan of the data might be
107379 ** avoided.
107381 ** Flattening is only attempted if all of the following are true:
107383 ** (1) The subquery and the outer query do not both use aggregates.
107385 ** (2) The subquery is not an aggregate or the outer query is not a join.
107387 ** (3) The subquery is not the right operand of a left outer join
107388 ** (Originally ticket #306. Strengthened by ticket #3300)
107390 ** (4) The subquery is not DISTINCT.
107392 ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
107393 ** sub-queries that were excluded from this optimization. Restriction
107394 ** (4) has since been expanded to exclude all DISTINCT subqueries.
107396 ** (6) The subquery does not use aggregates or the outer query is not
107397 ** DISTINCT.
107399 ** (7) The subquery has a FROM clause. TODO: For subqueries without
107400 ** A FROM clause, consider adding a FROM close with the special
107401 ** table sqlite_once that consists of a single row containing a
107402 ** single NULL.
107404 ** (8) The subquery does not use LIMIT or the outer query is not a join.
107406 ** (9) The subquery does not use LIMIT or the outer query does not use
107407 ** aggregates.
107409 ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
107410 ** accidently carried the comment forward until 2014-09-15. Original
107411 ** text: "The subquery does not use aggregates or the outer query does not
107412 ** use LIMIT."
107414 ** (11) The subquery and the outer query do not both have ORDER BY clauses.
107416 ** (**) Not implemented. Subsumed into restriction (3). Was previously
107417 ** a separate restriction deriving from ticket #350.
107419 ** (13) The subquery and outer query do not both use LIMIT.
107421 ** (14) The subquery does not use OFFSET.
107423 ** (15) The outer query is not part of a compound select or the
107424 ** subquery does not have a LIMIT clause.
107425 ** (See ticket #2339 and ticket [02a8e81d44]).
107427 ** (16) The outer query is not an aggregate or the subquery does
107428 ** not contain ORDER BY. (Ticket #2942) This used to not matter
107429 ** until we introduced the group_concat() function.
107431 ** (17) The sub-query is not a compound select, or it is a UNION ALL
107432 ** compound clause made up entirely of non-aggregate queries, and
107433 ** the parent query:
107435 ** * is not itself part of a compound select,
107436 ** * is not an aggregate or DISTINCT query, and
107437 ** * is not a join
107439 ** The parent and sub-query may contain WHERE clauses. Subject to
107440 ** rules (11), (13) and (14), they may also contain ORDER BY,
107441 ** LIMIT and OFFSET clauses. The subquery cannot use any compound
107442 ** operator other than UNION ALL because all the other compound
107443 ** operators have an implied DISTINCT which is disallowed by
107444 ** restriction (4).
107446 ** Also, each component of the sub-query must return the same number
107447 ** of result columns. This is actually a requirement for any compound
107448 ** SELECT statement, but all the code here does is make sure that no
107449 ** such (illegal) sub-query is flattened. The caller will detect the
107450 ** syntax error and return a detailed message.
107452 ** (18) If the sub-query is a compound select, then all terms of the
107453 ** ORDER by clause of the parent must be simple references to
107454 ** columns of the sub-query.
107456 ** (19) The subquery does not use LIMIT or the outer query does not
107457 ** have a WHERE clause.
107459 ** (20) If the sub-query is a compound select, then it must not use
107460 ** an ORDER BY clause. Ticket #3773. We could relax this constraint
107461 ** somewhat by saying that the terms of the ORDER BY clause must
107462 ** appear as unmodified result columns in the outer query. But we
107463 ** have other optimizations in mind to deal with that case.
107465 ** (21) The subquery does not use LIMIT or the outer query is not
107466 ** DISTINCT. (See ticket [752e1646fc]).
107468 ** (22) The subquery is not a recursive CTE.
107470 ** (23) The parent is not a recursive CTE, or the sub-query is not a
107471 ** compound query. This restriction is because transforming the
107472 ** parent to a compound query confuses the code that handles
107473 ** recursive queries in multiSelect().
107475 ** (24) The subquery is not an aggregate that uses the built-in min() or
107476 ** or max() functions. (Without this restriction, a query like:
107477 ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
107478 ** return the value X for which Y was maximal.)
107481 ** In this routine, the "p" parameter is a pointer to the outer query.
107482 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
107483 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
107485 ** If flattening is not attempted, this routine is a no-op and returns 0.
107486 ** If flattening is attempted this routine returns 1.
107488 ** All of the expression analysis must occur on both the outer query and
107489 ** the subquery before this routine runs.
107491 static int flattenSubquery(
107492 Parse *pParse, /* Parsing context */
107493 Select *p, /* The parent or outer SELECT statement */
107494 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
107495 int isAgg, /* True if outer SELECT uses aggregate functions */
107496 int subqueryIsAgg /* True if the subquery uses aggregate functions */
107498 const char *zSavedAuthContext = pParse->zAuthContext;
107499 Select *pParent;
107500 Select *pSub; /* The inner query or "subquery" */
107501 Select *pSub1; /* Pointer to the rightmost select in sub-query */
107502 SrcList *pSrc; /* The FROM clause of the outer query */
107503 SrcList *pSubSrc; /* The FROM clause of the subquery */
107504 ExprList *pList; /* The result set of the outer query */
107505 int iParent; /* VDBE cursor number of the pSub result set temp table */
107506 int i; /* Loop counter */
107507 Expr *pWhere; /* The WHERE clause */
107508 struct SrcList_item *pSubitem; /* The subquery */
107509 sqlite3 *db = pParse->db;
107511 /* Check to see if flattening is permitted. Return 0 if not.
107513 assert( p!=0 );
107514 assert( p->pPrior==0 ); /* Unable to flatten compound queries */
107515 if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
107516 pSrc = p->pSrc;
107517 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
107518 pSubitem = &pSrc->a[iFrom];
107519 iParent = pSubitem->iCursor;
107520 pSub = pSubitem->pSelect;
107521 assert( pSub!=0 );
107522 if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
107523 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
107524 pSubSrc = pSub->pSrc;
107525 assert( pSubSrc );
107526 /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
107527 ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
107528 ** because they could be computed at compile-time. But when LIMIT and OFFSET
107529 ** became arbitrary expressions, we were forced to add restrictions (13)
107530 ** and (14). */
107531 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
107532 if( pSub->pOffset ) return 0; /* Restriction (14) */
107533 if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
107534 return 0; /* Restriction (15) */
107536 if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
107537 if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
107538 if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
107539 return 0; /* Restrictions (8)(9) */
107541 if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
107542 return 0; /* Restriction (6) */
107544 if( p->pOrderBy && pSub->pOrderBy ){
107545 return 0; /* Restriction (11) */
107547 if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
107548 if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
107549 if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
107550 return 0; /* Restriction (21) */
107552 testcase( pSub->selFlags & SF_Recursive );
107553 testcase( pSub->selFlags & SF_MinMaxAgg );
107554 if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
107555 return 0; /* Restrictions (22) and (24) */
107557 if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
107558 return 0; /* Restriction (23) */
107561 /* OBSOLETE COMMENT 1:
107562 ** Restriction 3: If the subquery is a join, make sure the subquery is
107563 ** not used as the right operand of an outer join. Examples of why this
107564 ** is not allowed:
107566 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
107568 ** If we flatten the above, we would get
107570 ** (t1 LEFT OUTER JOIN t2) JOIN t3
107572 ** which is not at all the same thing.
107574 ** OBSOLETE COMMENT 2:
107575 ** Restriction 12: If the subquery is the right operand of a left outer
107576 ** join, make sure the subquery has no WHERE clause.
107577 ** An examples of why this is not allowed:
107579 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
107581 ** If we flatten the above, we would get
107583 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
107585 ** But the t2.x>0 test will always fail on a NULL row of t2, which
107586 ** effectively converts the OUTER JOIN into an INNER JOIN.
107588 ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
107589 ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
107590 ** is fraught with danger. Best to avoid the whole thing. If the
107591 ** subquery is the right term of a LEFT JOIN, then do not flatten.
107593 if( (pSubitem->jointype & JT_OUTER)!=0 ){
107594 return 0;
107597 /* Restriction 17: If the sub-query is a compound SELECT, then it must
107598 ** use only the UNION ALL operator. And none of the simple select queries
107599 ** that make up the compound SELECT are allowed to be aggregate or distinct
107600 ** queries.
107602 if( pSub->pPrior ){
107603 if( pSub->pOrderBy ){
107604 return 0; /* Restriction 20 */
107606 if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
107607 return 0;
107609 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
107610 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
107611 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
107612 assert( pSub->pSrc!=0 );
107613 if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
107614 || (pSub1->pPrior && pSub1->op!=TK_ALL)
107615 || pSub1->pSrc->nSrc<1
107616 || pSub->pEList->nExpr!=pSub1->pEList->nExpr
107618 return 0;
107620 testcase( pSub1->pSrc->nSrc>1 );
107623 /* Restriction 18. */
107624 if( p->pOrderBy ){
107625 int ii;
107626 for(ii=0; ii<p->pOrderBy->nExpr; ii++){
107627 if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
107632 /***** If we reach this point, flattening is permitted. *****/
107633 SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
107634 pSub->zSelName, pSub, iFrom));
107636 /* Authorize the subquery */
107637 pParse->zAuthContext = pSubitem->zName;
107638 TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
107639 testcase( i==SQLITE_DENY );
107640 pParse->zAuthContext = zSavedAuthContext;
107642 /* If the sub-query is a compound SELECT statement, then (by restrictions
107643 ** 17 and 18 above) it must be a UNION ALL and the parent query must
107644 ** be of the form:
107646 ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
107648 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
107649 ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
107650 ** OFFSET clauses and joins them to the left-hand-side of the original
107651 ** using UNION ALL operators. In this case N is the number of simple
107652 ** select statements in the compound sub-query.
107654 ** Example:
107656 ** SELECT a+1 FROM (
107657 ** SELECT x FROM tab
107658 ** UNION ALL
107659 ** SELECT y FROM tab
107660 ** UNION ALL
107661 ** SELECT abs(z*2) FROM tab2
107662 ** ) WHERE a!=5 ORDER BY 1
107664 ** Transformed into:
107666 ** SELECT x+1 FROM tab WHERE x+1!=5
107667 ** UNION ALL
107668 ** SELECT y+1 FROM tab WHERE y+1!=5
107669 ** UNION ALL
107670 ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
107671 ** ORDER BY 1
107673 ** We call this the "compound-subquery flattening".
107675 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
107676 Select *pNew;
107677 ExprList *pOrderBy = p->pOrderBy;
107678 Expr *pLimit = p->pLimit;
107679 Expr *pOffset = p->pOffset;
107680 Select *pPrior = p->pPrior;
107681 p->pOrderBy = 0;
107682 p->pSrc = 0;
107683 p->pPrior = 0;
107684 p->pLimit = 0;
107685 p->pOffset = 0;
107686 pNew = sqlite3SelectDup(db, p, 0);
107687 sqlite3SelectSetName(pNew, pSub->zSelName);
107688 p->pOffset = pOffset;
107689 p->pLimit = pLimit;
107690 p->pOrderBy = pOrderBy;
107691 p->pSrc = pSrc;
107692 p->op = TK_ALL;
107693 if( pNew==0 ){
107694 p->pPrior = pPrior;
107695 }else{
107696 pNew->pPrior = pPrior;
107697 if( pPrior ) pPrior->pNext = pNew;
107698 pNew->pNext = p;
107699 p->pPrior = pNew;
107700 SELECTTRACE(2,pParse,p,
107701 ("compound-subquery flattener creates %s.%p as peer\n",
107702 pNew->zSelName, pNew));
107704 if( db->mallocFailed ) return 1;
107707 /* Begin flattening the iFrom-th entry of the FROM clause
107708 ** in the outer query.
107710 pSub = pSub1 = pSubitem->pSelect;
107712 /* Delete the transient table structure associated with the
107713 ** subquery
107715 sqlite3DbFree(db, pSubitem->zDatabase);
107716 sqlite3DbFree(db, pSubitem->zName);
107717 sqlite3DbFree(db, pSubitem->zAlias);
107718 pSubitem->zDatabase = 0;
107719 pSubitem->zName = 0;
107720 pSubitem->zAlias = 0;
107721 pSubitem->pSelect = 0;
107723 /* Defer deleting the Table object associated with the
107724 ** subquery until code generation is
107725 ** complete, since there may still exist Expr.pTab entries that
107726 ** refer to the subquery even after flattening. Ticket #3346.
107728 ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
107730 if( ALWAYS(pSubitem->pTab!=0) ){
107731 Table *pTabToDel = pSubitem->pTab;
107732 if( pTabToDel->nRef==1 ){
107733 Parse *pToplevel = sqlite3ParseToplevel(pParse);
107734 pTabToDel->pNextZombie = pToplevel->pZombieTab;
107735 pToplevel->pZombieTab = pTabToDel;
107736 }else{
107737 pTabToDel->nRef--;
107739 pSubitem->pTab = 0;
107742 /* The following loop runs once for each term in a compound-subquery
107743 ** flattening (as described above). If we are doing a different kind
107744 ** of flattening - a flattening other than a compound-subquery flattening -
107745 ** then this loop only runs once.
107747 ** This loop moves all of the FROM elements of the subquery into the
107748 ** the FROM clause of the outer query. Before doing this, remember
107749 ** the cursor number for the original outer query FROM element in
107750 ** iParent. The iParent cursor will never be used. Subsequent code
107751 ** will scan expressions looking for iParent references and replace
107752 ** those references with expressions that resolve to the subquery FROM
107753 ** elements we are now copying in.
107755 for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
107756 int nSubSrc;
107757 u8 jointype = 0;
107758 pSubSrc = pSub->pSrc; /* FROM clause of subquery */
107759 nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
107760 pSrc = pParent->pSrc; /* FROM clause of the outer query */
107762 if( pSrc ){
107763 assert( pParent==p ); /* First time through the loop */
107764 jointype = pSubitem->jointype;
107765 }else{
107766 assert( pParent!=p ); /* 2nd and subsequent times through the loop */
107767 pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
107768 if( pSrc==0 ){
107769 assert( db->mallocFailed );
107770 break;
107774 /* The subquery uses a single slot of the FROM clause of the outer
107775 ** query. If the subquery has more than one element in its FROM clause,
107776 ** then expand the outer query to make space for it to hold all elements
107777 ** of the subquery.
107779 ** Example:
107781 ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
107783 ** The outer query has 3 slots in its FROM clause. One slot of the
107784 ** outer query (the middle slot) is used by the subquery. The next
107785 ** block of code will expand the out query to 4 slots. The middle
107786 ** slot is expanded to two slots in order to make space for the
107787 ** two elements in the FROM clause of the subquery.
107789 if( nSubSrc>1 ){
107790 pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
107791 if( db->mallocFailed ){
107792 break;
107796 /* Transfer the FROM clause terms from the subquery into the
107797 ** outer query.
107799 for(i=0; i<nSubSrc; i++){
107800 sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
107801 pSrc->a[i+iFrom] = pSubSrc->a[i];
107802 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
107804 pSrc->a[iFrom].jointype = jointype;
107806 /* Now begin substituting subquery result set expressions for
107807 ** references to the iParent in the outer query.
107809 ** Example:
107811 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
107812 ** \ \_____________ subquery __________/ /
107813 ** \_____________________ outer query ______________________________/
107815 ** We look at every expression in the outer query and every place we see
107816 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
107818 pList = pParent->pEList;
107819 for(i=0; i<pList->nExpr; i++){
107820 if( pList->a[i].zName==0 ){
107821 char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
107822 sqlite3Dequote(zName);
107823 pList->a[i].zName = zName;
107826 substExprList(db, pParent->pEList, iParent, pSub->pEList);
107827 if( isAgg ){
107828 substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
107829 pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
107831 if( pSub->pOrderBy ){
107832 /* At this point, any non-zero iOrderByCol values indicate that the
107833 ** ORDER BY column expression is identical to the iOrderByCol'th
107834 ** expression returned by SELECT statement pSub. Since these values
107835 ** do not necessarily correspond to columns in SELECT statement pParent,
107836 ** zero them before transfering the ORDER BY clause.
107838 ** Not doing this may cause an error if a subsequent call to this
107839 ** function attempts to flatten a compound sub-query into pParent
107840 ** (the only way this can happen is if the compound sub-query is
107841 ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
107842 ExprList *pOrderBy = pSub->pOrderBy;
107843 for(i=0; i<pOrderBy->nExpr; i++){
107844 pOrderBy->a[i].u.x.iOrderByCol = 0;
107846 assert( pParent->pOrderBy==0 );
107847 assert( pSub->pPrior==0 );
107848 pParent->pOrderBy = pOrderBy;
107849 pSub->pOrderBy = 0;
107850 }else if( pParent->pOrderBy ){
107851 substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
107853 if( pSub->pWhere ){
107854 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
107855 }else{
107856 pWhere = 0;
107858 if( subqueryIsAgg ){
107859 assert( pParent->pHaving==0 );
107860 pParent->pHaving = pParent->pWhere;
107861 pParent->pWhere = pWhere;
107862 pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
107863 pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
107864 sqlite3ExprDup(db, pSub->pHaving, 0));
107865 assert( pParent->pGroupBy==0 );
107866 pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
107867 }else{
107868 pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
107869 pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
107872 /* The flattened query is distinct if either the inner or the
107873 ** outer query is distinct.
107875 pParent->selFlags |= pSub->selFlags & SF_Distinct;
107878 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
107880 ** One is tempted to try to add a and b to combine the limits. But this
107881 ** does not work if either limit is negative.
107883 if( pSub->pLimit ){
107884 pParent->pLimit = pSub->pLimit;
107885 pSub->pLimit = 0;
107889 /* Finially, delete what is left of the subquery and return
107890 ** success.
107892 sqlite3SelectDelete(db, pSub1);
107894 #if SELECTTRACE_ENABLED
107895 if( sqlite3SelectTrace & 0x100 ){
107896 sqlite3DebugPrintf("After flattening:\n");
107897 sqlite3TreeViewSelect(0, p, 0);
107899 #endif
107901 return 1;
107903 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
107906 ** Based on the contents of the AggInfo structure indicated by the first
107907 ** argument, this function checks if the following are true:
107909 ** * the query contains just a single aggregate function,
107910 ** * the aggregate function is either min() or max(), and
107911 ** * the argument to the aggregate function is a column value.
107913 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
107914 ** is returned as appropriate. Also, *ppMinMax is set to point to the
107915 ** list of arguments passed to the aggregate before returning.
107917 ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
107918 ** WHERE_ORDERBY_NORMAL is returned.
107920 static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
107921 int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
107923 *ppMinMax = 0;
107924 if( pAggInfo->nFunc==1 ){
107925 Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
107926 ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
107928 assert( pExpr->op==TK_AGG_FUNCTION );
107929 if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
107930 const char *zFunc = pExpr->u.zToken;
107931 if( sqlite3StrICmp(zFunc, "min")==0 ){
107932 eRet = WHERE_ORDERBY_MIN;
107933 *ppMinMax = pEList;
107934 }else if( sqlite3StrICmp(zFunc, "max")==0 ){
107935 eRet = WHERE_ORDERBY_MAX;
107936 *ppMinMax = pEList;
107941 assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
107942 return eRet;
107946 ** The select statement passed as the first argument is an aggregate query.
107947 ** The second argument is the associated aggregate-info object. This
107948 ** function tests if the SELECT is of the form:
107950 ** SELECT count(*) FROM <tbl>
107952 ** where table is a database table, not a sub-select or view. If the query
107953 ** does match this pattern, then a pointer to the Table object representing
107954 ** <tbl> is returned. Otherwise, 0 is returned.
107956 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
107957 Table *pTab;
107958 Expr *pExpr;
107960 assert( !p->pGroupBy );
107962 if( p->pWhere || p->pEList->nExpr!=1
107963 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
107965 return 0;
107967 pTab = p->pSrc->a[0].pTab;
107968 pExpr = p->pEList->a[0].pExpr;
107969 assert( pTab && !pTab->pSelect && pExpr );
107971 if( IsVirtual(pTab) ) return 0;
107972 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
107973 if( NEVER(pAggInfo->nFunc==0) ) return 0;
107974 if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
107975 if( pExpr->flags&EP_Distinct ) return 0;
107977 return pTab;
107981 ** If the source-list item passed as an argument was augmented with an
107982 ** INDEXED BY clause, then try to locate the specified index. If there
107983 ** was such a clause and the named index cannot be found, return
107984 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
107985 ** pFrom->pIndex and return SQLITE_OK.
107987 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
107988 if( pFrom->pTab && pFrom->zIndex ){
107989 Table *pTab = pFrom->pTab;
107990 char *zIndex = pFrom->zIndex;
107991 Index *pIdx;
107992 for(pIdx=pTab->pIndex;
107993 pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
107994 pIdx=pIdx->pNext
107996 if( !pIdx ){
107997 sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
107998 pParse->checkSchema = 1;
107999 return SQLITE_ERROR;
108001 pFrom->pIndex = pIdx;
108003 return SQLITE_OK;
108006 ** Detect compound SELECT statements that use an ORDER BY clause with
108007 ** an alternative collating sequence.
108009 ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
108011 ** These are rewritten as a subquery:
108013 ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
108014 ** ORDER BY ... COLLATE ...
108016 ** This transformation is necessary because the multiSelectOrderBy() routine
108017 ** above that generates the code for a compound SELECT with an ORDER BY clause
108018 ** uses a merge algorithm that requires the same collating sequence on the
108019 ** result columns as on the ORDER BY clause. See ticket
108020 ** http://www.sqlite.org/src/info/6709574d2a
108022 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
108023 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
108024 ** there are COLLATE terms in the ORDER BY.
108026 static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
108027 int i;
108028 Select *pNew;
108029 Select *pX;
108030 sqlite3 *db;
108031 struct ExprList_item *a;
108032 SrcList *pNewSrc;
108033 Parse *pParse;
108034 Token dummy;
108036 if( p->pPrior==0 ) return WRC_Continue;
108037 if( p->pOrderBy==0 ) return WRC_Continue;
108038 for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
108039 if( pX==0 ) return WRC_Continue;
108040 a = p->pOrderBy->a;
108041 for(i=p->pOrderBy->nExpr-1; i>=0; i--){
108042 if( a[i].pExpr->flags & EP_Collate ) break;
108044 if( i<0 ) return WRC_Continue;
108046 /* If we reach this point, that means the transformation is required. */
108048 pParse = pWalker->pParse;
108049 db = pParse->db;
108050 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
108051 if( pNew==0 ) return WRC_Abort;
108052 memset(&dummy, 0, sizeof(dummy));
108053 pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
108054 if( pNewSrc==0 ) return WRC_Abort;
108055 *pNew = *p;
108056 p->pSrc = pNewSrc;
108057 p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
108058 p->op = TK_SELECT;
108059 p->pWhere = 0;
108060 pNew->pGroupBy = 0;
108061 pNew->pHaving = 0;
108062 pNew->pOrderBy = 0;
108063 p->pPrior = 0;
108064 p->pNext = 0;
108065 p->selFlags &= ~SF_Compound;
108066 assert( pNew->pPrior!=0 );
108067 pNew->pPrior->pNext = pNew;
108068 pNew->pLimit = 0;
108069 pNew->pOffset = 0;
108070 return WRC_Continue;
108073 #ifndef SQLITE_OMIT_CTE
108075 ** Argument pWith (which may be NULL) points to a linked list of nested
108076 ** WITH contexts, from inner to outermost. If the table identified by
108077 ** FROM clause element pItem is really a common-table-expression (CTE)
108078 ** then return a pointer to the CTE definition for that table. Otherwise
108079 ** return NULL.
108081 ** If a non-NULL value is returned, set *ppContext to point to the With
108082 ** object that the returned CTE belongs to.
108084 static struct Cte *searchWith(
108085 With *pWith, /* Current outermost WITH clause */
108086 struct SrcList_item *pItem, /* FROM clause element to resolve */
108087 With **ppContext /* OUT: WITH clause return value belongs to */
108089 const char *zName;
108090 if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
108091 With *p;
108092 for(p=pWith; p; p=p->pOuter){
108093 int i;
108094 for(i=0; i<p->nCte; i++){
108095 if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
108096 *ppContext = p;
108097 return &p->a[i];
108102 return 0;
108105 /* The code generator maintains a stack of active WITH clauses
108106 ** with the inner-most WITH clause being at the top of the stack.
108108 ** This routine pushes the WITH clause passed as the second argument
108109 ** onto the top of the stack. If argument bFree is true, then this
108110 ** WITH clause will never be popped from the stack. In this case it
108111 ** should be freed along with the Parse object. In other cases, when
108112 ** bFree==0, the With object will be freed along with the SELECT
108113 ** statement with which it is associated.
108115 SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
108116 assert( bFree==0 || pParse->pWith==0 );
108117 if( pWith ){
108118 pWith->pOuter = pParse->pWith;
108119 pParse->pWith = pWith;
108120 pParse->bFreeWith = bFree;
108125 ** This function checks if argument pFrom refers to a CTE declared by
108126 ** a WITH clause on the stack currently maintained by the parser. And,
108127 ** if currently processing a CTE expression, if it is a recursive
108128 ** reference to the current CTE.
108130 ** If pFrom falls into either of the two categories above, pFrom->pTab
108131 ** and other fields are populated accordingly. The caller should check
108132 ** (pFrom->pTab!=0) to determine whether or not a successful match
108133 ** was found.
108135 ** Whether or not a match is found, SQLITE_OK is returned if no error
108136 ** occurs. If an error does occur, an error message is stored in the
108137 ** parser and some error code other than SQLITE_OK returned.
108139 static int withExpand(
108140 Walker *pWalker,
108141 struct SrcList_item *pFrom
108143 Parse *pParse = pWalker->pParse;
108144 sqlite3 *db = pParse->db;
108145 struct Cte *pCte; /* Matched CTE (or NULL if no match) */
108146 With *pWith; /* WITH clause that pCte belongs to */
108148 assert( pFrom->pTab==0 );
108150 pCte = searchWith(pParse->pWith, pFrom, &pWith);
108151 if( pCte ){
108152 Table *pTab;
108153 ExprList *pEList;
108154 Select *pSel;
108155 Select *pLeft; /* Left-most SELECT statement */
108156 int bMayRecursive; /* True if compound joined by UNION [ALL] */
108157 With *pSavedWith; /* Initial value of pParse->pWith */
108159 /* If pCte->zErr is non-NULL at this point, then this is an illegal
108160 ** recursive reference to CTE pCte. Leave an error in pParse and return
108161 ** early. If pCte->zErr is NULL, then this is not a recursive reference.
108162 ** In this case, proceed. */
108163 if( pCte->zErr ){
108164 sqlite3ErrorMsg(pParse, pCte->zErr, pCte->zName);
108165 return SQLITE_ERROR;
108168 assert( pFrom->pTab==0 );
108169 pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
108170 if( pTab==0 ) return WRC_Abort;
108171 pTab->nRef = 1;
108172 pTab->zName = sqlite3DbStrDup(db, pCte->zName);
108173 pTab->iPKey = -1;
108174 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
108175 pTab->tabFlags |= TF_Ephemeral;
108176 pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
108177 if( db->mallocFailed ) return SQLITE_NOMEM;
108178 assert( pFrom->pSelect );
108180 /* Check if this is a recursive CTE. */
108181 pSel = pFrom->pSelect;
108182 bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
108183 if( bMayRecursive ){
108184 int i;
108185 SrcList *pSrc = pFrom->pSelect->pSrc;
108186 for(i=0; i<pSrc->nSrc; i++){
108187 struct SrcList_item *pItem = &pSrc->a[i];
108188 if( pItem->zDatabase==0
108189 && pItem->zName!=0
108190 && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
108192 pItem->pTab = pTab;
108193 pItem->isRecursive = 1;
108194 pTab->nRef++;
108195 pSel->selFlags |= SF_Recursive;
108200 /* Only one recursive reference is permitted. */
108201 if( pTab->nRef>2 ){
108202 sqlite3ErrorMsg(
108203 pParse, "multiple references to recursive table: %s", pCte->zName
108205 return SQLITE_ERROR;
108207 assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
108209 pCte->zErr = "circular reference: %s";
108210 pSavedWith = pParse->pWith;
108211 pParse->pWith = pWith;
108212 sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
108214 for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
108215 pEList = pLeft->pEList;
108216 if( pCte->pCols ){
108217 if( pEList->nExpr!=pCte->pCols->nExpr ){
108218 sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
108219 pCte->zName, pEList->nExpr, pCte->pCols->nExpr
108221 pParse->pWith = pSavedWith;
108222 return SQLITE_ERROR;
108224 pEList = pCte->pCols;
108227 selectColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
108228 if( bMayRecursive ){
108229 if( pSel->selFlags & SF_Recursive ){
108230 pCte->zErr = "multiple recursive references: %s";
108231 }else{
108232 pCte->zErr = "recursive reference in a subquery: %s";
108234 sqlite3WalkSelect(pWalker, pSel);
108236 pCte->zErr = 0;
108237 pParse->pWith = pSavedWith;
108240 return SQLITE_OK;
108242 #endif
108244 #ifndef SQLITE_OMIT_CTE
108246 ** If the SELECT passed as the second argument has an associated WITH
108247 ** clause, pop it from the stack stored as part of the Parse object.
108249 ** This function is used as the xSelectCallback2() callback by
108250 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
108251 ** names and other FROM clause elements.
108253 static void selectPopWith(Walker *pWalker, Select *p){
108254 Parse *pParse = pWalker->pParse;
108255 With *pWith = findRightmost(p)->pWith;
108256 if( pWith!=0 ){
108257 assert( pParse->pWith==pWith );
108258 pParse->pWith = pWith->pOuter;
108261 #else
108262 #define selectPopWith 0
108263 #endif
108266 ** This routine is a Walker callback for "expanding" a SELECT statement.
108267 ** "Expanding" means to do the following:
108269 ** (1) Make sure VDBE cursor numbers have been assigned to every
108270 ** element of the FROM clause.
108272 ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
108273 ** defines FROM clause. When views appear in the FROM clause,
108274 ** fill pTabList->a[].pSelect with a copy of the SELECT statement
108275 ** that implements the view. A copy is made of the view's SELECT
108276 ** statement so that we can freely modify or delete that statement
108277 ** without worrying about messing up the persistent representation
108278 ** of the view.
108280 ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
108281 ** on joins and the ON and USING clause of joins.
108283 ** (4) Scan the list of columns in the result set (pEList) looking
108284 ** for instances of the "*" operator or the TABLE.* operator.
108285 ** If found, expand each "*" to be every column in every table
108286 ** and TABLE.* to be every column in TABLE.
108289 static int selectExpander(Walker *pWalker, Select *p){
108290 Parse *pParse = pWalker->pParse;
108291 int i, j, k;
108292 SrcList *pTabList;
108293 ExprList *pEList;
108294 struct SrcList_item *pFrom;
108295 sqlite3 *db = pParse->db;
108296 Expr *pE, *pRight, *pExpr;
108297 u16 selFlags = p->selFlags;
108299 p->selFlags |= SF_Expanded;
108300 if( db->mallocFailed ){
108301 return WRC_Abort;
108303 if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
108304 return WRC_Prune;
108306 pTabList = p->pSrc;
108307 pEList = p->pEList;
108308 sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
108310 /* Make sure cursor numbers have been assigned to all entries in
108311 ** the FROM clause of the SELECT statement.
108313 sqlite3SrcListAssignCursors(pParse, pTabList);
108315 /* Look up every table named in the FROM clause of the select. If
108316 ** an entry of the FROM clause is a subquery instead of a table or view,
108317 ** then create a transient table structure to describe the subquery.
108319 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
108320 Table *pTab;
108321 assert( pFrom->isRecursive==0 || pFrom->pTab );
108322 if( pFrom->isRecursive ) continue;
108323 if( pFrom->pTab!=0 ){
108324 /* This statement has already been prepared. There is no need
108325 ** to go further. */
108326 assert( i==0 );
108327 #ifndef SQLITE_OMIT_CTE
108328 selectPopWith(pWalker, p);
108329 #endif
108330 return WRC_Prune;
108332 #ifndef SQLITE_OMIT_CTE
108333 if( withExpand(pWalker, pFrom) ) return WRC_Abort;
108334 if( pFrom->pTab ) {} else
108335 #endif
108336 if( pFrom->zName==0 ){
108337 #ifndef SQLITE_OMIT_SUBQUERY
108338 Select *pSel = pFrom->pSelect;
108339 /* A sub-query in the FROM clause of a SELECT */
108340 assert( pSel!=0 );
108341 assert( pFrom->pTab==0 );
108342 sqlite3WalkSelect(pWalker, pSel);
108343 pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
108344 if( pTab==0 ) return WRC_Abort;
108345 pTab->nRef = 1;
108346 pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
108347 while( pSel->pPrior ){ pSel = pSel->pPrior; }
108348 selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
108349 pTab->iPKey = -1;
108350 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
108351 pTab->tabFlags |= TF_Ephemeral;
108352 #endif
108353 }else{
108354 /* An ordinary table or view name in the FROM clause */
108355 assert( pFrom->pTab==0 );
108356 pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
108357 if( pTab==0 ) return WRC_Abort;
108358 if( pTab->nRef==0xffff ){
108359 sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
108360 pTab->zName);
108361 pFrom->pTab = 0;
108362 return WRC_Abort;
108364 pTab->nRef++;
108365 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
108366 if( pTab->pSelect || IsVirtual(pTab) ){
108367 /* We reach here if the named table is a really a view */
108368 if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
108369 assert( pFrom->pSelect==0 );
108370 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
108371 sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
108372 sqlite3WalkSelect(pWalker, pFrom->pSelect);
108374 #endif
108377 /* Locate the index named by the INDEXED BY clause, if any. */
108378 if( sqlite3IndexedByLookup(pParse, pFrom) ){
108379 return WRC_Abort;
108383 /* Process NATURAL keywords, and ON and USING clauses of joins.
108385 if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
108386 return WRC_Abort;
108389 /* For every "*" that occurs in the column list, insert the names of
108390 ** all columns in all tables. And for every TABLE.* insert the names
108391 ** of all columns in TABLE. The parser inserted a special expression
108392 ** with the TK_ALL operator for each "*" that it found in the column list.
108393 ** The following code just has to locate the TK_ALL expressions and expand
108394 ** each one to the list of all columns in all tables.
108396 ** The first loop just checks to see if there are any "*" operators
108397 ** that need expanding.
108399 for(k=0; k<pEList->nExpr; k++){
108400 pE = pEList->a[k].pExpr;
108401 if( pE->op==TK_ALL ) break;
108402 assert( pE->op!=TK_DOT || pE->pRight!=0 );
108403 assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
108404 if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
108406 if( k<pEList->nExpr ){
108408 ** If we get here it means the result set contains one or more "*"
108409 ** operators that need to be expanded. Loop through each expression
108410 ** in the result set and expand them one by one.
108412 struct ExprList_item *a = pEList->a;
108413 ExprList *pNew = 0;
108414 int flags = pParse->db->flags;
108415 int longNames = (flags & SQLITE_FullColNames)!=0
108416 && (flags & SQLITE_ShortColNames)==0;
108418 /* When processing FROM-clause subqueries, it is always the case
108419 ** that full_column_names=OFF and short_column_names=ON. The
108420 ** sqlite3ResultSetOfSelect() routine makes it so. */
108421 assert( (p->selFlags & SF_NestedFrom)==0
108422 || ((flags & SQLITE_FullColNames)==0 &&
108423 (flags & SQLITE_ShortColNames)!=0) );
108425 for(k=0; k<pEList->nExpr; k++){
108426 pE = a[k].pExpr;
108427 pRight = pE->pRight;
108428 assert( pE->op!=TK_DOT || pRight!=0 );
108429 if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
108430 /* This particular expression does not need to be expanded.
108432 pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
108433 if( pNew ){
108434 pNew->a[pNew->nExpr-1].zName = a[k].zName;
108435 pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
108436 a[k].zName = 0;
108437 a[k].zSpan = 0;
108439 a[k].pExpr = 0;
108440 }else{
108441 /* This expression is a "*" or a "TABLE.*" and needs to be
108442 ** expanded. */
108443 int tableSeen = 0; /* Set to 1 when TABLE matches */
108444 char *zTName = 0; /* text of name of TABLE */
108445 if( pE->op==TK_DOT ){
108446 assert( pE->pLeft!=0 );
108447 assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
108448 zTName = pE->pLeft->u.zToken;
108450 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
108451 Table *pTab = pFrom->pTab;
108452 Select *pSub = pFrom->pSelect;
108453 char *zTabName = pFrom->zAlias;
108454 const char *zSchemaName = 0;
108455 int iDb;
108456 if( zTabName==0 ){
108457 zTabName = pTab->zName;
108459 if( db->mallocFailed ) break;
108460 if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
108461 pSub = 0;
108462 if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
108463 continue;
108465 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
108466 zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
108468 for(j=0; j<pTab->nCol; j++){
108469 char *zName = pTab->aCol[j].zName;
108470 char *zColname; /* The computed column name */
108471 char *zToFree; /* Malloced string that needs to be freed */
108472 Token sColname; /* Computed column name as a token */
108474 assert( zName );
108475 if( zTName && pSub
108476 && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
108478 continue;
108481 /* If a column is marked as 'hidden' (currently only possible
108482 ** for virtual tables), do not include it in the expanded
108483 ** result-set list.
108485 if( IsHiddenColumn(&pTab->aCol[j]) ){
108486 assert(IsVirtual(pTab));
108487 continue;
108489 tableSeen = 1;
108491 if( i>0 && zTName==0 ){
108492 if( (pFrom->jointype & JT_NATURAL)!=0
108493 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
108495 /* In a NATURAL join, omit the join columns from the
108496 ** table to the right of the join */
108497 continue;
108499 if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
108500 /* In a join with a USING clause, omit columns in the
108501 ** using clause from the table on the right. */
108502 continue;
108505 pRight = sqlite3Expr(db, TK_ID, zName);
108506 zColname = zName;
108507 zToFree = 0;
108508 if( longNames || pTabList->nSrc>1 ){
108509 Expr *pLeft;
108510 pLeft = sqlite3Expr(db, TK_ID, zTabName);
108511 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
108512 if( zSchemaName ){
108513 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
108514 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
108516 if( longNames ){
108517 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
108518 zToFree = zColname;
108520 }else{
108521 pExpr = pRight;
108523 pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
108524 sColname.z = zColname;
108525 sColname.n = sqlite3Strlen30(zColname);
108526 sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
108527 if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
108528 struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
108529 if( pSub ){
108530 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
108531 testcase( pX->zSpan==0 );
108532 }else{
108533 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
108534 zSchemaName, zTabName, zColname);
108535 testcase( pX->zSpan==0 );
108537 pX->bSpanIsTab = 1;
108539 sqlite3DbFree(db, zToFree);
108542 if( !tableSeen ){
108543 if( zTName ){
108544 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
108545 }else{
108546 sqlite3ErrorMsg(pParse, "no tables specified");
108551 sqlite3ExprListDelete(db, pEList);
108552 p->pEList = pNew;
108554 #if SQLITE_MAX_COLUMN
108555 if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
108556 sqlite3ErrorMsg(pParse, "too many columns in result set");
108558 #endif
108559 return WRC_Continue;
108563 ** No-op routine for the parse-tree walker.
108565 ** When this routine is the Walker.xExprCallback then expression trees
108566 ** are walked without any actions being taken at each node. Presumably,
108567 ** when this routine is used for Walker.xExprCallback then
108568 ** Walker.xSelectCallback is set to do something useful for every
108569 ** subquery in the parser tree.
108571 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
108572 UNUSED_PARAMETER2(NotUsed, NotUsed2);
108573 return WRC_Continue;
108577 ** This routine "expands" a SELECT statement and all of its subqueries.
108578 ** For additional information on what it means to "expand" a SELECT
108579 ** statement, see the comment on the selectExpand worker callback above.
108581 ** Expanding a SELECT statement is the first step in processing a
108582 ** SELECT statement. The SELECT statement must be expanded before
108583 ** name resolution is performed.
108585 ** If anything goes wrong, an error message is written into pParse.
108586 ** The calling function can detect the problem by looking at pParse->nErr
108587 ** and/or pParse->db->mallocFailed.
108589 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
108590 Walker w;
108591 memset(&w, 0, sizeof(w));
108592 w.xExprCallback = exprWalkNoop;
108593 w.pParse = pParse;
108594 if( pParse->hasCompound ){
108595 w.xSelectCallback = convertCompoundSelectToSubquery;
108596 sqlite3WalkSelect(&w, pSelect);
108598 w.xSelectCallback = selectExpander;
108599 w.xSelectCallback2 = selectPopWith;
108600 sqlite3WalkSelect(&w, pSelect);
108604 #ifndef SQLITE_OMIT_SUBQUERY
108606 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
108607 ** interface.
108609 ** For each FROM-clause subquery, add Column.zType and Column.zColl
108610 ** information to the Table structure that represents the result set
108611 ** of that subquery.
108613 ** The Table structure that represents the result set was constructed
108614 ** by selectExpander() but the type and collation information was omitted
108615 ** at that point because identifiers had not yet been resolved. This
108616 ** routine is called after identifier resolution.
108618 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
108619 Parse *pParse;
108620 int i;
108621 SrcList *pTabList;
108622 struct SrcList_item *pFrom;
108624 assert( p->selFlags & SF_Resolved );
108625 if( (p->selFlags & SF_HasTypeInfo)==0 ){
108626 p->selFlags |= SF_HasTypeInfo;
108627 pParse = pWalker->pParse;
108628 pTabList = p->pSrc;
108629 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
108630 Table *pTab = pFrom->pTab;
108631 if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
108632 /* A sub-query in the FROM clause of a SELECT */
108633 Select *pSel = pFrom->pSelect;
108634 if( pSel ){
108635 while( pSel->pPrior ) pSel = pSel->pPrior;
108636 selectAddColumnTypeAndCollation(pParse, pTab, pSel);
108642 #endif
108646 ** This routine adds datatype and collating sequence information to
108647 ** the Table structures of all FROM-clause subqueries in a
108648 ** SELECT statement.
108650 ** Use this routine after name resolution.
108652 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
108653 #ifndef SQLITE_OMIT_SUBQUERY
108654 Walker w;
108655 memset(&w, 0, sizeof(w));
108656 w.xSelectCallback2 = selectAddSubqueryTypeInfo;
108657 w.xExprCallback = exprWalkNoop;
108658 w.pParse = pParse;
108659 sqlite3WalkSelect(&w, pSelect);
108660 #endif
108665 ** This routine sets up a SELECT statement for processing. The
108666 ** following is accomplished:
108668 ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
108669 ** * Ephemeral Table objects are created for all FROM-clause subqueries.
108670 ** * ON and USING clauses are shifted into WHERE statements
108671 ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
108672 ** * Identifiers in expression are matched to tables.
108674 ** This routine acts recursively on all subqueries within the SELECT.
108676 SQLITE_PRIVATE void sqlite3SelectPrep(
108677 Parse *pParse, /* The parser context */
108678 Select *p, /* The SELECT statement being coded. */
108679 NameContext *pOuterNC /* Name context for container */
108681 sqlite3 *db;
108682 if( NEVER(p==0) ) return;
108683 db = pParse->db;
108684 if( db->mallocFailed ) return;
108685 if( p->selFlags & SF_HasTypeInfo ) return;
108686 sqlite3SelectExpand(pParse, p);
108687 if( pParse->nErr || db->mallocFailed ) return;
108688 sqlite3ResolveSelectNames(pParse, p, pOuterNC);
108689 if( pParse->nErr || db->mallocFailed ) return;
108690 sqlite3SelectAddTypeInfo(pParse, p);
108694 ** Reset the aggregate accumulator.
108696 ** The aggregate accumulator is a set of memory cells that hold
108697 ** intermediate results while calculating an aggregate. This
108698 ** routine generates code that stores NULLs in all of those memory
108699 ** cells.
108701 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
108702 Vdbe *v = pParse->pVdbe;
108703 int i;
108704 struct AggInfo_func *pFunc;
108705 int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
108706 if( nReg==0 ) return;
108707 #ifdef SQLITE_DEBUG
108708 /* Verify that all AggInfo registers are within the range specified by
108709 ** AggInfo.mnReg..AggInfo.mxReg */
108710 assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
108711 for(i=0; i<pAggInfo->nColumn; i++){
108712 assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
108713 && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
108715 for(i=0; i<pAggInfo->nFunc; i++){
108716 assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
108717 && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
108719 #endif
108720 sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
108721 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
108722 if( pFunc->iDistinct>=0 ){
108723 Expr *pE = pFunc->pExpr;
108724 assert( !ExprHasProperty(pE, EP_xIsSelect) );
108725 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
108726 sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
108727 "argument");
108728 pFunc->iDistinct = -1;
108729 }else{
108730 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
108731 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
108732 (char*)pKeyInfo, P4_KEYINFO);
108739 ** Invoke the OP_AggFinalize opcode for every aggregate function
108740 ** in the AggInfo structure.
108742 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
108743 Vdbe *v = pParse->pVdbe;
108744 int i;
108745 struct AggInfo_func *pF;
108746 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
108747 ExprList *pList = pF->pExpr->x.pList;
108748 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
108749 sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
108750 (void*)pF->pFunc, P4_FUNCDEF);
108755 ** Update the accumulator memory cells for an aggregate based on
108756 ** the current cursor position.
108758 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
108759 Vdbe *v = pParse->pVdbe;
108760 int i;
108761 int regHit = 0;
108762 int addrHitTest = 0;
108763 struct AggInfo_func *pF;
108764 struct AggInfo_col *pC;
108766 pAggInfo->directMode = 1;
108767 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
108768 int nArg;
108769 int addrNext = 0;
108770 int regAgg;
108771 ExprList *pList = pF->pExpr->x.pList;
108772 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
108773 if( pList ){
108774 nArg = pList->nExpr;
108775 regAgg = sqlite3GetTempRange(pParse, nArg);
108776 sqlite3ExprCodeExprList(pParse, pList, regAgg, SQLITE_ECEL_DUP);
108777 }else{
108778 nArg = 0;
108779 regAgg = 0;
108781 if( pF->iDistinct>=0 ){
108782 addrNext = sqlite3VdbeMakeLabel(v);
108783 assert( nArg==1 );
108784 codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
108786 if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
108787 CollSeq *pColl = 0;
108788 struct ExprList_item *pItem;
108789 int j;
108790 assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
108791 for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
108792 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
108794 if( !pColl ){
108795 pColl = pParse->db->pDfltColl;
108797 if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
108798 sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
108800 sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
108801 (void*)pF->pFunc, P4_FUNCDEF);
108802 sqlite3VdbeChangeP5(v, (u8)nArg);
108803 sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
108804 sqlite3ReleaseTempRange(pParse, regAgg, nArg);
108805 if( addrNext ){
108806 sqlite3VdbeResolveLabel(v, addrNext);
108807 sqlite3ExprCacheClear(pParse);
108811 /* Before populating the accumulator registers, clear the column cache.
108812 ** Otherwise, if any of the required column values are already present
108813 ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
108814 ** to pC->iMem. But by the time the value is used, the original register
108815 ** may have been used, invalidating the underlying buffer holding the
108816 ** text or blob value. See ticket [883034dcb5].
108818 ** Another solution would be to change the OP_SCopy used to copy cached
108819 ** values to an OP_Copy.
108821 if( regHit ){
108822 addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
108824 sqlite3ExprCacheClear(pParse);
108825 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
108826 sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
108828 pAggInfo->directMode = 0;
108829 sqlite3ExprCacheClear(pParse);
108830 if( addrHitTest ){
108831 sqlite3VdbeJumpHere(v, addrHitTest);
108836 ** Add a single OP_Explain instruction to the VDBE to explain a simple
108837 ** count(*) query ("SELECT count(*) FROM pTab").
108839 #ifndef SQLITE_OMIT_EXPLAIN
108840 static void explainSimpleCount(
108841 Parse *pParse, /* Parse context */
108842 Table *pTab, /* Table being queried */
108843 Index *pIdx /* Index used to optimize scan, or NULL */
108845 if( pParse->explain==2 ){
108846 int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
108847 char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
108848 pTab->zName,
108849 bCover ? " USING COVERING INDEX " : "",
108850 bCover ? pIdx->zName : ""
108852 sqlite3VdbeAddOp4(
108853 pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
108857 #else
108858 # define explainSimpleCount(a,b,c)
108859 #endif
108862 ** Generate code for the SELECT statement given in the p argument.
108864 ** The results are returned according to the SelectDest structure.
108865 ** See comments in sqliteInt.h for further information.
108867 ** This routine returns the number of errors. If any errors are
108868 ** encountered, then an appropriate error message is left in
108869 ** pParse->zErrMsg.
108871 ** This routine does NOT free the Select structure passed in. The
108872 ** calling function needs to do that.
108874 SQLITE_PRIVATE int sqlite3Select(
108875 Parse *pParse, /* The parser context */
108876 Select *p, /* The SELECT statement being coded. */
108877 SelectDest *pDest /* What to do with the query results */
108879 int i, j; /* Loop counters */
108880 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
108881 Vdbe *v; /* The virtual machine under construction */
108882 int isAgg; /* True for select lists like "count(*)" */
108883 ExprList *pEList; /* List of columns to extract. */
108884 SrcList *pTabList; /* List of tables to select from */
108885 Expr *pWhere; /* The WHERE clause. May be NULL */
108886 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
108887 Expr *pHaving; /* The HAVING clause. May be NULL */
108888 int rc = 1; /* Value to return from this function */
108889 DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
108890 SortCtx sSort; /* Info on how to code the ORDER BY clause */
108891 AggInfo sAggInfo; /* Information used by aggregate queries */
108892 int iEnd; /* Address of the end of the query */
108893 sqlite3 *db; /* The database connection */
108895 #ifndef SQLITE_OMIT_EXPLAIN
108896 int iRestoreSelectId = pParse->iSelectId;
108897 pParse->iSelectId = pParse->iNextSelectId++;
108898 #endif
108900 db = pParse->db;
108901 if( p==0 || db->mallocFailed || pParse->nErr ){
108902 return 1;
108904 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
108905 memset(&sAggInfo, 0, sizeof(sAggInfo));
108906 #if SELECTTRACE_ENABLED
108907 pParse->nSelectIndent++;
108908 SELECTTRACE(1,pParse,p, ("begin processing:\n"));
108909 if( sqlite3SelectTrace & 0x100 ){
108910 sqlite3TreeViewSelect(0, p, 0);
108912 #endif
108914 assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
108915 assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
108916 assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
108917 assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
108918 if( IgnorableOrderby(pDest) ){
108919 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
108920 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
108921 pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
108922 pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
108923 /* If ORDER BY makes no difference in the output then neither does
108924 ** DISTINCT so it can be removed too. */
108925 sqlite3ExprListDelete(db, p->pOrderBy);
108926 p->pOrderBy = 0;
108927 p->selFlags &= ~SF_Distinct;
108929 sqlite3SelectPrep(pParse, p, 0);
108930 memset(&sSort, 0, sizeof(sSort));
108931 sSort.pOrderBy = p->pOrderBy;
108932 pTabList = p->pSrc;
108933 pEList = p->pEList;
108934 if( pParse->nErr || db->mallocFailed ){
108935 goto select_end;
108937 isAgg = (p->selFlags & SF_Aggregate)!=0;
108938 assert( pEList!=0 );
108940 /* Begin generating code.
108942 v = sqlite3GetVdbe(pParse);
108943 if( v==0 ) goto select_end;
108945 /* If writing to memory or generating a set
108946 ** only a single column may be output.
108948 #ifndef SQLITE_OMIT_SUBQUERY
108949 if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
108950 goto select_end;
108952 #endif
108954 /* Generate code for all sub-queries in the FROM clause
108956 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
108957 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
108958 struct SrcList_item *pItem = &pTabList->a[i];
108959 SelectDest dest;
108960 Select *pSub = pItem->pSelect;
108961 int isAggSub;
108963 if( pSub==0 ) continue;
108965 /* Sometimes the code for a subquery will be generated more than
108966 ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
108967 ** for example. In that case, do not regenerate the code to manifest
108968 ** a view or the co-routine to implement a view. The first instance
108969 ** is sufficient, though the subroutine to manifest the view does need
108970 ** to be invoked again. */
108971 if( pItem->addrFillSub ){
108972 if( pItem->viaCoroutine==0 ){
108973 sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
108975 continue;
108978 /* Increment Parse.nHeight by the height of the largest expression
108979 ** tree referred to by this, the parent select. The child select
108980 ** may contain expression trees of at most
108981 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
108982 ** more conservative than necessary, but much easier than enforcing
108983 ** an exact limit.
108985 pParse->nHeight += sqlite3SelectExprHeight(p);
108987 isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
108988 if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
108989 /* This subquery can be absorbed into its parent. */
108990 if( isAggSub ){
108991 isAgg = 1;
108992 p->selFlags |= SF_Aggregate;
108994 i = -1;
108995 }else if( pTabList->nSrc==1
108996 && OptimizationEnabled(db, SQLITE_SubqCoroutine)
108998 /* Implement a co-routine that will return a single row of the result
108999 ** set on each invocation.
109001 int addrTop = sqlite3VdbeCurrentAddr(v)+1;
109002 pItem->regReturn = ++pParse->nMem;
109003 sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
109004 VdbeComment((v, "%s", pItem->pTab->zName));
109005 pItem->addrFillSub = addrTop;
109006 sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
109007 explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
109008 sqlite3Select(pParse, pSub, &dest);
109009 pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
109010 pItem->viaCoroutine = 1;
109011 pItem->regResult = dest.iSdst;
109012 sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
109013 sqlite3VdbeJumpHere(v, addrTop-1);
109014 sqlite3ClearTempRegCache(pParse);
109015 }else{
109016 /* Generate a subroutine that will fill an ephemeral table with
109017 ** the content of this subquery. pItem->addrFillSub will point
109018 ** to the address of the generated subroutine. pItem->regReturn
109019 ** is a register allocated to hold the subroutine return address
109021 int topAddr;
109022 int onceAddr = 0;
109023 int retAddr;
109024 assert( pItem->addrFillSub==0 );
109025 pItem->regReturn = ++pParse->nMem;
109026 topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
109027 pItem->addrFillSub = topAddr+1;
109028 if( pItem->isCorrelated==0 ){
109029 /* If the subquery is not correlated and if we are not inside of
109030 ** a trigger, then we only need to compute the value of the subquery
109031 ** once. */
109032 onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
109033 VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
109034 }else{
109035 VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
109037 sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
109038 explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
109039 sqlite3Select(pParse, pSub, &dest);
109040 pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
109041 if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
109042 retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
109043 VdbeComment((v, "end %s", pItem->pTab->zName));
109044 sqlite3VdbeChangeP1(v, topAddr, retAddr);
109045 sqlite3ClearTempRegCache(pParse);
109047 if( /*pParse->nErr ||*/ db->mallocFailed ){
109048 goto select_end;
109050 pParse->nHeight -= sqlite3SelectExprHeight(p);
109051 pTabList = p->pSrc;
109052 if( !IgnorableOrderby(pDest) ){
109053 sSort.pOrderBy = p->pOrderBy;
109056 pEList = p->pEList;
109057 #endif
109058 pWhere = p->pWhere;
109059 pGroupBy = p->pGroupBy;
109060 pHaving = p->pHaving;
109061 sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
109063 #ifndef SQLITE_OMIT_COMPOUND_SELECT
109064 /* If there is are a sequence of queries, do the earlier ones first.
109066 if( p->pPrior ){
109067 rc = multiSelect(pParse, p, pDest);
109068 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
109069 #if SELECTTRACE_ENABLED
109070 SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
109071 pParse->nSelectIndent--;
109072 #endif
109073 return rc;
109075 #endif
109077 /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
109078 ** if the select-list is the same as the ORDER BY list, then this query
109079 ** can be rewritten as a GROUP BY. In other words, this:
109081 ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
109083 ** is transformed to:
109085 ** SELECT xyz FROM ... GROUP BY xyz
109087 ** The second form is preferred as a single index (or temp-table) may be
109088 ** used for both the ORDER BY and DISTINCT processing. As originally
109089 ** written the query must use a temp-table for at least one of the ORDER
109090 ** BY and DISTINCT, and an index or separate temp-table for the other.
109092 if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
109093 && sqlite3ExprListCompare(sSort.pOrderBy, p->pEList, -1)==0
109095 p->selFlags &= ~SF_Distinct;
109096 p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
109097 pGroupBy = p->pGroupBy;
109098 sSort.pOrderBy = 0;
109099 /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
109100 ** the sDistinct.isTnct is still set. Hence, isTnct represents the
109101 ** original setting of the SF_Distinct flag, not the current setting */
109102 assert( sDistinct.isTnct );
109105 /* If there is an ORDER BY clause, then this sorting
109106 ** index might end up being unused if the data can be
109107 ** extracted in pre-sorted order. If that is the case, then the
109108 ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
109109 ** we figure out that the sorting index is not needed. The addrSortIndex
109110 ** variable is used to facilitate that change.
109112 if( sSort.pOrderBy ){
109113 KeyInfo *pKeyInfo;
109114 pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, 0);
109115 sSort.iECursor = pParse->nTab++;
109116 sSort.addrSortIndex =
109117 sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
109118 sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
109119 (char*)pKeyInfo, P4_KEYINFO
109121 }else{
109122 sSort.addrSortIndex = -1;
109125 /* If the output is destined for a temporary table, open that table.
109127 if( pDest->eDest==SRT_EphemTab ){
109128 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
109131 /* Set the limiter.
109133 iEnd = sqlite3VdbeMakeLabel(v);
109134 p->nSelectRow = LARGEST_INT64;
109135 computeLimitRegisters(pParse, p, iEnd);
109136 if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
109137 sqlite3VdbeGetOp(v, sSort.addrSortIndex)->opcode = OP_SorterOpen;
109138 sSort.sortFlags |= SORTFLAG_UseSorter;
109141 /* Open a virtual index to use for the distinct set.
109143 if( p->selFlags & SF_Distinct ){
109144 sDistinct.tabTnct = pParse->nTab++;
109145 sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
109146 sDistinct.tabTnct, 0, 0,
109147 (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
109148 P4_KEYINFO);
109149 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
109150 sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
109151 }else{
109152 sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
109155 if( !isAgg && pGroupBy==0 ){
109156 /* No aggregate functions and no GROUP BY clause */
109157 u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
109159 /* Begin the database scan. */
109160 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
109161 p->pEList, wctrlFlags, 0);
109162 if( pWInfo==0 ) goto select_end;
109163 if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
109164 p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
109166 if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
109167 sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
109169 if( sSort.pOrderBy ){
109170 sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
109171 if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
109172 sSort.pOrderBy = 0;
109176 /* If sorting index that was created by a prior OP_OpenEphemeral
109177 ** instruction ended up not being needed, then change the OP_OpenEphemeral
109178 ** into an OP_Noop.
109180 if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
109181 sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
109184 /* Use the standard inner loop. */
109185 selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
109186 sqlite3WhereContinueLabel(pWInfo),
109187 sqlite3WhereBreakLabel(pWInfo));
109189 /* End the database scan loop.
109191 sqlite3WhereEnd(pWInfo);
109192 }else{
109193 /* This case when there exist aggregate functions or a GROUP BY clause
109194 ** or both */
109195 NameContext sNC; /* Name context for processing aggregate information */
109196 int iAMem; /* First Mem address for storing current GROUP BY */
109197 int iBMem; /* First Mem address for previous GROUP BY */
109198 int iUseFlag; /* Mem address holding flag indicating that at least
109199 ** one row of the input to the aggregator has been
109200 ** processed */
109201 int iAbortFlag; /* Mem address which causes query abort if positive */
109202 int groupBySort; /* Rows come from source in GROUP BY order */
109203 int addrEnd; /* End of processing for this SELECT */
109204 int sortPTab = 0; /* Pseudotable used to decode sorting results */
109205 int sortOut = 0; /* Output register from the sorter */
109206 int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
109208 /* Remove any and all aliases between the result set and the
109209 ** GROUP BY clause.
109211 if( pGroupBy ){
109212 int k; /* Loop counter */
109213 struct ExprList_item *pItem; /* For looping over expression in a list */
109215 for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
109216 pItem->u.x.iAlias = 0;
109218 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
109219 pItem->u.x.iAlias = 0;
109221 if( p->nSelectRow>100 ) p->nSelectRow = 100;
109222 }else{
109223 p->nSelectRow = 1;
109227 /* If there is both a GROUP BY and an ORDER BY clause and they are
109228 ** identical, then it may be possible to disable the ORDER BY clause
109229 ** on the grounds that the GROUP BY will cause elements to come out
109230 ** in the correct order. It also may not - the GROUP BY may use a
109231 ** database index that causes rows to be grouped together as required
109232 ** but not actually sorted. Either way, record the fact that the
109233 ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
109234 ** variable. */
109235 if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
109236 orderByGrp = 1;
109239 /* Create a label to jump to when we want to abort the query */
109240 addrEnd = sqlite3VdbeMakeLabel(v);
109242 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
109243 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
109244 ** SELECT statement.
109246 memset(&sNC, 0, sizeof(sNC));
109247 sNC.pParse = pParse;
109248 sNC.pSrcList = pTabList;
109249 sNC.pAggInfo = &sAggInfo;
109250 sAggInfo.mnReg = pParse->nMem+1;
109251 sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
109252 sAggInfo.pGroupBy = pGroupBy;
109253 sqlite3ExprAnalyzeAggList(&sNC, pEList);
109254 sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
109255 if( pHaving ){
109256 sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
109258 sAggInfo.nAccumulator = sAggInfo.nColumn;
109259 for(i=0; i<sAggInfo.nFunc; i++){
109260 assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
109261 sNC.ncFlags |= NC_InAggFunc;
109262 sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
109263 sNC.ncFlags &= ~NC_InAggFunc;
109265 sAggInfo.mxReg = pParse->nMem;
109266 if( db->mallocFailed ) goto select_end;
109268 /* Processing for aggregates with GROUP BY is very different and
109269 ** much more complex than aggregates without a GROUP BY.
109271 if( pGroupBy ){
109272 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
109273 int j1; /* A-vs-B comparision jump */
109274 int addrOutputRow; /* Start of subroutine that outputs a result row */
109275 int regOutputRow; /* Return address register for output subroutine */
109276 int addrSetAbort; /* Set the abort flag and return */
109277 int addrTopOfLoop; /* Top of the input loop */
109278 int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
109279 int addrReset; /* Subroutine for resetting the accumulator */
109280 int regReset; /* Return address register for reset subroutine */
109282 /* If there is a GROUP BY clause we might need a sorting index to
109283 ** implement it. Allocate that sorting index now. If it turns out
109284 ** that we do not need it after all, the OP_SorterOpen instruction
109285 ** will be converted into a Noop.
109287 sAggInfo.sortingIdx = pParse->nTab++;
109288 pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, 0);
109289 addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
109290 sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
109291 0, (char*)pKeyInfo, P4_KEYINFO);
109293 /* Initialize memory locations used by GROUP BY aggregate processing
109295 iUseFlag = ++pParse->nMem;
109296 iAbortFlag = ++pParse->nMem;
109297 regOutputRow = ++pParse->nMem;
109298 addrOutputRow = sqlite3VdbeMakeLabel(v);
109299 regReset = ++pParse->nMem;
109300 addrReset = sqlite3VdbeMakeLabel(v);
109301 iAMem = pParse->nMem + 1;
109302 pParse->nMem += pGroupBy->nExpr;
109303 iBMem = pParse->nMem + 1;
109304 pParse->nMem += pGroupBy->nExpr;
109305 sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
109306 VdbeComment((v, "clear abort flag"));
109307 sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
109308 VdbeComment((v, "indicate accumulator empty"));
109309 sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
109311 /* Begin a loop that will extract all source rows in GROUP BY order.
109312 ** This might involve two separate loops with an OP_Sort in between, or
109313 ** it might be a single loop that uses an index to extract information
109314 ** in the right order to begin with.
109316 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
109317 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
109318 WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
109320 if( pWInfo==0 ) goto select_end;
109321 if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
109322 /* The optimizer is able to deliver rows in group by order so
109323 ** we do not have to sort. The OP_OpenEphemeral table will be
109324 ** cancelled later because we still need to use the pKeyInfo
109326 groupBySort = 0;
109327 }else{
109328 /* Rows are coming out in undetermined order. We have to push
109329 ** each row into a sorting index, terminate the first loop,
109330 ** then loop over the sorting index in order to get the output
109331 ** in sorted order
109333 int regBase;
109334 int regRecord;
109335 int nCol;
109336 int nGroupBy;
109338 explainTempTable(pParse,
109339 (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
109340 "DISTINCT" : "GROUP BY");
109342 groupBySort = 1;
109343 nGroupBy = pGroupBy->nExpr;
109344 nCol = nGroupBy;
109345 j = nGroupBy;
109346 for(i=0; i<sAggInfo.nColumn; i++){
109347 if( sAggInfo.aCol[i].iSorterColumn>=j ){
109348 nCol++;
109352 regBase = sqlite3GetTempRange(pParse, nCol);
109353 sqlite3ExprCacheClear(pParse);
109354 sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
109355 j = nGroupBy;
109356 for(i=0; i<sAggInfo.nColumn; i++){
109357 struct AggInfo_col *pCol = &sAggInfo.aCol[i];
109358 if( pCol->iSorterColumn>=j ){
109359 int r1 = j + regBase;
109360 int r2;
109362 r2 = sqlite3ExprCodeGetColumn(pParse,
109363 pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
109364 if( r1!=r2 ){
109365 sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
109370 regRecord = sqlite3GetTempReg(pParse);
109371 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
109372 sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
109373 sqlite3ReleaseTempReg(pParse, regRecord);
109374 sqlite3ReleaseTempRange(pParse, regBase, nCol);
109375 sqlite3WhereEnd(pWInfo);
109376 sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
109377 sortOut = sqlite3GetTempReg(pParse);
109378 sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
109379 sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
109380 VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
109381 sAggInfo.useSortingIdx = 1;
109382 sqlite3ExprCacheClear(pParse);
109386 /* If the index or temporary table used by the GROUP BY sort
109387 ** will naturally deliver rows in the order required by the ORDER BY
109388 ** clause, cancel the ephemeral table open coded earlier.
109390 ** This is an optimization - the correct answer should result regardless.
109391 ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
109392 ** disable this optimization for testing purposes. */
109393 if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
109394 && (groupBySort || sqlite3WhereIsSorted(pWInfo))
109396 sSort.pOrderBy = 0;
109397 sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
109400 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
109401 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
109402 ** Then compare the current GROUP BY terms against the GROUP BY terms
109403 ** from the previous row currently stored in a0, a1, a2...
109405 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
109406 sqlite3ExprCacheClear(pParse);
109407 if( groupBySort ){
109408 sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, sortOut,sortPTab);
109410 for(j=0; j<pGroupBy->nExpr; j++){
109411 if( groupBySort ){
109412 sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
109413 }else{
109414 sAggInfo.directMode = 1;
109415 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
109418 sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
109419 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
109420 j1 = sqlite3VdbeCurrentAddr(v);
109421 sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); VdbeCoverage(v);
109423 /* Generate code that runs whenever the GROUP BY changes.
109424 ** Changes in the GROUP BY are detected by the previous code
109425 ** block. If there were no changes, this block is skipped.
109427 ** This code copies current group by terms in b0,b1,b2,...
109428 ** over to a0,a1,a2. It then calls the output subroutine
109429 ** and resets the aggregate accumulator registers in preparation
109430 ** for the next GROUP BY batch.
109432 sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
109433 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
109434 VdbeComment((v, "output one row"));
109435 sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
109436 VdbeComment((v, "check abort flag"));
109437 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
109438 VdbeComment((v, "reset accumulator"));
109440 /* Update the aggregate accumulators based on the content of
109441 ** the current row
109443 sqlite3VdbeJumpHere(v, j1);
109444 updateAccumulator(pParse, &sAggInfo);
109445 sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
109446 VdbeComment((v, "indicate data in accumulator"));
109448 /* End of the loop
109450 if( groupBySort ){
109451 sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
109452 VdbeCoverage(v);
109453 }else{
109454 sqlite3WhereEnd(pWInfo);
109455 sqlite3VdbeChangeToNoop(v, addrSortingIdx);
109458 /* Output the final row of result
109460 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
109461 VdbeComment((v, "output final row"));
109463 /* Jump over the subroutines
109465 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
109467 /* Generate a subroutine that outputs a single row of the result
109468 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
109469 ** is less than or equal to zero, the subroutine is a no-op. If
109470 ** the processing calls for the query to abort, this subroutine
109471 ** increments the iAbortFlag memory location before returning in
109472 ** order to signal the caller to abort.
109474 addrSetAbort = sqlite3VdbeCurrentAddr(v);
109475 sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
109476 VdbeComment((v, "set abort flag"));
109477 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
109478 sqlite3VdbeResolveLabel(v, addrOutputRow);
109479 addrOutputRow = sqlite3VdbeCurrentAddr(v);
109480 sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v);
109481 VdbeComment((v, "Groupby result generator entry point"));
109482 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
109483 finalizeAggFunctions(pParse, &sAggInfo);
109484 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
109485 selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
109486 &sDistinct, pDest,
109487 addrOutputRow+1, addrSetAbort);
109488 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
109489 VdbeComment((v, "end groupby result generator"));
109491 /* Generate a subroutine that will reset the group-by accumulator
109493 sqlite3VdbeResolveLabel(v, addrReset);
109494 resetAccumulator(pParse, &sAggInfo);
109495 sqlite3VdbeAddOp1(v, OP_Return, regReset);
109497 } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
109498 else {
109499 ExprList *pDel = 0;
109500 #ifndef SQLITE_OMIT_BTREECOUNT
109501 Table *pTab;
109502 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
109503 /* If isSimpleCount() returns a pointer to a Table structure, then
109504 ** the SQL statement is of the form:
109506 ** SELECT count(*) FROM <tbl>
109508 ** where the Table structure returned represents table <tbl>.
109510 ** This statement is so common that it is optimized specially. The
109511 ** OP_Count instruction is executed either on the intkey table that
109512 ** contains the data for table <tbl> or on one of its indexes. It
109513 ** is better to execute the op on an index, as indexes are almost
109514 ** always spread across less pages than their corresponding tables.
109516 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
109517 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
109518 Index *pIdx; /* Iterator variable */
109519 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
109520 Index *pBest = 0; /* Best index found so far */
109521 int iRoot = pTab->tnum; /* Root page of scanned b-tree */
109523 sqlite3CodeVerifySchema(pParse, iDb);
109524 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
109526 /* Search for the index that has the lowest scan cost.
109528 ** (2011-04-15) Do not do a full scan of an unordered index.
109530 ** (2013-10-03) Do not count the entries in a partial index.
109532 ** In practice the KeyInfo structure will not be used. It is only
109533 ** passed to keep OP_OpenRead happy.
109535 if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
109536 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
109537 if( pIdx->bUnordered==0
109538 && pIdx->szIdxRow<pTab->szTabRow
109539 && pIdx->pPartIdxWhere==0
109540 && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
109542 pBest = pIdx;
109545 if( pBest ){
109546 iRoot = pBest->tnum;
109547 pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
109550 /* Open a read-only cursor, execute the OP_Count, close the cursor. */
109551 sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
109552 if( pKeyInfo ){
109553 sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
109555 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
109556 sqlite3VdbeAddOp1(v, OP_Close, iCsr);
109557 explainSimpleCount(pParse, pTab, pBest);
109558 }else
109559 #endif /* SQLITE_OMIT_BTREECOUNT */
109561 /* Check if the query is of one of the following forms:
109563 ** SELECT min(x) FROM ...
109564 ** SELECT max(x) FROM ...
109566 ** If it is, then ask the code in where.c to attempt to sort results
109567 ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
109568 ** If where.c is able to produce results sorted in this order, then
109569 ** add vdbe code to break out of the processing loop after the
109570 ** first iteration (since the first iteration of the loop is
109571 ** guaranteed to operate on the row with the minimum or maximum
109572 ** value of x, the only row required).
109574 ** A special flag must be passed to sqlite3WhereBegin() to slightly
109575 ** modify behavior as follows:
109577 ** + If the query is a "SELECT min(x)", then the loop coded by
109578 ** where.c should not iterate over any values with a NULL value
109579 ** for x.
109581 ** + The optimizer code in where.c (the thing that decides which
109582 ** index or indices to use) should place a different priority on
109583 ** satisfying the 'ORDER BY' clause than it does in other cases.
109584 ** Refer to code and comments in where.c for details.
109586 ExprList *pMinMax = 0;
109587 u8 flag = WHERE_ORDERBY_NORMAL;
109589 assert( p->pGroupBy==0 );
109590 assert( flag==0 );
109591 if( p->pHaving==0 ){
109592 flag = minMaxQuery(&sAggInfo, &pMinMax);
109594 assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
109596 if( flag ){
109597 pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
109598 pDel = pMinMax;
109599 if( pMinMax && !db->mallocFailed ){
109600 pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
109601 pMinMax->a[0].pExpr->op = TK_COLUMN;
109605 /* This case runs if the aggregate has no GROUP BY clause. The
109606 ** processing is much simpler since there is only a single row
109607 ** of output.
109609 resetAccumulator(pParse, &sAggInfo);
109610 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
109611 if( pWInfo==0 ){
109612 sqlite3ExprListDelete(db, pDel);
109613 goto select_end;
109615 updateAccumulator(pParse, &sAggInfo);
109616 assert( pMinMax==0 || pMinMax->nExpr==1 );
109617 if( sqlite3WhereIsOrdered(pWInfo)>0 ){
109618 sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
109619 VdbeComment((v, "%s() by index",
109620 (flag==WHERE_ORDERBY_MIN?"min":"max")));
109622 sqlite3WhereEnd(pWInfo);
109623 finalizeAggFunctions(pParse, &sAggInfo);
109626 sSort.pOrderBy = 0;
109627 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
109628 selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
109629 pDest, addrEnd, addrEnd);
109630 sqlite3ExprListDelete(db, pDel);
109632 sqlite3VdbeResolveLabel(v, addrEnd);
109634 } /* endif aggregate query */
109636 if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
109637 explainTempTable(pParse, "DISTINCT");
109640 /* If there is an ORDER BY clause, then we need to sort the results
109641 ** and send them to the callback one by one.
109643 if( sSort.pOrderBy ){
109644 explainTempTable(pParse, sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
109645 generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
109648 /* Jump here to skip this query
109650 sqlite3VdbeResolveLabel(v, iEnd);
109652 /* The SELECT was successfully coded. Set the return code to 0
109653 ** to indicate no errors.
109655 rc = 0;
109657 /* Control jumps to here if an error is encountered above, or upon
109658 ** successful coding of the SELECT.
109660 select_end:
109661 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
109663 /* Identify column names if results of the SELECT are to be output.
109665 if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
109666 generateColumnNames(pParse, pTabList, pEList);
109669 sqlite3DbFree(db, sAggInfo.aCol);
109670 sqlite3DbFree(db, sAggInfo.aFunc);
109671 #if SELECTTRACE_ENABLED
109672 SELECTTRACE(1,pParse,p,("end processing\n"));
109673 pParse->nSelectIndent--;
109674 #endif
109675 return rc;
109678 #ifdef SQLITE_DEBUG
109680 ** Generate a human-readable description of a the Select object.
109682 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
109683 int n = 0;
109684 pView = sqlite3TreeViewPush(pView, moreToFollow);
109685 sqlite3TreeViewLine(pView, "SELECT%s%s",
109686 ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
109687 ((p->selFlags & SF_Aggregate) ? " agg_flag" : "")
109689 if( p->pSrc && p->pSrc->nSrc ) n++;
109690 if( p->pWhere ) n++;
109691 if( p->pGroupBy ) n++;
109692 if( p->pHaving ) n++;
109693 if( p->pOrderBy ) n++;
109694 if( p->pLimit ) n++;
109695 if( p->pOffset ) n++;
109696 if( p->pPrior ) n++;
109697 sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
109698 if( p->pSrc && p->pSrc->nSrc ){
109699 int i;
109700 pView = sqlite3TreeViewPush(pView, (n--)>0);
109701 sqlite3TreeViewLine(pView, "FROM");
109702 for(i=0; i<p->pSrc->nSrc; i++){
109703 struct SrcList_item *pItem = &p->pSrc->a[i];
109704 StrAccum x;
109705 char zLine[100];
109706 sqlite3StrAccumInit(&x, zLine, sizeof(zLine), 0);
109707 sqlite3XPrintf(&x, 0, "{%d,*}", pItem->iCursor);
109708 if( pItem->zDatabase ){
109709 sqlite3XPrintf(&x, 0, " %s.%s", pItem->zDatabase, pItem->zName);
109710 }else if( pItem->zName ){
109711 sqlite3XPrintf(&x, 0, " %s", pItem->zName);
109713 if( pItem->pTab ){
109714 sqlite3XPrintf(&x, 0, " tabname=%Q", pItem->pTab->zName);
109716 if( pItem->zAlias ){
109717 sqlite3XPrintf(&x, 0, " (AS %s)", pItem->zAlias);
109719 if( pItem->jointype & JT_LEFT ){
109720 sqlite3XPrintf(&x, 0, " LEFT-JOIN");
109722 sqlite3StrAccumFinish(&x);
109723 sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
109724 if( pItem->pSelect ){
109725 sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
109727 sqlite3TreeViewPop(pView);
109729 sqlite3TreeViewPop(pView);
109731 if( p->pWhere ){
109732 sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
109733 sqlite3TreeViewExpr(pView, p->pWhere, 0);
109734 sqlite3TreeViewPop(pView);
109736 if( p->pGroupBy ){
109737 sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
109739 if( p->pHaving ){
109740 sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
109741 sqlite3TreeViewExpr(pView, p->pHaving, 0);
109742 sqlite3TreeViewPop(pView);
109744 if( p->pOrderBy ){
109745 sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
109747 if( p->pLimit ){
109748 sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
109749 sqlite3TreeViewExpr(pView, p->pLimit, 0);
109750 sqlite3TreeViewPop(pView);
109752 if( p->pOffset ){
109753 sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
109754 sqlite3TreeViewExpr(pView, p->pOffset, 0);
109755 sqlite3TreeViewPop(pView);
109757 if( p->pPrior ){
109758 const char *zOp = "UNION";
109759 switch( p->op ){
109760 case TK_ALL: zOp = "UNION ALL"; break;
109761 case TK_INTERSECT: zOp = "INTERSECT"; break;
109762 case TK_EXCEPT: zOp = "EXCEPT"; break;
109764 sqlite3TreeViewItem(pView, zOp, (n--)>0);
109765 sqlite3TreeViewSelect(pView, p->pPrior, 0);
109766 sqlite3TreeViewPop(pView);
109768 sqlite3TreeViewPop(pView);
109770 #endif /* SQLITE_DEBUG */
109772 /************** End of select.c **********************************************/
109773 /************** Begin file table.c *******************************************/
109775 ** 2001 September 15
109777 ** The author disclaims copyright to this source code. In place of
109778 ** a legal notice, here is a blessing:
109780 ** May you do good and not evil.
109781 ** May you find forgiveness for yourself and forgive others.
109782 ** May you share freely, never taking more than you give.
109784 *************************************************************************
109785 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
109786 ** interface routines. These are just wrappers around the main
109787 ** interface routine of sqlite3_exec().
109789 ** These routines are in a separate files so that they will not be linked
109790 ** if they are not used.
109792 /* #include <stdlib.h> */
109793 /* #include <string.h> */
109795 #ifndef SQLITE_OMIT_GET_TABLE
109798 ** This structure is used to pass data from sqlite3_get_table() through
109799 ** to the callback function is uses to build the result.
109801 typedef struct TabResult {
109802 char **azResult; /* Accumulated output */
109803 char *zErrMsg; /* Error message text, if an error occurs */
109804 u32 nAlloc; /* Slots allocated for azResult[] */
109805 u32 nRow; /* Number of rows in the result */
109806 u32 nColumn; /* Number of columns in the result */
109807 u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
109808 int rc; /* Return code from sqlite3_exec() */
109809 } TabResult;
109812 ** This routine is called once for each row in the result table. Its job
109813 ** is to fill in the TabResult structure appropriately, allocating new
109814 ** memory as necessary.
109816 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
109817 TabResult *p = (TabResult*)pArg; /* Result accumulator */
109818 int need; /* Slots needed in p->azResult[] */
109819 int i; /* Loop counter */
109820 char *z; /* A single column of result */
109822 /* Make sure there is enough space in p->azResult to hold everything
109823 ** we need to remember from this invocation of the callback.
109825 if( p->nRow==0 && argv!=0 ){
109826 need = nCol*2;
109827 }else{
109828 need = nCol;
109830 if( p->nData + need > p->nAlloc ){
109831 char **azNew;
109832 p->nAlloc = p->nAlloc*2 + need;
109833 azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
109834 if( azNew==0 ) goto malloc_failed;
109835 p->azResult = azNew;
109838 /* If this is the first row, then generate an extra row containing
109839 ** the names of all columns.
109841 if( p->nRow==0 ){
109842 p->nColumn = nCol;
109843 for(i=0; i<nCol; i++){
109844 z = sqlite3_mprintf("%s", colv[i]);
109845 if( z==0 ) goto malloc_failed;
109846 p->azResult[p->nData++] = z;
109848 }else if( (int)p->nColumn!=nCol ){
109849 sqlite3_free(p->zErrMsg);
109850 p->zErrMsg = sqlite3_mprintf(
109851 "sqlite3_get_table() called with two or more incompatible queries"
109853 p->rc = SQLITE_ERROR;
109854 return 1;
109857 /* Copy over the row data
109859 if( argv!=0 ){
109860 for(i=0; i<nCol; i++){
109861 if( argv[i]==0 ){
109862 z = 0;
109863 }else{
109864 int n = sqlite3Strlen30(argv[i])+1;
109865 z = sqlite3_malloc( n );
109866 if( z==0 ) goto malloc_failed;
109867 memcpy(z, argv[i], n);
109869 p->azResult[p->nData++] = z;
109871 p->nRow++;
109873 return 0;
109875 malloc_failed:
109876 p->rc = SQLITE_NOMEM;
109877 return 1;
109881 ** Query the database. But instead of invoking a callback for each row,
109882 ** malloc() for space to hold the result and return the entire results
109883 ** at the conclusion of the call.
109885 ** The result that is written to ***pazResult is held in memory obtained
109886 ** from malloc(). But the caller cannot free this memory directly.
109887 ** Instead, the entire table should be passed to sqlite3_free_table() when
109888 ** the calling procedure is finished using it.
109890 SQLITE_API int sqlite3_get_table(
109891 sqlite3 *db, /* The database on which the SQL executes */
109892 const char *zSql, /* The SQL to be executed */
109893 char ***pazResult, /* Write the result table here */
109894 int *pnRow, /* Write the number of rows in the result here */
109895 int *pnColumn, /* Write the number of columns of result here */
109896 char **pzErrMsg /* Write error messages here */
109898 int rc;
109899 TabResult res;
109901 *pazResult = 0;
109902 if( pnColumn ) *pnColumn = 0;
109903 if( pnRow ) *pnRow = 0;
109904 if( pzErrMsg ) *pzErrMsg = 0;
109905 res.zErrMsg = 0;
109906 res.nRow = 0;
109907 res.nColumn = 0;
109908 res.nData = 1;
109909 res.nAlloc = 20;
109910 res.rc = SQLITE_OK;
109911 res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
109912 if( res.azResult==0 ){
109913 db->errCode = SQLITE_NOMEM;
109914 return SQLITE_NOMEM;
109916 res.azResult[0] = 0;
109917 rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
109918 assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
109919 res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
109920 if( (rc&0xff)==SQLITE_ABORT ){
109921 sqlite3_free_table(&res.azResult[1]);
109922 if( res.zErrMsg ){
109923 if( pzErrMsg ){
109924 sqlite3_free(*pzErrMsg);
109925 *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
109927 sqlite3_free(res.zErrMsg);
109929 db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
109930 return res.rc;
109932 sqlite3_free(res.zErrMsg);
109933 if( rc!=SQLITE_OK ){
109934 sqlite3_free_table(&res.azResult[1]);
109935 return rc;
109937 if( res.nAlloc>res.nData ){
109938 char **azNew;
109939 azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
109940 if( azNew==0 ){
109941 sqlite3_free_table(&res.azResult[1]);
109942 db->errCode = SQLITE_NOMEM;
109943 return SQLITE_NOMEM;
109945 res.azResult = azNew;
109947 *pazResult = &res.azResult[1];
109948 if( pnColumn ) *pnColumn = res.nColumn;
109949 if( pnRow ) *pnRow = res.nRow;
109950 return rc;
109954 ** This routine frees the space the sqlite3_get_table() malloced.
109956 SQLITE_API void sqlite3_free_table(
109957 char **azResult /* Result returned from sqlite3_get_table() */
109959 if( azResult ){
109960 int i, n;
109961 azResult--;
109962 assert( azResult!=0 );
109963 n = SQLITE_PTR_TO_INT(azResult[0]);
109964 for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
109965 sqlite3_free(azResult);
109969 #endif /* SQLITE_OMIT_GET_TABLE */
109971 /************** End of table.c ***********************************************/
109972 /************** Begin file trigger.c *****************************************/
109975 ** The author disclaims copyright to this source code. In place of
109976 ** a legal notice, here is a blessing:
109978 ** May you do good and not evil.
109979 ** May you find forgiveness for yourself and forgive others.
109980 ** May you share freely, never taking more than you give.
109982 *************************************************************************
109983 ** This file contains the implementation for TRIGGERs
109986 #ifndef SQLITE_OMIT_TRIGGER
109988 ** Delete a linked list of TriggerStep structures.
109990 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
109991 while( pTriggerStep ){
109992 TriggerStep * pTmp = pTriggerStep;
109993 pTriggerStep = pTriggerStep->pNext;
109995 sqlite3ExprDelete(db, pTmp->pWhere);
109996 sqlite3ExprListDelete(db, pTmp->pExprList);
109997 sqlite3SelectDelete(db, pTmp->pSelect);
109998 sqlite3IdListDelete(db, pTmp->pIdList);
110000 sqlite3DbFree(db, pTmp);
110005 ** Given table pTab, return a list of all the triggers attached to
110006 ** the table. The list is connected by Trigger.pNext pointers.
110008 ** All of the triggers on pTab that are in the same database as pTab
110009 ** are already attached to pTab->pTrigger. But there might be additional
110010 ** triggers on pTab in the TEMP schema. This routine prepends all
110011 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
110012 ** and returns the combined list.
110014 ** To state it another way: This routine returns a list of all triggers
110015 ** that fire off of pTab. The list will include any TEMP triggers on
110016 ** pTab as well as the triggers lised in pTab->pTrigger.
110018 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
110019 Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
110020 Trigger *pList = 0; /* List of triggers to return */
110022 if( pParse->disableTriggers ){
110023 return 0;
110026 if( pTmpSchema!=pTab->pSchema ){
110027 HashElem *p;
110028 assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
110029 for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
110030 Trigger *pTrig = (Trigger *)sqliteHashData(p);
110031 if( pTrig->pTabSchema==pTab->pSchema
110032 && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
110034 pTrig->pNext = (pList ? pList : pTab->pTrigger);
110035 pList = pTrig;
110040 return (pList ? pList : pTab->pTrigger);
110044 ** This is called by the parser when it sees a CREATE TRIGGER statement
110045 ** up to the point of the BEGIN before the trigger actions. A Trigger
110046 ** structure is generated based on the information available and stored
110047 ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
110048 ** sqlite3FinishTrigger() function is called to complete the trigger
110049 ** construction process.
110051 SQLITE_PRIVATE void sqlite3BeginTrigger(
110052 Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
110053 Token *pName1, /* The name of the trigger */
110054 Token *pName2, /* The name of the trigger */
110055 int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
110056 int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
110057 IdList *pColumns, /* column list if this is an UPDATE OF trigger */
110058 SrcList *pTableName,/* The name of the table/view the trigger applies to */
110059 Expr *pWhen, /* WHEN clause */
110060 int isTemp, /* True if the TEMPORARY keyword is present */
110061 int noErr /* Suppress errors if the trigger already exists */
110063 Trigger *pTrigger = 0; /* The new trigger */
110064 Table *pTab; /* Table that the trigger fires off of */
110065 char *zName = 0; /* Name of the trigger */
110066 sqlite3 *db = pParse->db; /* The database connection */
110067 int iDb; /* The database to store the trigger in */
110068 Token *pName; /* The unqualified db name */
110069 DbFixer sFix; /* State vector for the DB fixer */
110070 int iTabDb; /* Index of the database holding pTab */
110072 assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
110073 assert( pName2!=0 );
110074 assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
110075 assert( op>0 && op<0xff );
110076 if( isTemp ){
110077 /* If TEMP was specified, then the trigger name may not be qualified. */
110078 if( pName2->n>0 ){
110079 sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
110080 goto trigger_cleanup;
110082 iDb = 1;
110083 pName = pName1;
110084 }else{
110085 /* Figure out the db that the trigger will be created in */
110086 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
110087 if( iDb<0 ){
110088 goto trigger_cleanup;
110091 if( !pTableName || db->mallocFailed ){
110092 goto trigger_cleanup;
110095 /* A long-standing parser bug is that this syntax was allowed:
110097 ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
110098 ** ^^^^^^^^
110100 ** To maintain backwards compatibility, ignore the database
110101 ** name on pTableName if we are reparsing out of SQLITE_MASTER.
110103 if( db->init.busy && iDb!=1 ){
110104 sqlite3DbFree(db, pTableName->a[0].zDatabase);
110105 pTableName->a[0].zDatabase = 0;
110108 /* If the trigger name was unqualified, and the table is a temp table,
110109 ** then set iDb to 1 to create the trigger in the temporary database.
110110 ** If sqlite3SrcListLookup() returns 0, indicating the table does not
110111 ** exist, the error is caught by the block below.
110113 pTab = sqlite3SrcListLookup(pParse, pTableName);
110114 if( db->init.busy==0 && pName2->n==0 && pTab
110115 && pTab->pSchema==db->aDb[1].pSchema ){
110116 iDb = 1;
110119 /* Ensure the table name matches database name and that the table exists */
110120 if( db->mallocFailed ) goto trigger_cleanup;
110121 assert( pTableName->nSrc==1 );
110122 sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
110123 if( sqlite3FixSrcList(&sFix, pTableName) ){
110124 goto trigger_cleanup;
110126 pTab = sqlite3SrcListLookup(pParse, pTableName);
110127 if( !pTab ){
110128 /* The table does not exist. */
110129 if( db->init.iDb==1 ){
110130 /* Ticket #3810.
110131 ** Normally, whenever a table is dropped, all associated triggers are
110132 ** dropped too. But if a TEMP trigger is created on a non-TEMP table
110133 ** and the table is dropped by a different database connection, the
110134 ** trigger is not visible to the database connection that does the
110135 ** drop so the trigger cannot be dropped. This results in an
110136 ** "orphaned trigger" - a trigger whose associated table is missing.
110138 db->init.orphanTrigger = 1;
110140 goto trigger_cleanup;
110142 if( IsVirtual(pTab) ){
110143 sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
110144 goto trigger_cleanup;
110147 /* Check that the trigger name is not reserved and that no trigger of the
110148 ** specified name exists */
110149 zName = sqlite3NameFromToken(db, pName);
110150 if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
110151 goto trigger_cleanup;
110153 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
110154 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
110155 if( !noErr ){
110156 sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
110157 }else{
110158 assert( !db->init.busy );
110159 sqlite3CodeVerifySchema(pParse, iDb);
110161 goto trigger_cleanup;
110164 /* Do not create a trigger on a system table */
110165 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
110166 sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
110167 pParse->nErr++;
110168 goto trigger_cleanup;
110171 /* INSTEAD of triggers are only for views and views only support INSTEAD
110172 ** of triggers.
110174 if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
110175 sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
110176 (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
110177 goto trigger_cleanup;
110179 if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
110180 sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
110181 " trigger on table: %S", pTableName, 0);
110182 goto trigger_cleanup;
110184 iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
110186 #ifndef SQLITE_OMIT_AUTHORIZATION
110188 int code = SQLITE_CREATE_TRIGGER;
110189 const char *zDb = db->aDb[iTabDb].zName;
110190 const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
110191 if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
110192 if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
110193 goto trigger_cleanup;
110195 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
110196 goto trigger_cleanup;
110199 #endif
110201 /* INSTEAD OF triggers can only appear on views and BEFORE triggers
110202 ** cannot appear on views. So we might as well translate every
110203 ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
110204 ** elsewhere.
110206 if (tr_tm == TK_INSTEAD){
110207 tr_tm = TK_BEFORE;
110210 /* Build the Trigger object */
110211 pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
110212 if( pTrigger==0 ) goto trigger_cleanup;
110213 pTrigger->zName = zName;
110214 zName = 0;
110215 pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
110216 pTrigger->pSchema = db->aDb[iDb].pSchema;
110217 pTrigger->pTabSchema = pTab->pSchema;
110218 pTrigger->op = (u8)op;
110219 pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
110220 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
110221 pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
110222 assert( pParse->pNewTrigger==0 );
110223 pParse->pNewTrigger = pTrigger;
110225 trigger_cleanup:
110226 sqlite3DbFree(db, zName);
110227 sqlite3SrcListDelete(db, pTableName);
110228 sqlite3IdListDelete(db, pColumns);
110229 sqlite3ExprDelete(db, pWhen);
110230 if( !pParse->pNewTrigger ){
110231 sqlite3DeleteTrigger(db, pTrigger);
110232 }else{
110233 assert( pParse->pNewTrigger==pTrigger );
110238 ** This routine is called after all of the trigger actions have been parsed
110239 ** in order to complete the process of building the trigger.
110241 SQLITE_PRIVATE void sqlite3FinishTrigger(
110242 Parse *pParse, /* Parser context */
110243 TriggerStep *pStepList, /* The triggered program */
110244 Token *pAll /* Token that describes the complete CREATE TRIGGER */
110246 Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
110247 char *zName; /* Name of trigger */
110248 sqlite3 *db = pParse->db; /* The database */
110249 DbFixer sFix; /* Fixer object */
110250 int iDb; /* Database containing the trigger */
110251 Token nameToken; /* Trigger name for error reporting */
110253 pParse->pNewTrigger = 0;
110254 if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
110255 zName = pTrig->zName;
110256 iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
110257 pTrig->step_list = pStepList;
110258 while( pStepList ){
110259 pStepList->pTrig = pTrig;
110260 pStepList = pStepList->pNext;
110262 nameToken.z = pTrig->zName;
110263 nameToken.n = sqlite3Strlen30(nameToken.z);
110264 sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
110265 if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
110266 || sqlite3FixExpr(&sFix, pTrig->pWhen)
110268 goto triggerfinish_cleanup;
110271 /* if we are not initializing,
110272 ** build the sqlite_master entry
110274 if( !db->init.busy ){
110275 Vdbe *v;
110276 char *z;
110278 /* Make an entry in the sqlite_master table */
110279 v = sqlite3GetVdbe(pParse);
110280 if( v==0 ) goto triggerfinish_cleanup;
110281 sqlite3BeginWriteOperation(pParse, 0, iDb);
110282 z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
110283 sqlite3NestedParse(pParse,
110284 "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
110285 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
110286 pTrig->table, z);
110287 sqlite3DbFree(db, z);
110288 sqlite3ChangeCookie(pParse, iDb);
110289 sqlite3VdbeAddParseSchemaOp(v, iDb,
110290 sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
110293 if( db->init.busy ){
110294 Trigger *pLink = pTrig;
110295 Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
110296 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
110297 pTrig = sqlite3HashInsert(pHash, zName, pTrig);
110298 if( pTrig ){
110299 db->mallocFailed = 1;
110300 }else if( pLink->pSchema==pLink->pTabSchema ){
110301 Table *pTab;
110302 pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
110303 assert( pTab!=0 );
110304 pLink->pNext = pTab->pTrigger;
110305 pTab->pTrigger = pLink;
110309 triggerfinish_cleanup:
110310 sqlite3DeleteTrigger(db, pTrig);
110311 assert( !pParse->pNewTrigger );
110312 sqlite3DeleteTriggerStep(db, pStepList);
110316 ** Turn a SELECT statement (that the pSelect parameter points to) into
110317 ** a trigger step. Return a pointer to a TriggerStep structure.
110319 ** The parser calls this routine when it finds a SELECT statement in
110320 ** body of a TRIGGER.
110322 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
110323 TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
110324 if( pTriggerStep==0 ) {
110325 sqlite3SelectDelete(db, pSelect);
110326 return 0;
110328 pTriggerStep->op = TK_SELECT;
110329 pTriggerStep->pSelect = pSelect;
110330 pTriggerStep->orconf = OE_Default;
110331 return pTriggerStep;
110335 ** Allocate space to hold a new trigger step. The allocated space
110336 ** holds both the TriggerStep object and the TriggerStep.target.z string.
110338 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
110340 static TriggerStep *triggerStepAllocate(
110341 sqlite3 *db, /* Database connection */
110342 u8 op, /* Trigger opcode */
110343 Token *pName /* The target name */
110345 TriggerStep *pTriggerStep;
110347 pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
110348 if( pTriggerStep ){
110349 char *z = (char*)&pTriggerStep[1];
110350 memcpy(z, pName->z, pName->n);
110351 pTriggerStep->target.z = z;
110352 pTriggerStep->target.n = pName->n;
110353 pTriggerStep->op = op;
110355 return pTriggerStep;
110359 ** Build a trigger step out of an INSERT statement. Return a pointer
110360 ** to the new trigger step.
110362 ** The parser calls this routine when it sees an INSERT inside the
110363 ** body of a trigger.
110365 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
110366 sqlite3 *db, /* The database connection */
110367 Token *pTableName, /* Name of the table into which we insert */
110368 IdList *pColumn, /* List of columns in pTableName to insert into */
110369 Select *pSelect, /* A SELECT statement that supplies values */
110370 u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
110372 TriggerStep *pTriggerStep;
110374 assert(pSelect != 0 || db->mallocFailed);
110376 pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
110377 if( pTriggerStep ){
110378 pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
110379 pTriggerStep->pIdList = pColumn;
110380 pTriggerStep->orconf = orconf;
110381 }else{
110382 sqlite3IdListDelete(db, pColumn);
110384 sqlite3SelectDelete(db, pSelect);
110386 return pTriggerStep;
110390 ** Construct a trigger step that implements an UPDATE statement and return
110391 ** a pointer to that trigger step. The parser calls this routine when it
110392 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
110394 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
110395 sqlite3 *db, /* The database connection */
110396 Token *pTableName, /* Name of the table to be updated */
110397 ExprList *pEList, /* The SET clause: list of column and new values */
110398 Expr *pWhere, /* The WHERE clause */
110399 u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
110401 TriggerStep *pTriggerStep;
110403 pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
110404 if( pTriggerStep ){
110405 pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
110406 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
110407 pTriggerStep->orconf = orconf;
110409 sqlite3ExprListDelete(db, pEList);
110410 sqlite3ExprDelete(db, pWhere);
110411 return pTriggerStep;
110415 ** Construct a trigger step that implements a DELETE statement and return
110416 ** a pointer to that trigger step. The parser calls this routine when it
110417 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
110419 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
110420 sqlite3 *db, /* Database connection */
110421 Token *pTableName, /* The table from which rows are deleted */
110422 Expr *pWhere /* The WHERE clause */
110424 TriggerStep *pTriggerStep;
110426 pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
110427 if( pTriggerStep ){
110428 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
110429 pTriggerStep->orconf = OE_Default;
110431 sqlite3ExprDelete(db, pWhere);
110432 return pTriggerStep;
110436 ** Recursively delete a Trigger structure
110438 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
110439 if( pTrigger==0 ) return;
110440 sqlite3DeleteTriggerStep(db, pTrigger->step_list);
110441 sqlite3DbFree(db, pTrigger->zName);
110442 sqlite3DbFree(db, pTrigger->table);
110443 sqlite3ExprDelete(db, pTrigger->pWhen);
110444 sqlite3IdListDelete(db, pTrigger->pColumns);
110445 sqlite3DbFree(db, pTrigger);
110449 ** This function is called to drop a trigger from the database schema.
110451 ** This may be called directly from the parser and therefore identifies
110452 ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
110453 ** same job as this routine except it takes a pointer to the trigger
110454 ** instead of the trigger name.
110456 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
110457 Trigger *pTrigger = 0;
110458 int i;
110459 const char *zDb;
110460 const char *zName;
110461 sqlite3 *db = pParse->db;
110463 if( db->mallocFailed ) goto drop_trigger_cleanup;
110464 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
110465 goto drop_trigger_cleanup;
110468 assert( pName->nSrc==1 );
110469 zDb = pName->a[0].zDatabase;
110470 zName = pName->a[0].zName;
110471 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
110472 for(i=OMIT_TEMPDB; i<db->nDb; i++){
110473 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
110474 if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
110475 assert( sqlite3SchemaMutexHeld(db, j, 0) );
110476 pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
110477 if( pTrigger ) break;
110479 if( !pTrigger ){
110480 if( !noErr ){
110481 sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
110482 }else{
110483 sqlite3CodeVerifyNamedSchema(pParse, zDb);
110485 pParse->checkSchema = 1;
110486 goto drop_trigger_cleanup;
110488 sqlite3DropTriggerPtr(pParse, pTrigger);
110490 drop_trigger_cleanup:
110491 sqlite3SrcListDelete(db, pName);
110495 ** Return a pointer to the Table structure for the table that a trigger
110496 ** is set on.
110498 static Table *tableOfTrigger(Trigger *pTrigger){
110499 return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
110504 ** Drop a trigger given a pointer to that trigger.
110506 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
110507 Table *pTable;
110508 Vdbe *v;
110509 sqlite3 *db = pParse->db;
110510 int iDb;
110512 iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
110513 assert( iDb>=0 && iDb<db->nDb );
110514 pTable = tableOfTrigger(pTrigger);
110515 assert( pTable );
110516 assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
110517 #ifndef SQLITE_OMIT_AUTHORIZATION
110519 int code = SQLITE_DROP_TRIGGER;
110520 const char *zDb = db->aDb[iDb].zName;
110521 const char *zTab = SCHEMA_TABLE(iDb);
110522 if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
110523 if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
110524 sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
110525 return;
110528 #endif
110530 /* Generate code to destroy the database record of the trigger.
110532 assert( pTable!=0 );
110533 if( (v = sqlite3GetVdbe(pParse))!=0 ){
110534 int base;
110535 static const int iLn = VDBE_OFFSET_LINENO(2);
110536 static const VdbeOpList dropTrigger[] = {
110537 { OP_Rewind, 0, ADDR(9), 0},
110538 { OP_String8, 0, 1, 0}, /* 1 */
110539 { OP_Column, 0, 1, 2},
110540 { OP_Ne, 2, ADDR(8), 1},
110541 { OP_String8, 0, 1, 0}, /* 4: "trigger" */
110542 { OP_Column, 0, 0, 2},
110543 { OP_Ne, 2, ADDR(8), 1},
110544 { OP_Delete, 0, 0, 0},
110545 { OP_Next, 0, ADDR(1), 0}, /* 8 */
110548 sqlite3BeginWriteOperation(pParse, 0, iDb);
110549 sqlite3OpenMasterTable(pParse, iDb);
110550 base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger, iLn);
110551 sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
110552 sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
110553 sqlite3ChangeCookie(pParse, iDb);
110554 sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
110555 sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
110556 if( pParse->nMem<3 ){
110557 pParse->nMem = 3;
110563 ** Remove a trigger from the hash tables of the sqlite* pointer.
110565 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
110566 Trigger *pTrigger;
110567 Hash *pHash;
110569 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
110570 pHash = &(db->aDb[iDb].pSchema->trigHash);
110571 pTrigger = sqlite3HashInsert(pHash, zName, 0);
110572 if( ALWAYS(pTrigger) ){
110573 if( pTrigger->pSchema==pTrigger->pTabSchema ){
110574 Table *pTab = tableOfTrigger(pTrigger);
110575 Trigger **pp;
110576 for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
110577 *pp = (*pp)->pNext;
110579 sqlite3DeleteTrigger(db, pTrigger);
110580 db->flags |= SQLITE_InternChanges;
110585 ** pEList is the SET clause of an UPDATE statement. Each entry
110586 ** in pEList is of the format <id>=<expr>. If any of the entries
110587 ** in pEList have an <id> which matches an identifier in pIdList,
110588 ** then return TRUE. If pIdList==NULL, then it is considered a
110589 ** wildcard that matches anything. Likewise if pEList==NULL then
110590 ** it matches anything so always return true. Return false only
110591 ** if there is no match.
110593 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
110594 int e;
110595 if( pIdList==0 || NEVER(pEList==0) ) return 1;
110596 for(e=0; e<pEList->nExpr; e++){
110597 if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
110599 return 0;
110603 ** Return a list of all triggers on table pTab if there exists at least
110604 ** one trigger that must be fired when an operation of type 'op' is
110605 ** performed on the table, and, if that operation is an UPDATE, if at
110606 ** least one of the columns in pChanges is being modified.
110608 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
110609 Parse *pParse, /* Parse context */
110610 Table *pTab, /* The table the contains the triggers */
110611 int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
110612 ExprList *pChanges, /* Columns that change in an UPDATE statement */
110613 int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
110615 int mask = 0;
110616 Trigger *pList = 0;
110617 Trigger *p;
110619 if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
110620 pList = sqlite3TriggerList(pParse, pTab);
110622 assert( pList==0 || IsVirtual(pTab)==0 );
110623 for(p=pList; p; p=p->pNext){
110624 if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
110625 mask |= p->tr_tm;
110628 if( pMask ){
110629 *pMask = mask;
110631 return (mask ? pList : 0);
110635 ** Convert the pStep->target token into a SrcList and return a pointer
110636 ** to that SrcList.
110638 ** This routine adds a specific database name, if needed, to the target when
110639 ** forming the SrcList. This prevents a trigger in one database from
110640 ** referring to a target in another database. An exception is when the
110641 ** trigger is in TEMP in which case it can refer to any other database it
110642 ** wants.
110644 static SrcList *targetSrcList(
110645 Parse *pParse, /* The parsing context */
110646 TriggerStep *pStep /* The trigger containing the target token */
110648 int iDb; /* Index of the database to use */
110649 SrcList *pSrc; /* SrcList to be returned */
110651 pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
110652 if( pSrc ){
110653 assert( pSrc->nSrc>0 );
110654 assert( pSrc->a!=0 );
110655 iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
110656 if( iDb==0 || iDb>=2 ){
110657 sqlite3 *db = pParse->db;
110658 assert( iDb<pParse->db->nDb );
110659 pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
110662 return pSrc;
110666 ** Generate VDBE code for the statements inside the body of a single
110667 ** trigger.
110669 static int codeTriggerProgram(
110670 Parse *pParse, /* The parser context */
110671 TriggerStep *pStepList, /* List of statements inside the trigger body */
110672 int orconf /* Conflict algorithm. (OE_Abort, etc) */
110674 TriggerStep *pStep;
110675 Vdbe *v = pParse->pVdbe;
110676 sqlite3 *db = pParse->db;
110678 assert( pParse->pTriggerTab && pParse->pToplevel );
110679 assert( pStepList );
110680 assert( v!=0 );
110681 for(pStep=pStepList; pStep; pStep=pStep->pNext){
110682 /* Figure out the ON CONFLICT policy that will be used for this step
110683 ** of the trigger program. If the statement that caused this trigger
110684 ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
110685 ** the ON CONFLICT policy that was specified as part of the trigger
110686 ** step statement. Example:
110688 ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
110689 ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
110690 ** END;
110692 ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
110693 ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
110695 pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
110696 assert( pParse->okConstFactor==0 );
110698 switch( pStep->op ){
110699 case TK_UPDATE: {
110700 sqlite3Update(pParse,
110701 targetSrcList(pParse, pStep),
110702 sqlite3ExprListDup(db, pStep->pExprList, 0),
110703 sqlite3ExprDup(db, pStep->pWhere, 0),
110704 pParse->eOrconf
110706 break;
110708 case TK_INSERT: {
110709 sqlite3Insert(pParse,
110710 targetSrcList(pParse, pStep),
110711 sqlite3SelectDup(db, pStep->pSelect, 0),
110712 sqlite3IdListDup(db, pStep->pIdList),
110713 pParse->eOrconf
110715 break;
110717 case TK_DELETE: {
110718 sqlite3DeleteFrom(pParse,
110719 targetSrcList(pParse, pStep),
110720 sqlite3ExprDup(db, pStep->pWhere, 0)
110722 break;
110724 default: assert( pStep->op==TK_SELECT ); {
110725 SelectDest sDest;
110726 Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
110727 sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
110728 sqlite3Select(pParse, pSelect, &sDest);
110729 sqlite3SelectDelete(db, pSelect);
110730 break;
110733 if( pStep->op!=TK_SELECT ){
110734 sqlite3VdbeAddOp0(v, OP_ResetCount);
110738 return 0;
110741 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
110743 ** This function is used to add VdbeComment() annotations to a VDBE
110744 ** program. It is not used in production code, only for debugging.
110746 static const char *onErrorText(int onError){
110747 switch( onError ){
110748 case OE_Abort: return "abort";
110749 case OE_Rollback: return "rollback";
110750 case OE_Fail: return "fail";
110751 case OE_Replace: return "replace";
110752 case OE_Ignore: return "ignore";
110753 case OE_Default: return "default";
110755 return "n/a";
110757 #endif
110760 ** Parse context structure pFrom has just been used to create a sub-vdbe
110761 ** (trigger program). If an error has occurred, transfer error information
110762 ** from pFrom to pTo.
110764 static void transferParseError(Parse *pTo, Parse *pFrom){
110765 assert( pFrom->zErrMsg==0 || pFrom->nErr );
110766 assert( pTo->zErrMsg==0 || pTo->nErr );
110767 if( pTo->nErr==0 ){
110768 pTo->zErrMsg = pFrom->zErrMsg;
110769 pTo->nErr = pFrom->nErr;
110770 }else{
110771 sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
110776 ** Create and populate a new TriggerPrg object with a sub-program
110777 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
110779 static TriggerPrg *codeRowTrigger(
110780 Parse *pParse, /* Current parse context */
110781 Trigger *pTrigger, /* Trigger to code */
110782 Table *pTab, /* The table pTrigger is attached to */
110783 int orconf /* ON CONFLICT policy to code trigger program with */
110785 Parse *pTop = sqlite3ParseToplevel(pParse);
110786 sqlite3 *db = pParse->db; /* Database handle */
110787 TriggerPrg *pPrg; /* Value to return */
110788 Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
110789 Vdbe *v; /* Temporary VM */
110790 NameContext sNC; /* Name context for sub-vdbe */
110791 SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
110792 Parse *pSubParse; /* Parse context for sub-vdbe */
110793 int iEndTrigger = 0; /* Label to jump to if WHEN is false */
110795 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
110796 assert( pTop->pVdbe );
110798 /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
110799 ** are freed if an error occurs, link them into the Parse.pTriggerPrg
110800 ** list of the top-level Parse object sooner rather than later. */
110801 pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
110802 if( !pPrg ) return 0;
110803 pPrg->pNext = pTop->pTriggerPrg;
110804 pTop->pTriggerPrg = pPrg;
110805 pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
110806 if( !pProgram ) return 0;
110807 sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
110808 pPrg->pTrigger = pTrigger;
110809 pPrg->orconf = orconf;
110810 pPrg->aColmask[0] = 0xffffffff;
110811 pPrg->aColmask[1] = 0xffffffff;
110813 /* Allocate and populate a new Parse context to use for coding the
110814 ** trigger sub-program. */
110815 pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
110816 if( !pSubParse ) return 0;
110817 memset(&sNC, 0, sizeof(sNC));
110818 sNC.pParse = pSubParse;
110819 pSubParse->db = db;
110820 pSubParse->pTriggerTab = pTab;
110821 pSubParse->pToplevel = pTop;
110822 pSubParse->zAuthContext = pTrigger->zName;
110823 pSubParse->eTriggerOp = pTrigger->op;
110824 pSubParse->nQueryLoop = pParse->nQueryLoop;
110826 v = sqlite3GetVdbe(pSubParse);
110827 if( v ){
110828 VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
110829 pTrigger->zName, onErrorText(orconf),
110830 (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
110831 (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
110832 (pTrigger->op==TK_INSERT ? "INSERT" : ""),
110833 (pTrigger->op==TK_DELETE ? "DELETE" : ""),
110834 pTab->zName
110836 #ifndef SQLITE_OMIT_TRACE
110837 sqlite3VdbeChangeP4(v, -1,
110838 sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
110840 #endif
110842 /* If one was specified, code the WHEN clause. If it evaluates to false
110843 ** (or NULL) the sub-vdbe is immediately halted by jumping to the
110844 ** OP_Halt inserted at the end of the program. */
110845 if( pTrigger->pWhen ){
110846 pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
110847 if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
110848 && db->mallocFailed==0
110850 iEndTrigger = sqlite3VdbeMakeLabel(v);
110851 sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
110853 sqlite3ExprDelete(db, pWhen);
110856 /* Code the trigger program into the sub-vdbe. */
110857 codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
110859 /* Insert an OP_Halt at the end of the sub-program. */
110860 if( iEndTrigger ){
110861 sqlite3VdbeResolveLabel(v, iEndTrigger);
110863 sqlite3VdbeAddOp0(v, OP_Halt);
110864 VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
110866 transferParseError(pParse, pSubParse);
110867 if( db->mallocFailed==0 ){
110868 pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
110870 pProgram->nMem = pSubParse->nMem;
110871 pProgram->nCsr = pSubParse->nTab;
110872 pProgram->nOnce = pSubParse->nOnce;
110873 pProgram->token = (void *)pTrigger;
110874 pPrg->aColmask[0] = pSubParse->oldmask;
110875 pPrg->aColmask[1] = pSubParse->newmask;
110876 sqlite3VdbeDelete(v);
110879 assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
110880 assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
110881 sqlite3ParserReset(pSubParse);
110882 sqlite3StackFree(db, pSubParse);
110884 return pPrg;
110888 ** Return a pointer to a TriggerPrg object containing the sub-program for
110889 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
110890 ** TriggerPrg object exists, a new object is allocated and populated before
110891 ** being returned.
110893 static TriggerPrg *getRowTrigger(
110894 Parse *pParse, /* Current parse context */
110895 Trigger *pTrigger, /* Trigger to code */
110896 Table *pTab, /* The table trigger pTrigger is attached to */
110897 int orconf /* ON CONFLICT algorithm. */
110899 Parse *pRoot = sqlite3ParseToplevel(pParse);
110900 TriggerPrg *pPrg;
110902 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
110904 /* It may be that this trigger has already been coded (or is in the
110905 ** process of being coded). If this is the case, then an entry with
110906 ** a matching TriggerPrg.pTrigger field will be present somewhere
110907 ** in the Parse.pTriggerPrg list. Search for such an entry. */
110908 for(pPrg=pRoot->pTriggerPrg;
110909 pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
110910 pPrg=pPrg->pNext
110913 /* If an existing TriggerPrg could not be located, create a new one. */
110914 if( !pPrg ){
110915 pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
110918 return pPrg;
110922 ** Generate code for the trigger program associated with trigger p on
110923 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
110924 ** function are the same as those described in the header function for
110925 ** sqlite3CodeRowTrigger()
110927 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
110928 Parse *pParse, /* Parse context */
110929 Trigger *p, /* Trigger to code */
110930 Table *pTab, /* The table to code triggers from */
110931 int reg, /* Reg array containing OLD.* and NEW.* values */
110932 int orconf, /* ON CONFLICT policy */
110933 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
110935 Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
110936 TriggerPrg *pPrg;
110937 pPrg = getRowTrigger(pParse, p, pTab, orconf);
110938 assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
110940 /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
110941 ** is a pointer to the sub-vdbe containing the trigger program. */
110942 if( pPrg ){
110943 int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
110945 sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
110946 sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
110947 VdbeComment(
110948 (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
110950 /* Set the P5 operand of the OP_Program instruction to non-zero if
110951 ** recursive invocation of this trigger program is disallowed. Recursive
110952 ** invocation is disallowed if (a) the sub-program is really a trigger,
110953 ** not a foreign key action, and (b) the flag to enable recursive triggers
110954 ** is clear. */
110955 sqlite3VdbeChangeP5(v, (u8)bRecursive);
110960 ** This is called to code the required FOR EACH ROW triggers for an operation
110961 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
110962 ** is given by the op parameter. The tr_tm parameter determines whether the
110963 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
110964 ** parameter pChanges is passed the list of columns being modified.
110966 ** If there are no triggers that fire at the specified time for the specified
110967 ** operation on pTab, this function is a no-op.
110969 ** The reg argument is the address of the first in an array of registers
110970 ** that contain the values substituted for the new.* and old.* references
110971 ** in the trigger program. If N is the number of columns in table pTab
110972 ** (a copy of pTab->nCol), then registers are populated as follows:
110974 ** Register Contains
110975 ** ------------------------------------------------------
110976 ** reg+0 OLD.rowid
110977 ** reg+1 OLD.* value of left-most column of pTab
110978 ** ... ...
110979 ** reg+N OLD.* value of right-most column of pTab
110980 ** reg+N+1 NEW.rowid
110981 ** reg+N+2 OLD.* value of left-most column of pTab
110982 ** ... ...
110983 ** reg+N+N+1 NEW.* value of right-most column of pTab
110985 ** For ON DELETE triggers, the registers containing the NEW.* values will
110986 ** never be accessed by the trigger program, so they are not allocated or
110987 ** populated by the caller (there is no data to populate them with anyway).
110988 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
110989 ** are never accessed, and so are not allocated by the caller. So, for an
110990 ** ON INSERT trigger, the value passed to this function as parameter reg
110991 ** is not a readable register, although registers (reg+N) through
110992 ** (reg+N+N+1) are.
110994 ** Parameter orconf is the default conflict resolution algorithm for the
110995 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
110996 ** is the instruction that control should jump to if a trigger program
110997 ** raises an IGNORE exception.
110999 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
111000 Parse *pParse, /* Parse context */
111001 Trigger *pTrigger, /* List of triggers on table pTab */
111002 int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
111003 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
111004 int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
111005 Table *pTab, /* The table to code triggers from */
111006 int reg, /* The first in an array of registers (see above) */
111007 int orconf, /* ON CONFLICT policy */
111008 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
111010 Trigger *p; /* Used to iterate through pTrigger list */
111012 assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
111013 assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
111014 assert( (op==TK_UPDATE)==(pChanges!=0) );
111016 for(p=pTrigger; p; p=p->pNext){
111018 /* Sanity checking: The schema for the trigger and for the table are
111019 ** always defined. The trigger must be in the same schema as the table
111020 ** or else it must be a TEMP trigger. */
111021 assert( p->pSchema!=0 );
111022 assert( p->pTabSchema!=0 );
111023 assert( p->pSchema==p->pTabSchema
111024 || p->pSchema==pParse->db->aDb[1].pSchema );
111026 /* Determine whether we should code this trigger */
111027 if( p->op==op
111028 && p->tr_tm==tr_tm
111029 && checkColumnOverlap(p->pColumns, pChanges)
111031 sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
111037 ** Triggers may access values stored in the old.* or new.* pseudo-table.
111038 ** This function returns a 32-bit bitmask indicating which columns of the
111039 ** old.* or new.* tables actually are used by triggers. This information
111040 ** may be used by the caller, for example, to avoid having to load the entire
111041 ** old.* record into memory when executing an UPDATE or DELETE command.
111043 ** Bit 0 of the returned mask is set if the left-most column of the
111044 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
111045 ** the second leftmost column value is required, and so on. If there
111046 ** are more than 32 columns in the table, and at least one of the columns
111047 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
111049 ** It is not possible to determine if the old.rowid or new.rowid column is
111050 ** accessed by triggers. The caller must always assume that it is.
111052 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
111053 ** applies to the old.* table. If 1, the new.* table.
111055 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
111056 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
111057 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
111058 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
111059 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
111061 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
111062 Parse *pParse, /* Parse context */
111063 Trigger *pTrigger, /* List of triggers on table pTab */
111064 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
111065 int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
111066 int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
111067 Table *pTab, /* The table to code triggers from */
111068 int orconf /* Default ON CONFLICT policy for trigger steps */
111070 const int op = pChanges ? TK_UPDATE : TK_DELETE;
111071 u32 mask = 0;
111072 Trigger *p;
111074 assert( isNew==1 || isNew==0 );
111075 for(p=pTrigger; p; p=p->pNext){
111076 if( p->op==op && (tr_tm&p->tr_tm)
111077 && checkColumnOverlap(p->pColumns,pChanges)
111079 TriggerPrg *pPrg;
111080 pPrg = getRowTrigger(pParse, p, pTab, orconf);
111081 if( pPrg ){
111082 mask |= pPrg->aColmask[isNew];
111087 return mask;
111090 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
111092 /************** End of trigger.c *********************************************/
111093 /************** Begin file update.c ******************************************/
111095 ** 2001 September 15
111097 ** The author disclaims copyright to this source code. In place of
111098 ** a legal notice, here is a blessing:
111100 ** May you do good and not evil.
111101 ** May you find forgiveness for yourself and forgive others.
111102 ** May you share freely, never taking more than you give.
111104 *************************************************************************
111105 ** This file contains C code routines that are called by the parser
111106 ** to handle UPDATE statements.
111109 #ifndef SQLITE_OMIT_VIRTUALTABLE
111110 /* Forward declaration */
111111 static void updateVirtualTable(
111112 Parse *pParse, /* The parsing context */
111113 SrcList *pSrc, /* The virtual table to be modified */
111114 Table *pTab, /* The virtual table */
111115 ExprList *pChanges, /* The columns to change in the UPDATE statement */
111116 Expr *pRowidExpr, /* Expression used to recompute the rowid */
111117 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
111118 Expr *pWhere, /* WHERE clause of the UPDATE statement */
111119 int onError /* ON CONFLICT strategy */
111121 #endif /* SQLITE_OMIT_VIRTUALTABLE */
111124 ** The most recently coded instruction was an OP_Column to retrieve the
111125 ** i-th column of table pTab. This routine sets the P4 parameter of the
111126 ** OP_Column to the default value, if any.
111128 ** The default value of a column is specified by a DEFAULT clause in the
111129 ** column definition. This was either supplied by the user when the table
111130 ** was created, or added later to the table definition by an ALTER TABLE
111131 ** command. If the latter, then the row-records in the table btree on disk
111132 ** may not contain a value for the column and the default value, taken
111133 ** from the P4 parameter of the OP_Column instruction, is returned instead.
111134 ** If the former, then all row-records are guaranteed to include a value
111135 ** for the column and the P4 value is not required.
111137 ** Column definitions created by an ALTER TABLE command may only have
111138 ** literal default values specified: a number, null or a string. (If a more
111139 ** complicated default expression value was provided, it is evaluated
111140 ** when the ALTER TABLE is executed and one of the literal values written
111141 ** into the sqlite_master table.)
111143 ** Therefore, the P4 parameter is only required if the default value for
111144 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
111145 ** function is capable of transforming these types of expressions into
111146 ** sqlite3_value objects.
111148 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
111149 ** on register iReg. This is used when an equivalent integer value is
111150 ** stored in place of an 8-byte floating point value in order to save
111151 ** space.
111153 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
111154 assert( pTab!=0 );
111155 if( !pTab->pSelect ){
111156 sqlite3_value *pValue = 0;
111157 u8 enc = ENC(sqlite3VdbeDb(v));
111158 Column *pCol = &pTab->aCol[i];
111159 VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
111160 assert( i<pTab->nCol );
111161 sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
111162 pCol->affinity, &pValue);
111163 if( pValue ){
111164 sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
111166 #ifndef SQLITE_OMIT_FLOATING_POINT
111167 if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
111168 sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
111170 #endif
111175 ** Process an UPDATE statement.
111177 ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
111178 ** \_______/ \________/ \______/ \________________/
111179 * onError pTabList pChanges pWhere
111181 SQLITE_PRIVATE void sqlite3Update(
111182 Parse *pParse, /* The parser context */
111183 SrcList *pTabList, /* The table in which we should change things */
111184 ExprList *pChanges, /* Things to be changed */
111185 Expr *pWhere, /* The WHERE clause. May be null */
111186 int onError /* How to handle constraint errors */
111188 int i, j; /* Loop counters */
111189 Table *pTab; /* The table to be updated */
111190 int addrTop = 0; /* VDBE instruction address of the start of the loop */
111191 WhereInfo *pWInfo; /* Information about the WHERE clause */
111192 Vdbe *v; /* The virtual database engine */
111193 Index *pIdx; /* For looping over indices */
111194 Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
111195 int nIdx; /* Number of indices that need updating */
111196 int iBaseCur; /* Base cursor number */
111197 int iDataCur; /* Cursor for the canonical data btree */
111198 int iIdxCur; /* Cursor for the first index */
111199 sqlite3 *db; /* The database structure */
111200 int *aRegIdx = 0; /* One register assigned to each index to be updated */
111201 int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
111202 ** an expression for the i-th column of the table.
111203 ** aXRef[i]==-1 if the i-th column is not changed. */
111204 u8 *aToOpen; /* 1 for tables and indices to be opened */
111205 u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
111206 u8 chngRowid; /* Rowid changed in a normal table */
111207 u8 chngKey; /* Either chngPk or chngRowid */
111208 Expr *pRowidExpr = 0; /* Expression defining the new record number */
111209 AuthContext sContext; /* The authorization context */
111210 NameContext sNC; /* The name-context to resolve expressions in */
111211 int iDb; /* Database containing the table being updated */
111212 int okOnePass; /* True for one-pass algorithm without the FIFO */
111213 int hasFK; /* True if foreign key processing is required */
111214 int labelBreak; /* Jump here to break out of UPDATE loop */
111215 int labelContinue; /* Jump here to continue next step of UPDATE loop */
111217 #ifndef SQLITE_OMIT_TRIGGER
111218 int isView; /* True when updating a view (INSTEAD OF trigger) */
111219 Trigger *pTrigger; /* List of triggers on pTab, if required */
111220 int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
111221 #endif
111222 int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
111223 int iEph = 0; /* Ephemeral table holding all primary key values */
111224 int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
111225 int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
111227 /* Register Allocations */
111228 int regRowCount = 0; /* A count of rows changed */
111229 int regOldRowid; /* The old rowid */
111230 int regNewRowid; /* The new rowid */
111231 int regNew; /* Content of the NEW.* table in triggers */
111232 int regOld = 0; /* Content of OLD.* table in triggers */
111233 int regRowSet = 0; /* Rowset of rows to be updated */
111234 int regKey = 0; /* composite PRIMARY KEY value */
111236 memset(&sContext, 0, sizeof(sContext));
111237 db = pParse->db;
111238 if( pParse->nErr || db->mallocFailed ){
111239 goto update_cleanup;
111241 assert( pTabList->nSrc==1 );
111243 /* Locate the table which we want to update.
111245 pTab = sqlite3SrcListLookup(pParse, pTabList);
111246 if( pTab==0 ) goto update_cleanup;
111247 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
111249 /* Figure out if we have any triggers and if the table being
111250 ** updated is a view.
111252 #ifndef SQLITE_OMIT_TRIGGER
111253 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
111254 isView = pTab->pSelect!=0;
111255 assert( pTrigger || tmask==0 );
111256 #else
111257 # define pTrigger 0
111258 # define isView 0
111259 # define tmask 0
111260 #endif
111261 #ifdef SQLITE_OMIT_VIEW
111262 # undef isView
111263 # define isView 0
111264 #endif
111266 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
111267 goto update_cleanup;
111269 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
111270 goto update_cleanup;
111273 /* Allocate a cursors for the main database table and for all indices.
111274 ** The index cursors might not be used, but if they are used they
111275 ** need to occur right after the database cursor. So go ahead and
111276 ** allocate enough space, just in case.
111278 pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
111279 iIdxCur = iDataCur+1;
111280 pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
111281 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
111282 if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
111283 iDataCur = pParse->nTab;
111284 pTabList->a[0].iCursor = iDataCur;
111286 pParse->nTab++;
111289 /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
111290 ** Initialize aXRef[] and aToOpen[] to their default values.
111292 aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
111293 if( aXRef==0 ) goto update_cleanup;
111294 aRegIdx = aXRef+pTab->nCol;
111295 aToOpen = (u8*)(aRegIdx+nIdx);
111296 memset(aToOpen, 1, nIdx+1);
111297 aToOpen[nIdx+1] = 0;
111298 for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
111300 /* Initialize the name-context */
111301 memset(&sNC, 0, sizeof(sNC));
111302 sNC.pParse = pParse;
111303 sNC.pSrcList = pTabList;
111305 /* Resolve the column names in all the expressions of the
111306 ** of the UPDATE statement. Also find the column index
111307 ** for each column to be updated in the pChanges array. For each
111308 ** column to be updated, make sure we have authorization to change
111309 ** that column.
111311 chngRowid = chngPk = 0;
111312 for(i=0; i<pChanges->nExpr; i++){
111313 if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
111314 goto update_cleanup;
111316 for(j=0; j<pTab->nCol; j++){
111317 if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
111318 if( j==pTab->iPKey ){
111319 chngRowid = 1;
111320 pRowidExpr = pChanges->a[i].pExpr;
111321 }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
111322 chngPk = 1;
111324 aXRef[j] = i;
111325 break;
111328 if( j>=pTab->nCol ){
111329 if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
111330 j = -1;
111331 chngRowid = 1;
111332 pRowidExpr = pChanges->a[i].pExpr;
111333 }else{
111334 sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
111335 pParse->checkSchema = 1;
111336 goto update_cleanup;
111339 #ifndef SQLITE_OMIT_AUTHORIZATION
111341 int rc;
111342 rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
111343 j<0 ? "ROWID" : pTab->aCol[j].zName,
111344 db->aDb[iDb].zName);
111345 if( rc==SQLITE_DENY ){
111346 goto update_cleanup;
111347 }else if( rc==SQLITE_IGNORE ){
111348 aXRef[j] = -1;
111351 #endif
111353 assert( (chngRowid & chngPk)==0 );
111354 assert( chngRowid==0 || chngRowid==1 );
111355 assert( chngPk==0 || chngPk==1 );
111356 chngKey = chngRowid + chngPk;
111358 /* The SET expressions are not actually used inside the WHERE loop.
111359 ** So reset the colUsed mask
111361 pTabList->a[0].colUsed = 0;
111363 hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
111365 /* There is one entry in the aRegIdx[] array for each index on the table
111366 ** being updated. Fill in aRegIdx[] with a register number that will hold
111367 ** the key for accessing each index.
111369 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
111370 int reg;
111371 if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
111372 reg = ++pParse->nMem;
111373 }else{
111374 reg = 0;
111375 for(i=0; i<pIdx->nKeyCol; i++){
111376 if( aXRef[pIdx->aiColumn[i]]>=0 ){
111377 reg = ++pParse->nMem;
111378 break;
111382 if( reg==0 ) aToOpen[j+1] = 0;
111383 aRegIdx[j] = reg;
111386 /* Begin generating code. */
111387 v = sqlite3GetVdbe(pParse);
111388 if( v==0 ) goto update_cleanup;
111389 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
111390 sqlite3BeginWriteOperation(pParse, 1, iDb);
111392 #ifndef SQLITE_OMIT_VIRTUALTABLE
111393 /* Virtual tables must be handled separately */
111394 if( IsVirtual(pTab) ){
111395 updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
111396 pWhere, onError);
111397 pWhere = 0;
111398 pTabList = 0;
111399 goto update_cleanup;
111401 #endif
111403 /* Allocate required registers. */
111404 regRowSet = ++pParse->nMem;
111405 regOldRowid = regNewRowid = ++pParse->nMem;
111406 if( chngPk || pTrigger || hasFK ){
111407 regOld = pParse->nMem + 1;
111408 pParse->nMem += pTab->nCol;
111410 if( chngKey || pTrigger || hasFK ){
111411 regNewRowid = ++pParse->nMem;
111413 regNew = pParse->nMem + 1;
111414 pParse->nMem += pTab->nCol;
111416 /* Start the view context. */
111417 if( isView ){
111418 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
111421 /* If we are trying to update a view, realize that view into
111422 ** an ephemeral table.
111424 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
111425 if( isView ){
111426 sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
111428 #endif
111430 /* Resolve the column names in all the expressions in the
111431 ** WHERE clause.
111433 if( sqlite3ResolveExprNames(&sNC, pWhere) ){
111434 goto update_cleanup;
111437 /* Begin the database scan
111439 if( HasRowid(pTab) ){
111440 sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
111441 pWInfo = sqlite3WhereBegin(
111442 pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
111444 if( pWInfo==0 ) goto update_cleanup;
111445 okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
111447 /* Remember the rowid of every item to be updated.
111449 sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
111450 if( !okOnePass ){
111451 sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
111454 /* End the database scan loop.
111456 sqlite3WhereEnd(pWInfo);
111457 }else{
111458 int iPk; /* First of nPk memory cells holding PRIMARY KEY value */
111459 i16 nPk; /* Number of components of the PRIMARY KEY */
111460 int addrOpen; /* Address of the OpenEphemeral instruction */
111462 assert( pPk!=0 );
111463 nPk = pPk->nKeyCol;
111464 iPk = pParse->nMem+1;
111465 pParse->nMem += nPk;
111466 regKey = ++pParse->nMem;
111467 iEph = pParse->nTab++;
111468 sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
111469 addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
111470 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
111471 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
111472 WHERE_ONEPASS_DESIRED, iIdxCur);
111473 if( pWInfo==0 ) goto update_cleanup;
111474 okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
111475 for(i=0; i<nPk; i++){
111476 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
111477 iPk+i);
111479 if( okOnePass ){
111480 sqlite3VdbeChangeToNoop(v, addrOpen);
111481 nKey = nPk;
111482 regKey = iPk;
111483 }else{
111484 sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
111485 sqlite3IndexAffinityStr(v, pPk), nPk);
111486 sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
111488 sqlite3WhereEnd(pWInfo);
111491 /* Initialize the count of updated rows
111493 if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
111494 regRowCount = ++pParse->nMem;
111495 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
111498 labelBreak = sqlite3VdbeMakeLabel(v);
111499 if( !isView ){
111501 ** Open every index that needs updating. Note that if any
111502 ** index could potentially invoke a REPLACE conflict resolution
111503 ** action, then we need to open all indices because we might need
111504 ** to be deleting some records.
111506 if( onError==OE_Replace ){
111507 memset(aToOpen, 1, nIdx+1);
111508 }else{
111509 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
111510 if( pIdx->onError==OE_Replace ){
111511 memset(aToOpen, 1, nIdx+1);
111512 break;
111516 if( okOnePass ){
111517 if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
111518 if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
111520 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iBaseCur, aToOpen,
111521 0, 0);
111524 /* Top of the update loop */
111525 if( okOnePass ){
111526 if( aToOpen[iDataCur-iBaseCur] && !isView ){
111527 assert( pPk );
111528 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
111529 VdbeCoverageNeverTaken(v);
111531 labelContinue = labelBreak;
111532 sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
111533 VdbeCoverageIf(v, pPk==0);
111534 VdbeCoverageIf(v, pPk!=0);
111535 }else if( pPk ){
111536 labelContinue = sqlite3VdbeMakeLabel(v);
111537 sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
111538 addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
111539 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
111540 VdbeCoverage(v);
111541 }else{
111542 labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
111543 regOldRowid);
111544 VdbeCoverage(v);
111545 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
111546 VdbeCoverage(v);
111549 /* If the record number will change, set register regNewRowid to
111550 ** contain the new value. If the record number is not being modified,
111551 ** then regNewRowid is the same register as regOldRowid, which is
111552 ** already populated. */
111553 assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
111554 if( chngRowid ){
111555 sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
111556 sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
111559 /* Compute the old pre-UPDATE content of the row being changed, if that
111560 ** information is needed */
111561 if( chngPk || hasFK || pTrigger ){
111562 u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
111563 oldmask |= sqlite3TriggerColmask(pParse,
111564 pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
111566 for(i=0; i<pTab->nCol; i++){
111567 if( oldmask==0xffffffff
111568 || (i<32 && (oldmask & MASKBIT32(i))!=0)
111569 || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
111571 testcase( oldmask!=0xffffffff && i==31 );
111572 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
111573 }else{
111574 sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
111577 if( chngRowid==0 && pPk==0 ){
111578 sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
111582 /* Populate the array of registers beginning at regNew with the new
111583 ** row data. This array is used to check constants, create the new
111584 ** table and index records, and as the values for any new.* references
111585 ** made by triggers.
111587 ** If there are one or more BEFORE triggers, then do not populate the
111588 ** registers associated with columns that are (a) not modified by
111589 ** this UPDATE statement and (b) not accessed by new.* references. The
111590 ** values for registers not modified by the UPDATE must be reloaded from
111591 ** the database after the BEFORE triggers are fired anyway (as the trigger
111592 ** may have modified them). So not loading those that are not going to
111593 ** be used eliminates some redundant opcodes.
111595 newmask = sqlite3TriggerColmask(
111596 pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
111598 /*sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);*/
111599 for(i=0; i<pTab->nCol; i++){
111600 if( i==pTab->iPKey ){
111601 sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
111602 }else{
111603 j = aXRef[i];
111604 if( j>=0 ){
111605 sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
111606 }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
111607 /* This branch loads the value of a column that will not be changed
111608 ** into a register. This is done if there are no BEFORE triggers, or
111609 ** if there are one or more BEFORE triggers that use this value via
111610 ** a new.* reference in a trigger program.
111612 testcase( i==31 );
111613 testcase( i==32 );
111614 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
111615 }else{
111616 sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
111621 /* Fire any BEFORE UPDATE triggers. This happens before constraints are
111622 ** verified. One could argue that this is wrong.
111624 if( tmask&TRIGGER_BEFORE ){
111625 sqlite3TableAffinity(v, pTab, regNew);
111626 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
111627 TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
111629 /* The row-trigger may have deleted the row being updated. In this
111630 ** case, jump to the next row. No updates or AFTER triggers are
111631 ** required. This behavior - what happens when the row being updated
111632 ** is deleted or renamed by a BEFORE trigger - is left undefined in the
111633 ** documentation.
111635 if( pPk ){
111636 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
111637 VdbeCoverage(v);
111638 }else{
111639 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
111640 VdbeCoverage(v);
111643 /* If it did not delete it, the row-trigger may still have modified
111644 ** some of the columns of the row being updated. Load the values for
111645 ** all columns not modified by the update statement into their
111646 ** registers in case this has happened.
111648 for(i=0; i<pTab->nCol; i++){
111649 if( aXRef[i]<0 && i!=pTab->iPKey ){
111650 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
111655 if( !isView ){
111656 int j1 = 0; /* Address of jump instruction */
111657 int bReplace = 0; /* True if REPLACE conflict resolution might happen */
111659 /* Do constraint checks. */
111660 assert( regOldRowid>0 );
111661 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
111662 regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
111664 /* Do FK constraint checks. */
111665 if( hasFK ){
111666 sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
111669 /* Delete the index entries associated with the current record. */
111670 if( bReplace || chngKey ){
111671 if( pPk ){
111672 j1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
111673 }else{
111674 j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
111676 VdbeCoverageNeverTaken(v);
111678 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx);
111680 /* If changing the record number, delete the old record. */
111681 if( hasFK || chngKey || pPk!=0 ){
111682 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
111684 if( bReplace || chngKey ){
111685 sqlite3VdbeJumpHere(v, j1);
111688 if( hasFK ){
111689 sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
111692 /* Insert the new index entries and the new record. */
111693 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
111694 regNewRowid, aRegIdx, 1, 0, 0);
111696 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
111697 ** handle rows (possibly in other tables) that refer via a foreign key
111698 ** to the row just updated. */
111699 if( hasFK ){
111700 sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
111704 /* Increment the row counter
111706 if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
111707 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
111710 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
111711 TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
111713 /* Repeat the above with the next record to be updated, until
111714 ** all record selected by the WHERE clause have been updated.
111716 if( okOnePass ){
111717 /* Nothing to do at end-of-loop for a single-pass */
111718 }else if( pPk ){
111719 sqlite3VdbeResolveLabel(v, labelContinue);
111720 sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
111721 }else{
111722 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelContinue);
111724 sqlite3VdbeResolveLabel(v, labelBreak);
111726 /* Close all tables */
111727 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
111728 assert( aRegIdx );
111729 if( aToOpen[i+1] ){
111730 sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
111733 if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
111735 /* Update the sqlite_sequence table by storing the content of the
111736 ** maximum rowid counter values recorded while inserting into
111737 ** autoincrement tables.
111739 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
111740 sqlite3AutoincrementEnd(pParse);
111744 ** Return the number of rows that were changed. If this routine is
111745 ** generating code because of a call to sqlite3NestedParse(), do not
111746 ** invoke the callback function.
111748 if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
111749 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
111750 sqlite3VdbeSetNumCols(v, 1);
111751 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
111754 update_cleanup:
111755 sqlite3AuthContextPop(&sContext);
111756 sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
111757 sqlite3SrcListDelete(db, pTabList);
111758 sqlite3ExprListDelete(db, pChanges);
111759 sqlite3ExprDelete(db, pWhere);
111760 return;
111762 /* Make sure "isView" and other macros defined above are undefined. Otherwise
111763 ** they may interfere with compilation of other functions in this file
111764 ** (or in another file, if this file becomes part of the amalgamation). */
111765 #ifdef isView
111766 #undef isView
111767 #endif
111768 #ifdef pTrigger
111769 #undef pTrigger
111770 #endif
111772 #ifndef SQLITE_OMIT_VIRTUALTABLE
111774 ** Generate code for an UPDATE of a virtual table.
111776 ** The strategy is that we create an ephemeral table that contains
111777 ** for each row to be changed:
111779 ** (A) The original rowid of that row.
111780 ** (B) The revised rowid for the row. (note1)
111781 ** (C) The content of every column in the row.
111783 ** Then we loop over this ephemeral table and for each row in
111784 ** the ephemeral table call VUpdate.
111786 ** When finished, drop the ephemeral table.
111788 ** (note1) Actually, if we know in advance that (A) is always the same
111789 ** as (B) we only store (A), then duplicate (A) when pulling
111790 ** it out of the ephemeral table before calling VUpdate.
111792 static void updateVirtualTable(
111793 Parse *pParse, /* The parsing context */
111794 SrcList *pSrc, /* The virtual table to be modified */
111795 Table *pTab, /* The virtual table */
111796 ExprList *pChanges, /* The columns to change in the UPDATE statement */
111797 Expr *pRowid, /* Expression used to recompute the rowid */
111798 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
111799 Expr *pWhere, /* WHERE clause of the UPDATE statement */
111800 int onError /* ON CONFLICT strategy */
111802 Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
111803 ExprList *pEList = 0; /* The result set of the SELECT statement */
111804 Select *pSelect = 0; /* The SELECT statement */
111805 Expr *pExpr; /* Temporary expression */
111806 int ephemTab; /* Table holding the result of the SELECT */
111807 int i; /* Loop counter */
111808 int addr; /* Address of top of loop */
111809 int iReg; /* First register in set passed to OP_VUpdate */
111810 sqlite3 *db = pParse->db; /* Database connection */
111811 const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
111812 SelectDest dest;
111814 /* Construct the SELECT statement that will find the new values for
111815 ** all updated rows.
111817 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
111818 if( pRowid ){
111819 pEList = sqlite3ExprListAppend(pParse, pEList,
111820 sqlite3ExprDup(db, pRowid, 0));
111822 assert( pTab->iPKey<0 );
111823 for(i=0; i<pTab->nCol; i++){
111824 if( aXRef[i]>=0 ){
111825 pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
111826 }else{
111827 pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
111829 pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
111831 pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
111833 /* Create the ephemeral table into which the update results will
111834 ** be stored.
111836 assert( v );
111837 ephemTab = pParse->nTab++;
111838 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
111839 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
111841 /* fill the ephemeral table
111843 sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
111844 sqlite3Select(pParse, pSelect, &dest);
111846 /* Generate code to scan the ephemeral table and call VUpdate. */
111847 iReg = ++pParse->nMem;
111848 pParse->nMem += pTab->nCol+1;
111849 addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0); VdbeCoverage(v);
111850 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
111851 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
111852 for(i=0; i<pTab->nCol; i++){
111853 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
111855 sqlite3VtabMakeWritable(pParse, pTab);
111856 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
111857 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
111858 sqlite3MayAbort(pParse);
111859 sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
111860 sqlite3VdbeJumpHere(v, addr);
111861 sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
111863 /* Cleanup */
111864 sqlite3SelectDelete(db, pSelect);
111866 #endif /* SQLITE_OMIT_VIRTUALTABLE */
111868 /************** End of update.c **********************************************/
111869 /************** Begin file vacuum.c ******************************************/
111871 ** 2003 April 6
111873 ** The author disclaims copyright to this source code. In place of
111874 ** a legal notice, here is a blessing:
111876 ** May you do good and not evil.
111877 ** May you find forgiveness for yourself and forgive others.
111878 ** May you share freely, never taking more than you give.
111880 *************************************************************************
111881 ** This file contains code used to implement the VACUUM command.
111883 ** Most of the code in this file may be omitted by defining the
111884 ** SQLITE_OMIT_VACUUM macro.
111887 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
111889 ** Finalize a prepared statement. If there was an error, store the
111890 ** text of the error message in *pzErrMsg. Return the result code.
111892 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
111893 int rc;
111894 rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
111895 if( rc ){
111896 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
111898 return rc;
111902 ** Execute zSql on database db. Return an error code.
111904 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
111905 sqlite3_stmt *pStmt;
111906 VVA_ONLY( int rc; )
111907 if( !zSql ){
111908 return SQLITE_NOMEM;
111910 if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
111911 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
111912 return sqlite3_errcode(db);
111914 VVA_ONLY( rc = ) sqlite3_step(pStmt);
111915 assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
111916 return vacuumFinalize(db, pStmt, pzErrMsg);
111920 ** Execute zSql on database db. The statement returns exactly
111921 ** one column. Execute this as SQL on the same database.
111923 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
111924 sqlite3_stmt *pStmt;
111925 int rc;
111927 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
111928 if( rc!=SQLITE_OK ) return rc;
111930 while( SQLITE_ROW==sqlite3_step(pStmt) ){
111931 rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
111932 if( rc!=SQLITE_OK ){
111933 vacuumFinalize(db, pStmt, pzErrMsg);
111934 return rc;
111938 return vacuumFinalize(db, pStmt, pzErrMsg);
111942 ** The VACUUM command is used to clean up the database,
111943 ** collapse free space, etc. It is modelled after the VACUUM command
111944 ** in PostgreSQL. The VACUUM command works as follows:
111946 ** (1) Create a new transient database file
111947 ** (2) Copy all content from the database being vacuumed into
111948 ** the new transient database file
111949 ** (3) Copy content from the transient database back into the
111950 ** original database.
111952 ** The transient database requires temporary disk space approximately
111953 ** equal to the size of the original database. The copy operation of
111954 ** step (3) requires additional temporary disk space approximately equal
111955 ** to the size of the original database for the rollback journal.
111956 ** Hence, temporary disk space that is approximately 2x the size of the
111957 ** original database is required. Every page of the database is written
111958 ** approximately 3 times: Once for step (2) and twice for step (3).
111959 ** Two writes per page are required in step (3) because the original
111960 ** database content must be written into the rollback journal prior to
111961 ** overwriting the database with the vacuumed content.
111963 ** Only 1x temporary space and only 1x writes would be required if
111964 ** the copy of step (3) were replace by deleting the original database
111965 ** and renaming the transient database as the original. But that will
111966 ** not work if other processes are attached to the original database.
111967 ** And a power loss in between deleting the original and renaming the
111968 ** transient would cause the database file to appear to be deleted
111969 ** following reboot.
111971 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
111972 Vdbe *v = sqlite3GetVdbe(pParse);
111973 if( v ){
111974 sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
111975 sqlite3VdbeUsesBtree(v, 0);
111977 return;
111981 ** This routine implements the OP_Vacuum opcode of the VDBE.
111983 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
111984 int rc = SQLITE_OK; /* Return code from service routines */
111985 Btree *pMain; /* The database being vacuumed */
111986 Btree *pTemp; /* The temporary database we vacuum into */
111987 char *zSql = 0; /* SQL statements */
111988 int saved_flags; /* Saved value of the db->flags */
111989 int saved_nChange; /* Saved value of db->nChange */
111990 int saved_nTotalChange; /* Saved value of db->nTotalChange */
111991 void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
111992 Db *pDb = 0; /* Database to detach at end of vacuum */
111993 int isMemDb; /* True if vacuuming a :memory: database */
111994 int nRes; /* Bytes of reserved space at the end of each page */
111995 int nDb; /* Number of attached databases */
111997 if( !db->autoCommit ){
111998 sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
111999 return SQLITE_ERROR;
112001 if( db->nVdbeActive>1 ){
112002 sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
112003 return SQLITE_ERROR;
112006 /* Save the current value of the database flags so that it can be
112007 ** restored before returning. Then set the writable-schema flag, and
112008 ** disable CHECK and foreign key constraints. */
112009 saved_flags = db->flags;
112010 saved_nChange = db->nChange;
112011 saved_nTotalChange = db->nTotalChange;
112012 saved_xTrace = db->xTrace;
112013 db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
112014 db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
112015 db->xTrace = 0;
112017 pMain = db->aDb[0].pBt;
112018 isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
112020 /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
112021 ** can be set to 'off' for this file, as it is not recovered if a crash
112022 ** occurs anyway. The integrity of the database is maintained by a
112023 ** (possibly synchronous) transaction opened on the main database before
112024 ** sqlite3BtreeCopyFile() is called.
112026 ** An optimisation would be to use a non-journaled pager.
112027 ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
112028 ** that actually made the VACUUM run slower. Very little journalling
112029 ** actually occurs when doing a vacuum since the vacuum_db is initially
112030 ** empty. Only the journal header is written. Apparently it takes more
112031 ** time to parse and run the PRAGMA to turn journalling off than it does
112032 ** to write the journal header file.
112034 nDb = db->nDb;
112035 if( sqlite3TempInMemory(db) ){
112036 zSql = "ATTACH ':memory:' AS vacuum_db;";
112037 }else{
112038 zSql = "ATTACH '' AS vacuum_db;";
112040 rc = execSql(db, pzErrMsg, zSql);
112041 if( db->nDb>nDb ){
112042 pDb = &db->aDb[db->nDb-1];
112043 assert( strcmp(pDb->zName,"vacuum_db")==0 );
112045 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112046 pTemp = db->aDb[db->nDb-1].pBt;
112048 /* The call to execSql() to attach the temp database has left the file
112049 ** locked (as there was more than one active statement when the transaction
112050 ** to read the schema was concluded. Unlock it here so that this doesn't
112051 ** cause problems for the call to BtreeSetPageSize() below. */
112052 sqlite3BtreeCommit(pTemp);
112054 nRes = sqlite3BtreeGetReserve(pMain);
112056 /* A VACUUM cannot change the pagesize of an encrypted database. */
112057 #ifdef SQLITE_HAS_CODEC
112058 if( db->nextPagesize ){
112059 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
112060 int nKey;
112061 char *zKey;
112062 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
112063 if( nKey ) db->nextPagesize = 0;
112065 #endif
112067 rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
112068 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112070 /* Begin a transaction and take an exclusive lock on the main database
112071 ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
112072 ** to ensure that we do not try to change the page-size on a WAL database.
112074 rc = execSql(db, pzErrMsg, "BEGIN;");
112075 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112076 rc = sqlite3BtreeBeginTrans(pMain, 2);
112077 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112079 /* Do not attempt to change the page size for a WAL database */
112080 if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
112081 ==PAGER_JOURNALMODE_WAL ){
112082 db->nextPagesize = 0;
112085 if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
112086 || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
112087 || NEVER(db->mallocFailed)
112089 rc = SQLITE_NOMEM;
112090 goto end_of_vacuum;
112093 #ifndef SQLITE_OMIT_AUTOVACUUM
112094 sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
112095 sqlite3BtreeGetAutoVacuum(pMain));
112096 #endif
112098 /* Query the schema of the main database. Create a mirror schema
112099 ** in the temporary database.
112101 rc = execExecSql(db, pzErrMsg,
112102 "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
112103 " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
112104 " AND coalesce(rootpage,1)>0"
112106 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112107 rc = execExecSql(db, pzErrMsg,
112108 "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
112109 " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
112110 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112111 rc = execExecSql(db, pzErrMsg,
112112 "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
112113 " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
112114 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112116 /* Loop through the tables in the main database. For each, do
112117 ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
112118 ** the contents to the temporary database.
112120 rc = execExecSql(db, pzErrMsg,
112121 "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
112122 "|| ' SELECT * FROM main.' || quote(name) || ';'"
112123 "FROM main.sqlite_master "
112124 "WHERE type = 'table' AND name!='sqlite_sequence' "
112125 " AND coalesce(rootpage,1)>0"
112127 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112129 /* Copy over the sequence table
112131 rc = execExecSql(db, pzErrMsg,
112132 "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
112133 "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
112135 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112136 rc = execExecSql(db, pzErrMsg,
112137 "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
112138 "|| ' SELECT * FROM main.' || quote(name) || ';' "
112139 "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
112141 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112144 /* Copy the triggers, views, and virtual tables from the main database
112145 ** over to the temporary database. None of these objects has any
112146 ** associated storage, so all we have to do is copy their entries
112147 ** from the SQLITE_MASTER table.
112149 rc = execSql(db, pzErrMsg,
112150 "INSERT INTO vacuum_db.sqlite_master "
112151 " SELECT type, name, tbl_name, rootpage, sql"
112152 " FROM main.sqlite_master"
112153 " WHERE type='view' OR type='trigger'"
112154 " OR (type='table' AND rootpage=0)"
112156 if( rc ) goto end_of_vacuum;
112158 /* At this point, there is a write transaction open on both the
112159 ** vacuum database and the main database. Assuming no error occurs,
112160 ** both transactions are closed by this block - the main database
112161 ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
112162 ** call to sqlite3BtreeCommit().
112165 u32 meta;
112166 int i;
112168 /* This array determines which meta meta values are preserved in the
112169 ** vacuum. Even entries are the meta value number and odd entries
112170 ** are an increment to apply to the meta value after the vacuum.
112171 ** The increment is used to increase the schema cookie so that other
112172 ** connections to the same database will know to reread the schema.
112174 static const unsigned char aCopy[] = {
112175 BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
112176 BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
112177 BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
112178 BTREE_USER_VERSION, 0, /* Preserve the user version */
112179 BTREE_APPLICATION_ID, 0, /* Preserve the application id */
112182 assert( 1==sqlite3BtreeIsInTrans(pTemp) );
112183 assert( 1==sqlite3BtreeIsInTrans(pMain) );
112185 /* Copy Btree meta values */
112186 for(i=0; i<ArraySize(aCopy); i+=2){
112187 /* GetMeta() and UpdateMeta() cannot fail in this context because
112188 ** we already have page 1 loaded into cache and marked dirty. */
112189 sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
112190 rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
112191 if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
112194 rc = sqlite3BtreeCopyFile(pMain, pTemp);
112195 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112196 rc = sqlite3BtreeCommit(pTemp);
112197 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112198 #ifndef SQLITE_OMIT_AUTOVACUUM
112199 sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
112200 #endif
112203 assert( rc==SQLITE_OK );
112204 rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
112206 end_of_vacuum:
112207 /* Restore the original value of db->flags */
112208 db->flags = saved_flags;
112209 db->nChange = saved_nChange;
112210 db->nTotalChange = saved_nTotalChange;
112211 db->xTrace = saved_xTrace;
112212 sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
112214 /* Currently there is an SQL level transaction open on the vacuum
112215 ** database. No locks are held on any other files (since the main file
112216 ** was committed at the btree level). So it safe to end the transaction
112217 ** by manually setting the autoCommit flag to true and detaching the
112218 ** vacuum database. The vacuum_db journal file is deleted when the pager
112219 ** is closed by the DETACH.
112221 db->autoCommit = 1;
112223 if( pDb ){
112224 sqlite3BtreeClose(pDb->pBt);
112225 pDb->pBt = 0;
112226 pDb->pSchema = 0;
112229 /* This both clears the schemas and reduces the size of the db->aDb[]
112230 ** array. */
112231 sqlite3ResetAllSchemasOfConnection(db);
112233 return rc;
112236 #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
112238 /************** End of vacuum.c **********************************************/
112239 /************** Begin file vtab.c ********************************************/
112241 ** 2006 June 10
112243 ** The author disclaims copyright to this source code. In place of
112244 ** a legal notice, here is a blessing:
112246 ** May you do good and not evil.
112247 ** May you find forgiveness for yourself and forgive others.
112248 ** May you share freely, never taking more than you give.
112250 *************************************************************************
112251 ** This file contains code used to help implement virtual tables.
112253 #ifndef SQLITE_OMIT_VIRTUALTABLE
112256 ** Before a virtual table xCreate() or xConnect() method is invoked, the
112257 ** sqlite3.pVtabCtx member variable is set to point to an instance of
112258 ** this struct allocated on the stack. It is used by the implementation of
112259 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
112260 ** are invoked only from within xCreate and xConnect methods.
112262 struct VtabCtx {
112263 VTable *pVTable; /* The virtual table being constructed */
112264 Table *pTab; /* The Table object to which the virtual table belongs */
112268 ** The actual function that does the work of creating a new module.
112269 ** This function implements the sqlite3_create_module() and
112270 ** sqlite3_create_module_v2() interfaces.
112272 static int createModule(
112273 sqlite3 *db, /* Database in which module is registered */
112274 const char *zName, /* Name assigned to this module */
112275 const sqlite3_module *pModule, /* The definition of the module */
112276 void *pAux, /* Context pointer for xCreate/xConnect */
112277 void (*xDestroy)(void *) /* Module destructor function */
112279 int rc = SQLITE_OK;
112280 int nName;
112282 sqlite3_mutex_enter(db->mutex);
112283 nName = sqlite3Strlen30(zName);
112284 if( sqlite3HashFind(&db->aModule, zName) ){
112285 rc = SQLITE_MISUSE_BKPT;
112286 }else{
112287 Module *pMod;
112288 pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
112289 if( pMod ){
112290 Module *pDel;
112291 char *zCopy = (char *)(&pMod[1]);
112292 memcpy(zCopy, zName, nName+1);
112293 pMod->zName = zCopy;
112294 pMod->pModule = pModule;
112295 pMod->pAux = pAux;
112296 pMod->xDestroy = xDestroy;
112297 pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
112298 assert( pDel==0 || pDel==pMod );
112299 if( pDel ){
112300 db->mallocFailed = 1;
112301 sqlite3DbFree(db, pDel);
112305 rc = sqlite3ApiExit(db, rc);
112306 if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
112308 sqlite3_mutex_leave(db->mutex);
112309 return rc;
112314 ** External API function used to create a new virtual-table module.
112316 SQLITE_API int sqlite3_create_module(
112317 sqlite3 *db, /* Database in which module is registered */
112318 const char *zName, /* Name assigned to this module */
112319 const sqlite3_module *pModule, /* The definition of the module */
112320 void *pAux /* Context pointer for xCreate/xConnect */
112322 return createModule(db, zName, pModule, pAux, 0);
112326 ** External API function used to create a new virtual-table module.
112328 SQLITE_API int sqlite3_create_module_v2(
112329 sqlite3 *db, /* Database in which module is registered */
112330 const char *zName, /* Name assigned to this module */
112331 const sqlite3_module *pModule, /* The definition of the module */
112332 void *pAux, /* Context pointer for xCreate/xConnect */
112333 void (*xDestroy)(void *) /* Module destructor function */
112335 return createModule(db, zName, pModule, pAux, xDestroy);
112339 ** Lock the virtual table so that it cannot be disconnected.
112340 ** Locks nest. Every lock should have a corresponding unlock.
112341 ** If an unlock is omitted, resources leaks will occur.
112343 ** If a disconnect is attempted while a virtual table is locked,
112344 ** the disconnect is deferred until all locks have been removed.
112346 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
112347 pVTab->nRef++;
112352 ** pTab is a pointer to a Table structure representing a virtual-table.
112353 ** Return a pointer to the VTable object used by connection db to access
112354 ** this virtual-table, if one has been created, or NULL otherwise.
112356 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
112357 VTable *pVtab;
112358 assert( IsVirtual(pTab) );
112359 for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
112360 return pVtab;
112364 ** Decrement the ref-count on a virtual table object. When the ref-count
112365 ** reaches zero, call the xDisconnect() method to delete the object.
112367 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
112368 sqlite3 *db = pVTab->db;
112370 assert( db );
112371 assert( pVTab->nRef>0 );
112372 assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
112374 pVTab->nRef--;
112375 if( pVTab->nRef==0 ){
112376 sqlite3_vtab *p = pVTab->pVtab;
112377 if( p ){
112378 p->pModule->xDisconnect(p);
112380 sqlite3DbFree(db, pVTab);
112385 ** Table p is a virtual table. This function moves all elements in the
112386 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
112387 ** database connections to be disconnected at the next opportunity.
112388 ** Except, if argument db is not NULL, then the entry associated with
112389 ** connection db is left in the p->pVTable list.
112391 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
112392 VTable *pRet = 0;
112393 VTable *pVTable = p->pVTable;
112394 p->pVTable = 0;
112396 /* Assert that the mutex (if any) associated with the BtShared database
112397 ** that contains table p is held by the caller. See header comments
112398 ** above function sqlite3VtabUnlockList() for an explanation of why
112399 ** this makes it safe to access the sqlite3.pDisconnect list of any
112400 ** database connection that may have an entry in the p->pVTable list.
112402 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
112404 while( pVTable ){
112405 sqlite3 *db2 = pVTable->db;
112406 VTable *pNext = pVTable->pNext;
112407 assert( db2 );
112408 if( db2==db ){
112409 pRet = pVTable;
112410 p->pVTable = pRet;
112411 pRet->pNext = 0;
112412 }else{
112413 pVTable->pNext = db2->pDisconnect;
112414 db2->pDisconnect = pVTable;
112416 pVTable = pNext;
112419 assert( !db || pRet );
112420 return pRet;
112424 ** Table *p is a virtual table. This function removes the VTable object
112425 ** for table *p associated with database connection db from the linked
112426 ** list in p->pVTab. It also decrements the VTable ref count. This is
112427 ** used when closing database connection db to free all of its VTable
112428 ** objects without disturbing the rest of the Schema object (which may
112429 ** be being used by other shared-cache connections).
112431 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
112432 VTable **ppVTab;
112434 assert( IsVirtual(p) );
112435 assert( sqlite3BtreeHoldsAllMutexes(db) );
112436 assert( sqlite3_mutex_held(db->mutex) );
112438 for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
112439 if( (*ppVTab)->db==db ){
112440 VTable *pVTab = *ppVTab;
112441 *ppVTab = pVTab->pNext;
112442 sqlite3VtabUnlock(pVTab);
112443 break;
112450 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
112452 ** This function may only be called when the mutexes associated with all
112453 ** shared b-tree databases opened using connection db are held by the
112454 ** caller. This is done to protect the sqlite3.pDisconnect list. The
112455 ** sqlite3.pDisconnect list is accessed only as follows:
112457 ** 1) By this function. In this case, all BtShared mutexes and the mutex
112458 ** associated with the database handle itself must be held.
112460 ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
112461 ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
112462 ** associated with the database the virtual table is stored in is held
112463 ** or, if the virtual table is stored in a non-sharable database, then
112464 ** the database handle mutex is held.
112466 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
112467 ** by multiple threads. It is thread-safe.
112469 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
112470 VTable *p = db->pDisconnect;
112471 db->pDisconnect = 0;
112473 assert( sqlite3BtreeHoldsAllMutexes(db) );
112474 assert( sqlite3_mutex_held(db->mutex) );
112476 if( p ){
112477 sqlite3ExpirePreparedStatements(db);
112479 VTable *pNext = p->pNext;
112480 sqlite3VtabUnlock(p);
112481 p = pNext;
112482 }while( p );
112487 ** Clear any and all virtual-table information from the Table record.
112488 ** This routine is called, for example, just before deleting the Table
112489 ** record.
112491 ** Since it is a virtual-table, the Table structure contains a pointer
112492 ** to the head of a linked list of VTable structures. Each VTable
112493 ** structure is associated with a single sqlite3* user of the schema.
112494 ** The reference count of the VTable structure associated with database
112495 ** connection db is decremented immediately (which may lead to the
112496 ** structure being xDisconnected and free). Any other VTable structures
112497 ** in the list are moved to the sqlite3.pDisconnect list of the associated
112498 ** database connection.
112500 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
112501 if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
112502 if( p->azModuleArg ){
112503 int i;
112504 for(i=0; i<p->nModuleArg; i++){
112505 if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
112507 sqlite3DbFree(db, p->azModuleArg);
112512 ** Add a new module argument to pTable->azModuleArg[].
112513 ** The string is not copied - the pointer is stored. The
112514 ** string will be freed automatically when the table is
112515 ** deleted.
112517 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
112518 int i = pTable->nModuleArg++;
112519 int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
112520 char **azModuleArg;
112521 azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
112522 if( azModuleArg==0 ){
112523 int j;
112524 for(j=0; j<i; j++){
112525 sqlite3DbFree(db, pTable->azModuleArg[j]);
112527 sqlite3DbFree(db, zArg);
112528 sqlite3DbFree(db, pTable->azModuleArg);
112529 pTable->nModuleArg = 0;
112530 }else{
112531 azModuleArg[i] = zArg;
112532 azModuleArg[i+1] = 0;
112534 pTable->azModuleArg = azModuleArg;
112538 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
112539 ** statement. The module name has been parsed, but the optional list
112540 ** of parameters that follow the module name are still pending.
112542 SQLITE_PRIVATE void sqlite3VtabBeginParse(
112543 Parse *pParse, /* Parsing context */
112544 Token *pName1, /* Name of new table, or database name */
112545 Token *pName2, /* Name of new table or NULL */
112546 Token *pModuleName, /* Name of the module for the virtual table */
112547 int ifNotExists /* No error if the table already exists */
112549 int iDb; /* The database the table is being created in */
112550 Table *pTable; /* The new virtual table */
112551 sqlite3 *db; /* Database connection */
112553 sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
112554 pTable = pParse->pNewTable;
112555 if( pTable==0 ) return;
112556 assert( 0==pTable->pIndex );
112558 db = pParse->db;
112559 iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
112560 assert( iDb>=0 );
112562 pTable->tabFlags |= TF_Virtual;
112563 pTable->nModuleArg = 0;
112564 addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
112565 addModuleArgument(db, pTable, 0);
112566 addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
112567 pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
112569 #ifndef SQLITE_OMIT_AUTHORIZATION
112570 /* Creating a virtual table invokes the authorization callback twice.
112571 ** The first invocation, to obtain permission to INSERT a row into the
112572 ** sqlite_master table, has already been made by sqlite3StartTable().
112573 ** The second call, to obtain permission to create the table, is made now.
112575 if( pTable->azModuleArg ){
112576 sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
112577 pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
112579 #endif
112583 ** This routine takes the module argument that has been accumulating
112584 ** in pParse->zArg[] and appends it to the list of arguments on the
112585 ** virtual table currently under construction in pParse->pTable.
112587 static void addArgumentToVtab(Parse *pParse){
112588 if( pParse->sArg.z && pParse->pNewTable ){
112589 const char *z = (const char*)pParse->sArg.z;
112590 int n = pParse->sArg.n;
112591 sqlite3 *db = pParse->db;
112592 addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
112597 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
112598 ** has been completely parsed.
112600 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
112601 Table *pTab = pParse->pNewTable; /* The table being constructed */
112602 sqlite3 *db = pParse->db; /* The database connection */
112604 if( pTab==0 ) return;
112605 addArgumentToVtab(pParse);
112606 pParse->sArg.z = 0;
112607 if( pTab->nModuleArg<1 ) return;
112609 /* If the CREATE VIRTUAL TABLE statement is being entered for the
112610 ** first time (in other words if the virtual table is actually being
112611 ** created now instead of just being read out of sqlite_master) then
112612 ** do additional initialization work and store the statement text
112613 ** in the sqlite_master table.
112615 if( !db->init.busy ){
112616 char *zStmt;
112617 char *zWhere;
112618 int iDb;
112619 Vdbe *v;
112621 /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
112622 if( pEnd ){
112623 pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
112625 zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
112627 /* A slot for the record has already been allocated in the
112628 ** SQLITE_MASTER table. We just need to update that slot with all
112629 ** the information we've collected.
112631 ** The VM register number pParse->regRowid holds the rowid of an
112632 ** entry in the sqlite_master table tht was created for this vtab
112633 ** by sqlite3StartTable().
112635 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
112636 sqlite3NestedParse(pParse,
112637 "UPDATE %Q.%s "
112638 "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
112639 "WHERE rowid=#%d",
112640 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
112641 pTab->zName,
112642 pTab->zName,
112643 zStmt,
112644 pParse->regRowid
112646 sqlite3DbFree(db, zStmt);
112647 v = sqlite3GetVdbe(pParse);
112648 sqlite3ChangeCookie(pParse, iDb);
112650 sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
112651 zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
112652 sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
112653 sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
112654 pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
112657 /* If we are rereading the sqlite_master table create the in-memory
112658 ** record of the table. The xConnect() method is not called until
112659 ** the first time the virtual table is used in an SQL statement. This
112660 ** allows a schema that contains virtual tables to be loaded before
112661 ** the required virtual table implementations are registered. */
112662 else {
112663 Table *pOld;
112664 Schema *pSchema = pTab->pSchema;
112665 const char *zName = pTab->zName;
112666 assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
112667 pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
112668 if( pOld ){
112669 db->mallocFailed = 1;
112670 assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
112671 return;
112673 pParse->pNewTable = 0;
112678 ** The parser calls this routine when it sees the first token
112679 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
112681 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
112682 addArgumentToVtab(pParse);
112683 pParse->sArg.z = 0;
112684 pParse->sArg.n = 0;
112688 ** The parser calls this routine for each token after the first token
112689 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
112691 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
112692 Token *pArg = &pParse->sArg;
112693 if( pArg->z==0 ){
112694 pArg->z = p->z;
112695 pArg->n = p->n;
112696 }else{
112697 assert(pArg->z < p->z);
112698 pArg->n = (int)(&p->z[p->n] - pArg->z);
112703 ** Invoke a virtual table constructor (either xCreate or xConnect). The
112704 ** pointer to the function to invoke is passed as the fourth parameter
112705 ** to this procedure.
112707 static int vtabCallConstructor(
112708 sqlite3 *db,
112709 Table *pTab,
112710 Module *pMod,
112711 int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
112712 char **pzErr
112714 VtabCtx sCtx, *pPriorCtx;
112715 VTable *pVTable;
112716 int rc;
112717 const char *const*azArg = (const char *const*)pTab->azModuleArg;
112718 int nArg = pTab->nModuleArg;
112719 char *zErr = 0;
112720 char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
112721 int iDb;
112723 if( !zModuleName ){
112724 return SQLITE_NOMEM;
112727 pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
112728 if( !pVTable ){
112729 sqlite3DbFree(db, zModuleName);
112730 return SQLITE_NOMEM;
112732 pVTable->db = db;
112733 pVTable->pMod = pMod;
112735 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
112736 pTab->azModuleArg[1] = db->aDb[iDb].zName;
112738 /* Invoke the virtual table constructor */
112739 assert( &db->pVtabCtx );
112740 assert( xConstruct );
112741 sCtx.pTab = pTab;
112742 sCtx.pVTable = pVTable;
112743 pPriorCtx = db->pVtabCtx;
112744 db->pVtabCtx = &sCtx;
112745 rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
112746 db->pVtabCtx = pPriorCtx;
112747 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
112749 if( SQLITE_OK!=rc ){
112750 if( zErr==0 ){
112751 *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
112752 }else {
112753 *pzErr = sqlite3MPrintf(db, "%s", zErr);
112754 sqlite3_free(zErr);
112756 sqlite3DbFree(db, pVTable);
112757 }else if( ALWAYS(pVTable->pVtab) ){
112758 /* Justification of ALWAYS(): A correct vtab constructor must allocate
112759 ** the sqlite3_vtab object if successful. */
112760 memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
112761 pVTable->pVtab->pModule = pMod->pModule;
112762 pVTable->nRef = 1;
112763 if( sCtx.pTab ){
112764 const char *zFormat = "vtable constructor did not declare schema: %s";
112765 *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
112766 sqlite3VtabUnlock(pVTable);
112767 rc = SQLITE_ERROR;
112768 }else{
112769 int iCol;
112770 /* If everything went according to plan, link the new VTable structure
112771 ** into the linked list headed by pTab->pVTable. Then loop through the
112772 ** columns of the table to see if any of them contain the token "hidden".
112773 ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
112774 ** the type string. */
112775 pVTable->pNext = pTab->pVTable;
112776 pTab->pVTable = pVTable;
112778 for(iCol=0; iCol<pTab->nCol; iCol++){
112779 char *zType = pTab->aCol[iCol].zType;
112780 int nType;
112781 int i = 0;
112782 if( !zType ) continue;
112783 nType = sqlite3Strlen30(zType);
112784 if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
112785 for(i=0; i<nType; i++){
112786 if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
112787 && (zType[i+7]=='\0' || zType[i+7]==' ')
112790 break;
112794 if( i<nType ){
112795 int j;
112796 int nDel = 6 + (zType[i+6] ? 1 : 0);
112797 for(j=i; (j+nDel)<=nType; j++){
112798 zType[j] = zType[j+nDel];
112800 if( zType[i]=='\0' && i>0 ){
112801 assert(zType[i-1]==' ');
112802 zType[i-1] = '\0';
112804 pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
112810 sqlite3DbFree(db, zModuleName);
112811 return rc;
112815 ** This function is invoked by the parser to call the xConnect() method
112816 ** of the virtual table pTab. If an error occurs, an error code is returned
112817 ** and an error left in pParse.
112819 ** This call is a no-op if table pTab is not a virtual table.
112821 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
112822 sqlite3 *db = pParse->db;
112823 const char *zMod;
112824 Module *pMod;
112825 int rc;
112827 assert( pTab );
112828 if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
112829 return SQLITE_OK;
112832 /* Locate the required virtual table module */
112833 zMod = pTab->azModuleArg[0];
112834 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
112836 if( !pMod ){
112837 const char *zModule = pTab->azModuleArg[0];
112838 sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
112839 rc = SQLITE_ERROR;
112840 }else{
112841 char *zErr = 0;
112842 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
112843 if( rc!=SQLITE_OK ){
112844 sqlite3ErrorMsg(pParse, "%s", zErr);
112846 sqlite3DbFree(db, zErr);
112849 return rc;
112852 ** Grow the db->aVTrans[] array so that there is room for at least one
112853 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
112855 static int growVTrans(sqlite3 *db){
112856 const int ARRAY_INCR = 5;
112858 /* Grow the sqlite3.aVTrans array if required */
112859 if( (db->nVTrans%ARRAY_INCR)==0 ){
112860 VTable **aVTrans;
112861 int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
112862 aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
112863 if( !aVTrans ){
112864 return SQLITE_NOMEM;
112866 memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
112867 db->aVTrans = aVTrans;
112870 return SQLITE_OK;
112874 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
112875 ** have already been reserved using growVTrans().
112877 static void addToVTrans(sqlite3 *db, VTable *pVTab){
112878 /* Add pVtab to the end of sqlite3.aVTrans */
112879 db->aVTrans[db->nVTrans++] = pVTab;
112880 sqlite3VtabLock(pVTab);
112884 ** This function is invoked by the vdbe to call the xCreate method
112885 ** of the virtual table named zTab in database iDb.
112887 ** If an error occurs, *pzErr is set to point an an English language
112888 ** description of the error and an SQLITE_XXX error code is returned.
112889 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
112891 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
112892 int rc = SQLITE_OK;
112893 Table *pTab;
112894 Module *pMod;
112895 const char *zMod;
112897 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
112898 assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
112900 /* Locate the required virtual table module */
112901 zMod = pTab->azModuleArg[0];
112902 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
112904 /* If the module has been registered and includes a Create method,
112905 ** invoke it now. If the module has not been registered, return an
112906 ** error. Otherwise, do nothing.
112908 if( !pMod ){
112909 *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
112910 rc = SQLITE_ERROR;
112911 }else{
112912 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
112915 /* Justification of ALWAYS(): The xConstructor method is required to
112916 ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
112917 if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
112918 rc = growVTrans(db);
112919 if( rc==SQLITE_OK ){
112920 addToVTrans(db, sqlite3GetVTable(db, pTab));
112924 return rc;
112928 ** This function is used to set the schema of a virtual table. It is only
112929 ** valid to call this function from within the xCreate() or xConnect() of a
112930 ** virtual table module.
112932 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
112933 Parse *pParse;
112935 int rc = SQLITE_OK;
112936 Table *pTab;
112937 char *zErr = 0;
112939 sqlite3_mutex_enter(db->mutex);
112940 if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
112941 sqlite3Error(db, SQLITE_MISUSE);
112942 sqlite3_mutex_leave(db->mutex);
112943 return SQLITE_MISUSE_BKPT;
112945 assert( (pTab->tabFlags & TF_Virtual)!=0 );
112947 pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
112948 if( pParse==0 ){
112949 rc = SQLITE_NOMEM;
112950 }else{
112951 pParse->declareVtab = 1;
112952 pParse->db = db;
112953 pParse->nQueryLoop = 1;
112955 if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
112956 && pParse->pNewTable
112957 && !db->mallocFailed
112958 && !pParse->pNewTable->pSelect
112959 && (pParse->pNewTable->tabFlags & TF_Virtual)==0
112961 if( !pTab->aCol ){
112962 pTab->aCol = pParse->pNewTable->aCol;
112963 pTab->nCol = pParse->pNewTable->nCol;
112964 pParse->pNewTable->nCol = 0;
112965 pParse->pNewTable->aCol = 0;
112967 db->pVtabCtx->pTab = 0;
112968 }else{
112969 sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
112970 sqlite3DbFree(db, zErr);
112971 rc = SQLITE_ERROR;
112973 pParse->declareVtab = 0;
112975 if( pParse->pVdbe ){
112976 sqlite3VdbeFinalize(pParse->pVdbe);
112978 sqlite3DeleteTable(db, pParse->pNewTable);
112979 sqlite3ParserReset(pParse);
112980 sqlite3StackFree(db, pParse);
112983 assert( (rc&0xff)==rc );
112984 rc = sqlite3ApiExit(db, rc);
112985 sqlite3_mutex_leave(db->mutex);
112986 return rc;
112990 ** This function is invoked by the vdbe to call the xDestroy method
112991 ** of the virtual table named zTab in database iDb. This occurs
112992 ** when a DROP TABLE is mentioned.
112994 ** This call is a no-op if zTab is not a virtual table.
112996 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
112997 int rc = SQLITE_OK;
112998 Table *pTab;
113000 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
113001 if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
113002 VTable *p = vtabDisconnectAll(db, pTab);
113004 assert( rc==SQLITE_OK );
113005 rc = p->pMod->pModule->xDestroy(p->pVtab);
113007 /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
113008 if( rc==SQLITE_OK ){
113009 assert( pTab->pVTable==p && p->pNext==0 );
113010 p->pVtab = 0;
113011 pTab->pVTable = 0;
113012 sqlite3VtabUnlock(p);
113016 return rc;
113020 ** This function invokes either the xRollback or xCommit method
113021 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
113022 ** called is identified by the second argument, "offset", which is
113023 ** the offset of the method to call in the sqlite3_module structure.
113025 ** The array is cleared after invoking the callbacks.
113027 static void callFinaliser(sqlite3 *db, int offset){
113028 int i;
113029 if( db->aVTrans ){
113030 for(i=0; i<db->nVTrans; i++){
113031 VTable *pVTab = db->aVTrans[i];
113032 sqlite3_vtab *p = pVTab->pVtab;
113033 if( p ){
113034 int (*x)(sqlite3_vtab *);
113035 x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
113036 if( x ) x(p);
113038 pVTab->iSavepoint = 0;
113039 sqlite3VtabUnlock(pVTab);
113041 sqlite3DbFree(db, db->aVTrans);
113042 db->nVTrans = 0;
113043 db->aVTrans = 0;
113048 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
113049 ** array. Return the error code for the first error that occurs, or
113050 ** SQLITE_OK if all xSync operations are successful.
113052 ** If an error message is available, leave it in p->zErrMsg.
113054 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
113055 int i;
113056 int rc = SQLITE_OK;
113057 VTable **aVTrans = db->aVTrans;
113059 db->aVTrans = 0;
113060 for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
113061 int (*x)(sqlite3_vtab *);
113062 sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
113063 if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
113064 rc = x(pVtab);
113065 sqlite3VtabImportErrmsg(p, pVtab);
113068 db->aVTrans = aVTrans;
113069 return rc;
113073 ** Invoke the xRollback method of all virtual tables in the
113074 ** sqlite3.aVTrans array. Then clear the array itself.
113076 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
113077 callFinaliser(db, offsetof(sqlite3_module,xRollback));
113078 return SQLITE_OK;
113082 ** Invoke the xCommit method of all virtual tables in the
113083 ** sqlite3.aVTrans array. Then clear the array itself.
113085 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
113086 callFinaliser(db, offsetof(sqlite3_module,xCommit));
113087 return SQLITE_OK;
113091 ** If the virtual table pVtab supports the transaction interface
113092 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
113093 ** not currently open, invoke the xBegin method now.
113095 ** If the xBegin call is successful, place the sqlite3_vtab pointer
113096 ** in the sqlite3.aVTrans array.
113098 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
113099 int rc = SQLITE_OK;
113100 const sqlite3_module *pModule;
113102 /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
113103 ** than zero, then this function is being called from within a
113104 ** virtual module xSync() callback. It is illegal to write to
113105 ** virtual module tables in this case, so return SQLITE_LOCKED.
113107 if( sqlite3VtabInSync(db) ){
113108 return SQLITE_LOCKED;
113110 if( !pVTab ){
113111 return SQLITE_OK;
113113 pModule = pVTab->pVtab->pModule;
113115 if( pModule->xBegin ){
113116 int i;
113118 /* If pVtab is already in the aVTrans array, return early */
113119 for(i=0; i<db->nVTrans; i++){
113120 if( db->aVTrans[i]==pVTab ){
113121 return SQLITE_OK;
113125 /* Invoke the xBegin method. If successful, add the vtab to the
113126 ** sqlite3.aVTrans[] array. */
113127 rc = growVTrans(db);
113128 if( rc==SQLITE_OK ){
113129 rc = pModule->xBegin(pVTab->pVtab);
113130 if( rc==SQLITE_OK ){
113131 addToVTrans(db, pVTab);
113135 return rc;
113139 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
113140 ** virtual tables that currently have an open transaction. Pass iSavepoint
113141 ** as the second argument to the virtual table method invoked.
113143 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
113144 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
113145 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
113146 ** an open transaction is invoked.
113148 ** If any virtual table method returns an error code other than SQLITE_OK,
113149 ** processing is abandoned and the error returned to the caller of this
113150 ** function immediately. If all calls to virtual table methods are successful,
113151 ** SQLITE_OK is returned.
113153 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
113154 int rc = SQLITE_OK;
113156 assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
113157 assert( iSavepoint>=0 );
113158 if( db->aVTrans ){
113159 int i;
113160 for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
113161 VTable *pVTab = db->aVTrans[i];
113162 const sqlite3_module *pMod = pVTab->pMod->pModule;
113163 if( pVTab->pVtab && pMod->iVersion>=2 ){
113164 int (*xMethod)(sqlite3_vtab *, int);
113165 switch( op ){
113166 case SAVEPOINT_BEGIN:
113167 xMethod = pMod->xSavepoint;
113168 pVTab->iSavepoint = iSavepoint+1;
113169 break;
113170 case SAVEPOINT_ROLLBACK:
113171 xMethod = pMod->xRollbackTo;
113172 break;
113173 default:
113174 xMethod = pMod->xRelease;
113175 break;
113177 if( xMethod && pVTab->iSavepoint>iSavepoint ){
113178 rc = xMethod(pVTab->pVtab, iSavepoint);
113183 return rc;
113187 ** The first parameter (pDef) is a function implementation. The
113188 ** second parameter (pExpr) is the first argument to this function.
113189 ** If pExpr is a column in a virtual table, then let the virtual
113190 ** table implementation have an opportunity to overload the function.
113192 ** This routine is used to allow virtual table implementations to
113193 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
113195 ** Return either the pDef argument (indicating no change) or a
113196 ** new FuncDef structure that is marked as ephemeral using the
113197 ** SQLITE_FUNC_EPHEM flag.
113199 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
113200 sqlite3 *db, /* Database connection for reporting malloc problems */
113201 FuncDef *pDef, /* Function to possibly overload */
113202 int nArg, /* Number of arguments to the function */
113203 Expr *pExpr /* First argument to the function */
113205 Table *pTab;
113206 sqlite3_vtab *pVtab;
113207 sqlite3_module *pMod;
113208 void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
113209 void *pArg = 0;
113210 FuncDef *pNew;
113211 int rc = 0;
113212 char *zLowerName;
113213 unsigned char *z;
113216 /* Check to see the left operand is a column in a virtual table */
113217 if( NEVER(pExpr==0) ) return pDef;
113218 if( pExpr->op!=TK_COLUMN ) return pDef;
113219 pTab = pExpr->pTab;
113220 if( NEVER(pTab==0) ) return pDef;
113221 if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
113222 pVtab = sqlite3GetVTable(db, pTab)->pVtab;
113223 assert( pVtab!=0 );
113224 assert( pVtab->pModule!=0 );
113225 pMod = (sqlite3_module *)pVtab->pModule;
113226 if( pMod->xFindFunction==0 ) return pDef;
113228 /* Call the xFindFunction method on the virtual table implementation
113229 ** to see if the implementation wants to overload this function
113231 zLowerName = sqlite3DbStrDup(db, pDef->zName);
113232 if( zLowerName ){
113233 for(z=(unsigned char*)zLowerName; *z; z++){
113234 *z = sqlite3UpperToLower[*z];
113236 rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
113237 sqlite3DbFree(db, zLowerName);
113239 if( rc==0 ){
113240 return pDef;
113243 /* Create a new ephemeral function definition for the overloaded
113244 ** function */
113245 pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
113246 + sqlite3Strlen30(pDef->zName) + 1);
113247 if( pNew==0 ){
113248 return pDef;
113250 *pNew = *pDef;
113251 pNew->zName = (char *)&pNew[1];
113252 memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
113253 pNew->xFunc = xFunc;
113254 pNew->pUserData = pArg;
113255 pNew->funcFlags |= SQLITE_FUNC_EPHEM;
113256 return pNew;
113260 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
113261 ** array so that an OP_VBegin will get generated for it. Add pTab to the
113262 ** array if it is missing. If pTab is already in the array, this routine
113263 ** is a no-op.
113265 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
113266 Parse *pToplevel = sqlite3ParseToplevel(pParse);
113267 int i, n;
113268 Table **apVtabLock;
113270 assert( IsVirtual(pTab) );
113271 for(i=0; i<pToplevel->nVtabLock; i++){
113272 if( pTab==pToplevel->apVtabLock[i] ) return;
113274 n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
113275 apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
113276 if( apVtabLock ){
113277 pToplevel->apVtabLock = apVtabLock;
113278 pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
113279 }else{
113280 pToplevel->db->mallocFailed = 1;
113285 ** Return the ON CONFLICT resolution mode in effect for the virtual
113286 ** table update operation currently in progress.
113288 ** The results of this routine are undefined unless it is called from
113289 ** within an xUpdate method.
113291 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
113292 static const unsigned char aMap[] = {
113293 SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
113295 assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
113296 assert( OE_Ignore==4 && OE_Replace==5 );
113297 assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
113298 return (int)aMap[db->vtabOnConflict-1];
113302 ** Call from within the xCreate() or xConnect() methods to provide
113303 ** the SQLite core with additional information about the behavior
113304 ** of the virtual table being implemented.
113306 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
113307 va_list ap;
113308 int rc = SQLITE_OK;
113310 sqlite3_mutex_enter(db->mutex);
113312 va_start(ap, op);
113313 switch( op ){
113314 case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
113315 VtabCtx *p = db->pVtabCtx;
113316 if( !p ){
113317 rc = SQLITE_MISUSE_BKPT;
113318 }else{
113319 assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
113320 p->pVTable->bConstraint = (u8)va_arg(ap, int);
113322 break;
113324 default:
113325 rc = SQLITE_MISUSE_BKPT;
113326 break;
113328 va_end(ap);
113330 if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
113331 sqlite3_mutex_leave(db->mutex);
113332 return rc;
113335 #endif /* SQLITE_OMIT_VIRTUALTABLE */
113337 /************** End of vtab.c ************************************************/
113338 /************** Begin file where.c *******************************************/
113340 ** 2001 September 15
113342 ** The author disclaims copyright to this source code. In place of
113343 ** a legal notice, here is a blessing:
113345 ** May you do good and not evil.
113346 ** May you find forgiveness for yourself and forgive others.
113347 ** May you share freely, never taking more than you give.
113349 *************************************************************************
113350 ** This module contains C code that generates VDBE code used to process
113351 ** the WHERE clause of SQL statements. This module is responsible for
113352 ** generating the code that loops through a table looking for applicable
113353 ** rows. Indices are selected and used to speed the search when doing
113354 ** so is applicable. Because this module is responsible for selecting
113355 ** indices, you might also think of this module as the "query optimizer".
113357 /************** Include whereInt.h in the middle of where.c ******************/
113358 /************** Begin file whereInt.h ****************************************/
113360 ** 2013-11-12
113362 ** The author disclaims copyright to this source code. In place of
113363 ** a legal notice, here is a blessing:
113365 ** May you do good and not evil.
113366 ** May you find forgiveness for yourself and forgive others.
113367 ** May you share freely, never taking more than you give.
113369 *************************************************************************
113371 ** This file contains structure and macro definitions for the query
113372 ** planner logic in "where.c". These definitions are broken out into
113373 ** a separate source file for easier editing.
113377 ** Trace output macros
113379 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
113380 /***/ int sqlite3WhereTrace = 0;
113381 #endif
113382 #if defined(SQLITE_DEBUG) \
113383 && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
113384 # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
113385 # define WHERETRACE_ENABLED 1
113386 #else
113387 # define WHERETRACE(K,X)
113388 #endif
113390 /* Forward references
113392 typedef struct WhereClause WhereClause;
113393 typedef struct WhereMaskSet WhereMaskSet;
113394 typedef struct WhereOrInfo WhereOrInfo;
113395 typedef struct WhereAndInfo WhereAndInfo;
113396 typedef struct WhereLevel WhereLevel;
113397 typedef struct WhereLoop WhereLoop;
113398 typedef struct WherePath WherePath;
113399 typedef struct WhereTerm WhereTerm;
113400 typedef struct WhereLoopBuilder WhereLoopBuilder;
113401 typedef struct WhereScan WhereScan;
113402 typedef struct WhereOrCost WhereOrCost;
113403 typedef struct WhereOrSet WhereOrSet;
113406 ** This object contains information needed to implement a single nested
113407 ** loop in WHERE clause.
113409 ** Contrast this object with WhereLoop. This object describes the
113410 ** implementation of the loop. WhereLoop describes the algorithm.
113411 ** This object contains a pointer to the WhereLoop algorithm as one of
113412 ** its elements.
113414 ** The WhereInfo object contains a single instance of this object for
113415 ** each term in the FROM clause (which is to say, for each of the
113416 ** nested loops as implemented). The order of WhereLevel objects determines
113417 ** the loop nested order, with WhereInfo.a[0] being the outer loop and
113418 ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
113420 struct WhereLevel {
113421 int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
113422 int iTabCur; /* The VDBE cursor used to access the table */
113423 int iIdxCur; /* The VDBE cursor used to access pIdx */
113424 int addrBrk; /* Jump here to break out of the loop */
113425 int addrNxt; /* Jump here to start the next IN combination */
113426 int addrSkip; /* Jump here for next iteration of skip-scan */
113427 int addrCont; /* Jump here to continue with the next loop cycle */
113428 int addrFirst; /* First instruction of interior of the loop */
113429 int addrBody; /* Beginning of the body of this loop */
113430 u8 iFrom; /* Which entry in the FROM clause */
113431 u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
113432 int p1, p2; /* Operands of the opcode used to ends the loop */
113433 union { /* Information that depends on pWLoop->wsFlags */
113434 struct {
113435 int nIn; /* Number of entries in aInLoop[] */
113436 struct InLoop {
113437 int iCur; /* The VDBE cursor used by this IN operator */
113438 int addrInTop; /* Top of the IN loop */
113439 u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
113440 } *aInLoop; /* Information about each nested IN operator */
113441 } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
113442 Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
113444 struct WhereLoop *pWLoop; /* The selected WhereLoop object */
113445 Bitmask notReady; /* FROM entries not usable at this level */
113449 ** Each instance of this object represents an algorithm for evaluating one
113450 ** term of a join. Every term of the FROM clause will have at least
113451 ** one corresponding WhereLoop object (unless INDEXED BY constraints
113452 ** prevent a query solution - which is an error) and many terms of the
113453 ** FROM clause will have multiple WhereLoop objects, each describing a
113454 ** potential way of implementing that FROM-clause term, together with
113455 ** dependencies and cost estimates for using the chosen algorithm.
113457 ** Query planning consists of building up a collection of these WhereLoop
113458 ** objects, then computing a particular sequence of WhereLoop objects, with
113459 ** one WhereLoop object per FROM clause term, that satisfy all dependencies
113460 ** and that minimize the overall cost.
113462 struct WhereLoop {
113463 Bitmask prereq; /* Bitmask of other loops that must run first */
113464 Bitmask maskSelf; /* Bitmask identifying table iTab */
113465 #ifdef SQLITE_DEBUG
113466 char cId; /* Symbolic ID of this loop for debugging use */
113467 #endif
113468 u8 iTab; /* Position in FROM clause of table for this loop */
113469 u8 iSortIdx; /* Sorting index number. 0==None */
113470 LogEst rSetup; /* One-time setup cost (ex: create transient index) */
113471 LogEst rRun; /* Cost of running each loop */
113472 LogEst nOut; /* Estimated number of output rows */
113473 union {
113474 struct { /* Information for internal btree tables */
113475 u16 nEq; /* Number of equality constraints */
113476 u16 nSkip; /* Number of initial index columns to skip */
113477 Index *pIndex; /* Index used, or NULL */
113478 } btree;
113479 struct { /* Information for virtual tables */
113480 int idxNum; /* Index number */
113481 u8 needFree; /* True if sqlite3_free(idxStr) is needed */
113482 i8 isOrdered; /* True if satisfies ORDER BY */
113483 u16 omitMask; /* Terms that may be omitted */
113484 char *idxStr; /* Index identifier string */
113485 } vtab;
113487 u32 wsFlags; /* WHERE_* flags describing the plan */
113488 u16 nLTerm; /* Number of entries in aLTerm[] */
113489 /**** whereLoopXfer() copies fields above ***********************/
113490 # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
113491 u16 nLSlot; /* Number of slots allocated for aLTerm[] */
113492 WhereTerm **aLTerm; /* WhereTerms used */
113493 WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
113494 WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
113497 /* This object holds the prerequisites and the cost of running a
113498 ** subquery on one operand of an OR operator in the WHERE clause.
113499 ** See WhereOrSet for additional information
113501 struct WhereOrCost {
113502 Bitmask prereq; /* Prerequisites */
113503 LogEst rRun; /* Cost of running this subquery */
113504 LogEst nOut; /* Number of outputs for this subquery */
113507 /* The WhereOrSet object holds a set of possible WhereOrCosts that
113508 ** correspond to the subquery(s) of OR-clause processing. Only the
113509 ** best N_OR_COST elements are retained.
113511 #define N_OR_COST 3
113512 struct WhereOrSet {
113513 u16 n; /* Number of valid a[] entries */
113514 WhereOrCost a[N_OR_COST]; /* Set of best costs */
113518 /* Forward declaration of methods */
113519 static int whereLoopResize(sqlite3*, WhereLoop*, int);
113522 ** Each instance of this object holds a sequence of WhereLoop objects
113523 ** that implement some or all of a query plan.
113525 ** Think of each WhereLoop object as a node in a graph with arcs
113526 ** showing dependencies and costs for travelling between nodes. (That is
113527 ** not a completely accurate description because WhereLoop costs are a
113528 ** vector, not a scalar, and because dependencies are many-to-one, not
113529 ** one-to-one as are graph nodes. But it is a useful visualization aid.)
113530 ** Then a WherePath object is a path through the graph that visits some
113531 ** or all of the WhereLoop objects once.
113533 ** The "solver" works by creating the N best WherePath objects of length
113534 ** 1. Then using those as a basis to compute the N best WherePath objects
113535 ** of length 2. And so forth until the length of WherePaths equals the
113536 ** number of nodes in the FROM clause. The best (lowest cost) WherePath
113537 ** at the end is the chosen query plan.
113539 struct WherePath {
113540 Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
113541 Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
113542 LogEst nRow; /* Estimated number of rows generated by this path */
113543 LogEst rCost; /* Total cost of this path */
113544 LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
113545 i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
113546 WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
113550 ** The query generator uses an array of instances of this structure to
113551 ** help it analyze the subexpressions of the WHERE clause. Each WHERE
113552 ** clause subexpression is separated from the others by AND operators,
113553 ** usually, or sometimes subexpressions separated by OR.
113555 ** All WhereTerms are collected into a single WhereClause structure.
113556 ** The following identity holds:
113558 ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
113560 ** When a term is of the form:
113562 ** X <op> <expr>
113564 ** where X is a column name and <op> is one of certain operators,
113565 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
113566 ** cursor number and column number for X. WhereTerm.eOperator records
113567 ** the <op> using a bitmask encoding defined by WO_xxx below. The
113568 ** use of a bitmask encoding for the operator allows us to search
113569 ** quickly for terms that match any of several different operators.
113571 ** A WhereTerm might also be two or more subterms connected by OR:
113573 ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
113575 ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
113576 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
113577 ** is collected about the OR clause.
113579 ** If a term in the WHERE clause does not match either of the two previous
113580 ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
113581 ** to the original subexpression content and wtFlags is set up appropriately
113582 ** but no other fields in the WhereTerm object are meaningful.
113584 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
113585 ** but they do so indirectly. A single WhereMaskSet structure translates
113586 ** cursor number into bits and the translated bit is stored in the prereq
113587 ** fields. The translation is used in order to maximize the number of
113588 ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
113589 ** spread out over the non-negative integers. For example, the cursor
113590 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
113591 ** translates these sparse cursor numbers into consecutive integers
113592 ** beginning with 0 in order to make the best possible use of the available
113593 ** bits in the Bitmask. So, in the example above, the cursor numbers
113594 ** would be mapped into integers 0 through 7.
113596 ** The number of terms in a join is limited by the number of bits
113597 ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
113598 ** is only able to process joins with 64 or fewer tables.
113600 struct WhereTerm {
113601 Expr *pExpr; /* Pointer to the subexpression that is this term */
113602 int iParent; /* Disable pWC->a[iParent] when this term disabled */
113603 int leftCursor; /* Cursor number of X in "X <op> <expr>" */
113604 union {
113605 int leftColumn; /* Column number of X in "X <op> <expr>" */
113606 WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
113607 WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
113609 LogEst truthProb; /* Probability of truth for this expression */
113610 u16 eOperator; /* A WO_xx value describing <op> */
113611 u8 wtFlags; /* TERM_xxx bit flags. See below */
113612 u8 nChild; /* Number of children that must disable us */
113613 WhereClause *pWC; /* The clause this term is part of */
113614 Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
113615 Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
113619 ** Allowed values of WhereTerm.wtFlags
113621 #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
113622 #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
113623 #define TERM_CODED 0x04 /* This term is already coded */
113624 #define TERM_COPIED 0x08 /* Has a child */
113625 #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
113626 #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
113627 #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
113628 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
113629 # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
113630 #else
113631 # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
113632 #endif
113635 ** An instance of the WhereScan object is used as an iterator for locating
113636 ** terms in the WHERE clause that are useful to the query planner.
113638 struct WhereScan {
113639 WhereClause *pOrigWC; /* Original, innermost WhereClause */
113640 WhereClause *pWC; /* WhereClause currently being scanned */
113641 char *zCollName; /* Required collating sequence, if not NULL */
113642 char idxaff; /* Must match this affinity, if zCollName!=NULL */
113643 unsigned char nEquiv; /* Number of entries in aEquiv[] */
113644 unsigned char iEquiv; /* Next unused slot in aEquiv[] */
113645 u32 opMask; /* Acceptable operators */
113646 int k; /* Resume scanning at this->pWC->a[this->k] */
113647 int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
113651 ** An instance of the following structure holds all information about a
113652 ** WHERE clause. Mostly this is a container for one or more WhereTerms.
113654 ** Explanation of pOuter: For a WHERE clause of the form
113656 ** a AND ((b AND c) OR (d AND e)) AND f
113658 ** There are separate WhereClause objects for the whole clause and for
113659 ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
113660 ** subclauses points to the WhereClause object for the whole clause.
113662 struct WhereClause {
113663 WhereInfo *pWInfo; /* WHERE clause processing context */
113664 WhereClause *pOuter; /* Outer conjunction */
113665 u8 op; /* Split operator. TK_AND or TK_OR */
113666 int nTerm; /* Number of terms */
113667 int nSlot; /* Number of entries in a[] */
113668 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
113669 #if defined(SQLITE_SMALL_STACK)
113670 WhereTerm aStatic[1]; /* Initial static space for a[] */
113671 #else
113672 WhereTerm aStatic[8]; /* Initial static space for a[] */
113673 #endif
113677 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
113678 ** a dynamically allocated instance of the following structure.
113680 struct WhereOrInfo {
113681 WhereClause wc; /* Decomposition into subterms */
113682 Bitmask indexable; /* Bitmask of all indexable tables in the clause */
113686 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
113687 ** a dynamically allocated instance of the following structure.
113689 struct WhereAndInfo {
113690 WhereClause wc; /* The subexpression broken out */
113694 ** An instance of the following structure keeps track of a mapping
113695 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
113697 ** The VDBE cursor numbers are small integers contained in
113698 ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
113699 ** clause, the cursor numbers might not begin with 0 and they might
113700 ** contain gaps in the numbering sequence. But we want to make maximum
113701 ** use of the bits in our bitmasks. This structure provides a mapping
113702 ** from the sparse cursor numbers into consecutive integers beginning
113703 ** with 0.
113705 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
113706 ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
113708 ** For example, if the WHERE clause expression used these VDBE
113709 ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
113710 ** would map those cursor numbers into bits 0 through 5.
113712 ** Note that the mapping is not necessarily ordered. In the example
113713 ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
113714 ** 57->5, 73->4. Or one of 719 other combinations might be used. It
113715 ** does not really matter. What is important is that sparse cursor
113716 ** numbers all get mapped into bit numbers that begin with 0 and contain
113717 ** no gaps.
113719 struct WhereMaskSet {
113720 int n; /* Number of assigned cursor values */
113721 int ix[BMS]; /* Cursor assigned to each bit */
113725 ** This object is a convenience wrapper holding all information needed
113726 ** to construct WhereLoop objects for a particular query.
113728 struct WhereLoopBuilder {
113729 WhereInfo *pWInfo; /* Information about this WHERE */
113730 WhereClause *pWC; /* WHERE clause terms */
113731 ExprList *pOrderBy; /* ORDER BY clause */
113732 WhereLoop *pNew; /* Template WhereLoop */
113733 WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
113734 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
113735 UnpackedRecord *pRec; /* Probe for stat4 (if required) */
113736 int nRecValid; /* Number of valid fields currently in pRec */
113737 #endif
113741 ** The WHERE clause processing routine has two halves. The
113742 ** first part does the start of the WHERE loop and the second
113743 ** half does the tail of the WHERE loop. An instance of
113744 ** this structure is returned by the first half and passed
113745 ** into the second half to give some continuity.
113747 ** An instance of this object holds the complete state of the query
113748 ** planner.
113750 struct WhereInfo {
113751 Parse *pParse; /* Parsing and code generating context */
113752 SrcList *pTabList; /* List of tables in the join */
113753 ExprList *pOrderBy; /* The ORDER BY clause or NULL */
113754 ExprList *pResultSet; /* Result set. DISTINCT operates on these */
113755 WhereLoop *pLoops; /* List of all WhereLoop objects */
113756 Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
113757 LogEst nRowOut; /* Estimated number of output rows */
113758 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
113759 i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
113760 u8 sorted; /* True if really sorted (not just grouped) */
113761 u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
113762 u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
113763 u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
113764 u8 nLevel; /* Number of nested loop */
113765 int iTop; /* The very beginning of the WHERE loop */
113766 int iContinue; /* Jump here to continue with next record */
113767 int iBreak; /* Jump here to break out of the loop */
113768 int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
113769 int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
113770 WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
113771 WhereClause sWC; /* Decomposition of the WHERE clause */
113772 WhereLevel a[1]; /* Information about each nest loop in WHERE */
113776 ** Bitmasks for the operators on WhereTerm objects. These are all
113777 ** operators that are of interest to the query planner. An
113778 ** OR-ed combination of these values can be used when searching for
113779 ** particular WhereTerms within a WhereClause.
113781 #define WO_IN 0x001
113782 #define WO_EQ 0x002
113783 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
113784 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
113785 #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
113786 #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
113787 #define WO_MATCH 0x040
113788 #define WO_ISNULL 0x080
113789 #define WO_OR 0x100 /* Two or more OR-connected terms */
113790 #define WO_AND 0x200 /* Two or more AND-connected terms */
113791 #define WO_EQUIV 0x400 /* Of the form A==B, both columns */
113792 #define WO_NOOP 0x800 /* This term does not restrict search space */
113794 #define WO_ALL 0xfff /* Mask of all possible WO_* values */
113795 #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
113798 ** These are definitions of bits in the WhereLoop.wsFlags field.
113799 ** The particular combination of bits in each WhereLoop help to
113800 ** determine the algorithm that WhereLoop represents.
113802 #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
113803 #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
113804 #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
113805 #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
113806 #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
113807 #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
113808 #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
113809 #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
113810 #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
113811 #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
113812 #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
113813 #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
113814 #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
113815 #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
113816 #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
113817 #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
113818 #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
113819 #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
113821 /************** End of whereInt.h ********************************************/
113822 /************** Continuing where we left off in where.c **********************/
113825 ** Return the estimated number of output rows from a WHERE clause
113827 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
113828 return sqlite3LogEstToInt(pWInfo->nRowOut);
113832 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
113833 ** WHERE clause returns outputs for DISTINCT processing.
113835 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
113836 return pWInfo->eDistinct;
113840 ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
113841 ** Return FALSE if the output needs to be sorted.
113843 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
113844 return pWInfo->nOBSat;
113848 ** Return the VDBE address or label to jump to in order to continue
113849 ** immediately with the next row of a WHERE clause.
113851 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
113852 assert( pWInfo->iContinue!=0 );
113853 return pWInfo->iContinue;
113857 ** Return the VDBE address or label to jump to in order to break
113858 ** out of a WHERE loop.
113860 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
113861 return pWInfo->iBreak;
113865 ** Return TRUE if an UPDATE or DELETE statement can operate directly on
113866 ** the rowids returned by a WHERE clause. Return FALSE if doing an
113867 ** UPDATE or DELETE might change subsequent WHERE clause results.
113869 ** If the ONEPASS optimization is used (if this routine returns true)
113870 ** then also write the indices of open cursors used by ONEPASS
113871 ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
113872 ** table and iaCur[1] gets the cursor used by an auxiliary index.
113873 ** Either value may be -1, indicating that cursor is not used.
113874 ** Any cursors returned will have been opened for writing.
113876 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
113877 ** unable to use the ONEPASS optimization.
113879 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
113880 memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
113881 return pWInfo->okOnePass;
113885 ** Move the content of pSrc into pDest
113887 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
113888 pDest->n = pSrc->n;
113889 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
113893 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
113895 ** The new entry might overwrite an existing entry, or it might be
113896 ** appended, or it might be discarded. Do whatever is the right thing
113897 ** so that pSet keeps the N_OR_COST best entries seen so far.
113899 static int whereOrInsert(
113900 WhereOrSet *pSet, /* The WhereOrSet to be updated */
113901 Bitmask prereq, /* Prerequisites of the new entry */
113902 LogEst rRun, /* Run-cost of the new entry */
113903 LogEst nOut /* Number of outputs for the new entry */
113905 u16 i;
113906 WhereOrCost *p;
113907 for(i=pSet->n, p=pSet->a; i>0; i--, p++){
113908 if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
113909 goto whereOrInsert_done;
113911 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
113912 return 0;
113915 if( pSet->n<N_OR_COST ){
113916 p = &pSet->a[pSet->n++];
113917 p->nOut = nOut;
113918 }else{
113919 p = pSet->a;
113920 for(i=1; i<pSet->n; i++){
113921 if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
113923 if( p->rRun<=rRun ) return 0;
113925 whereOrInsert_done:
113926 p->prereq = prereq;
113927 p->rRun = rRun;
113928 if( p->nOut>nOut ) p->nOut = nOut;
113929 return 1;
113933 ** Initialize a preallocated WhereClause structure.
113935 static void whereClauseInit(
113936 WhereClause *pWC, /* The WhereClause to be initialized */
113937 WhereInfo *pWInfo /* The WHERE processing context */
113939 pWC->pWInfo = pWInfo;
113940 pWC->pOuter = 0;
113941 pWC->nTerm = 0;
113942 pWC->nSlot = ArraySize(pWC->aStatic);
113943 pWC->a = pWC->aStatic;
113946 /* Forward reference */
113947 static void whereClauseClear(WhereClause*);
113950 ** Deallocate all memory associated with a WhereOrInfo object.
113952 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
113953 whereClauseClear(&p->wc);
113954 sqlite3DbFree(db, p);
113958 ** Deallocate all memory associated with a WhereAndInfo object.
113960 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
113961 whereClauseClear(&p->wc);
113962 sqlite3DbFree(db, p);
113966 ** Deallocate a WhereClause structure. The WhereClause structure
113967 ** itself is not freed. This routine is the inverse of whereClauseInit().
113969 static void whereClauseClear(WhereClause *pWC){
113970 int i;
113971 WhereTerm *a;
113972 sqlite3 *db = pWC->pWInfo->pParse->db;
113973 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
113974 if( a->wtFlags & TERM_DYNAMIC ){
113975 sqlite3ExprDelete(db, a->pExpr);
113977 if( a->wtFlags & TERM_ORINFO ){
113978 whereOrInfoDelete(db, a->u.pOrInfo);
113979 }else if( a->wtFlags & TERM_ANDINFO ){
113980 whereAndInfoDelete(db, a->u.pAndInfo);
113983 if( pWC->a!=pWC->aStatic ){
113984 sqlite3DbFree(db, pWC->a);
113989 ** Add a single new WhereTerm entry to the WhereClause object pWC.
113990 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
113991 ** The index in pWC->a[] of the new WhereTerm is returned on success.
113992 ** 0 is returned if the new WhereTerm could not be added due to a memory
113993 ** allocation error. The memory allocation failure will be recorded in
113994 ** the db->mallocFailed flag so that higher-level functions can detect it.
113996 ** This routine will increase the size of the pWC->a[] array as necessary.
113998 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
113999 ** for freeing the expression p is assumed by the WhereClause object pWC.
114000 ** This is true even if this routine fails to allocate a new WhereTerm.
114002 ** WARNING: This routine might reallocate the space used to store
114003 ** WhereTerms. All pointers to WhereTerms should be invalidated after
114004 ** calling this routine. Such pointers may be reinitialized by referencing
114005 ** the pWC->a[] array.
114007 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
114008 WhereTerm *pTerm;
114009 int idx;
114010 testcase( wtFlags & TERM_VIRTUAL );
114011 if( pWC->nTerm>=pWC->nSlot ){
114012 WhereTerm *pOld = pWC->a;
114013 sqlite3 *db = pWC->pWInfo->pParse->db;
114014 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
114015 if( pWC->a==0 ){
114016 if( wtFlags & TERM_DYNAMIC ){
114017 sqlite3ExprDelete(db, p);
114019 pWC->a = pOld;
114020 return 0;
114022 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
114023 if( pOld!=pWC->aStatic ){
114024 sqlite3DbFree(db, pOld);
114026 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
114028 pTerm = &pWC->a[idx = pWC->nTerm++];
114029 if( p && ExprHasProperty(p, EP_Unlikely) ){
114030 pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
114031 }else{
114032 pTerm->truthProb = 1;
114034 pTerm->pExpr = sqlite3ExprSkipCollate(p);
114035 pTerm->wtFlags = wtFlags;
114036 pTerm->pWC = pWC;
114037 pTerm->iParent = -1;
114038 return idx;
114042 ** This routine identifies subexpressions in the WHERE clause where
114043 ** each subexpression is separated by the AND operator or some other
114044 ** operator specified in the op parameter. The WhereClause structure
114045 ** is filled with pointers to subexpressions. For example:
114047 ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
114048 ** \________/ \_______________/ \________________/
114049 ** slot[0] slot[1] slot[2]
114051 ** The original WHERE clause in pExpr is unaltered. All this routine
114052 ** does is make slot[] entries point to substructure within pExpr.
114054 ** In the previous sentence and in the diagram, "slot[]" refers to
114055 ** the WhereClause.a[] array. The slot[] array grows as needed to contain
114056 ** all terms of the WHERE clause.
114058 static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
114059 pWC->op = op;
114060 if( pExpr==0 ) return;
114061 if( pExpr->op!=op ){
114062 whereClauseInsert(pWC, pExpr, 0);
114063 }else{
114064 whereSplit(pWC, pExpr->pLeft, op);
114065 whereSplit(pWC, pExpr->pRight, op);
114070 ** Initialize a WhereMaskSet object
114072 #define initMaskSet(P) (P)->n=0
114075 ** Return the bitmask for the given cursor number. Return 0 if
114076 ** iCursor is not in the set.
114078 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
114079 int i;
114080 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
114081 for(i=0; i<pMaskSet->n; i++){
114082 if( pMaskSet->ix[i]==iCursor ){
114083 return MASKBIT(i);
114086 return 0;
114090 ** Create a new mask for cursor iCursor.
114092 ** There is one cursor per table in the FROM clause. The number of
114093 ** tables in the FROM clause is limited by a test early in the
114094 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
114095 ** array will never overflow.
114097 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
114098 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
114099 pMaskSet->ix[pMaskSet->n++] = iCursor;
114103 ** These routines walk (recursively) an expression tree and generate
114104 ** a bitmask indicating which tables are used in that expression
114105 ** tree.
114107 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
114108 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
114109 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
114110 Bitmask mask = 0;
114111 if( p==0 ) return 0;
114112 if( p->op==TK_COLUMN ){
114113 mask = getMask(pMaskSet, p->iTable);
114114 return mask;
114116 mask = exprTableUsage(pMaskSet, p->pRight);
114117 mask |= exprTableUsage(pMaskSet, p->pLeft);
114118 if( ExprHasProperty(p, EP_xIsSelect) ){
114119 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
114120 }else{
114121 mask |= exprListTableUsage(pMaskSet, p->x.pList);
114123 return mask;
114125 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
114126 int i;
114127 Bitmask mask = 0;
114128 if( pList ){
114129 for(i=0; i<pList->nExpr; i++){
114130 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
114133 return mask;
114135 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
114136 Bitmask mask = 0;
114137 while( pS ){
114138 SrcList *pSrc = pS->pSrc;
114139 mask |= exprListTableUsage(pMaskSet, pS->pEList);
114140 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
114141 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
114142 mask |= exprTableUsage(pMaskSet, pS->pWhere);
114143 mask |= exprTableUsage(pMaskSet, pS->pHaving);
114144 if( ALWAYS(pSrc!=0) ){
114145 int i;
114146 for(i=0; i<pSrc->nSrc; i++){
114147 mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
114148 mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
114151 pS = pS->pPrior;
114153 return mask;
114157 ** Return TRUE if the given operator is one of the operators that is
114158 ** allowed for an indexable WHERE clause term. The allowed operators are
114159 ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
114161 static int allowedOp(int op){
114162 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
114163 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
114164 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
114165 assert( TK_GE==TK_EQ+4 );
114166 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
114170 ** Commute a comparison operator. Expressions of the form "X op Y"
114171 ** are converted into "Y op X".
114173 ** If left/right precedence rules come into play when determining the
114174 ** collating sequence, then COLLATE operators are adjusted to ensure
114175 ** that the collating sequence does not change. For example:
114176 ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
114177 ** the left hand side of a comparison overrides any collation sequence
114178 ** attached to the right. For the same reason the EP_Collate flag
114179 ** is not commuted.
114181 static void exprCommute(Parse *pParse, Expr *pExpr){
114182 u16 expRight = (pExpr->pRight->flags & EP_Collate);
114183 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
114184 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
114185 if( expRight==expLeft ){
114186 /* Either X and Y both have COLLATE operator or neither do */
114187 if( expRight ){
114188 /* Both X and Y have COLLATE operators. Make sure X is always
114189 ** used by clearing the EP_Collate flag from Y. */
114190 pExpr->pRight->flags &= ~EP_Collate;
114191 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
114192 /* Neither X nor Y have COLLATE operators, but X has a non-default
114193 ** collating sequence. So add the EP_Collate marker on X to cause
114194 ** it to be searched first. */
114195 pExpr->pLeft->flags |= EP_Collate;
114198 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
114199 if( pExpr->op>=TK_GT ){
114200 assert( TK_LT==TK_GT+2 );
114201 assert( TK_GE==TK_LE+2 );
114202 assert( TK_GT>TK_EQ );
114203 assert( TK_GT<TK_LE );
114204 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
114205 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
114210 ** Translate from TK_xx operator to WO_xx bitmask.
114212 static u16 operatorMask(int op){
114213 u16 c;
114214 assert( allowedOp(op) );
114215 if( op==TK_IN ){
114216 c = WO_IN;
114217 }else if( op==TK_ISNULL ){
114218 c = WO_ISNULL;
114219 }else{
114220 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
114221 c = (u16)(WO_EQ<<(op-TK_EQ));
114223 assert( op!=TK_ISNULL || c==WO_ISNULL );
114224 assert( op!=TK_IN || c==WO_IN );
114225 assert( op!=TK_EQ || c==WO_EQ );
114226 assert( op!=TK_LT || c==WO_LT );
114227 assert( op!=TK_LE || c==WO_LE );
114228 assert( op!=TK_GT || c==WO_GT );
114229 assert( op!=TK_GE || c==WO_GE );
114230 return c;
114234 ** Advance to the next WhereTerm that matches according to the criteria
114235 ** established when the pScan object was initialized by whereScanInit().
114236 ** Return NULL if there are no more matching WhereTerms.
114238 static WhereTerm *whereScanNext(WhereScan *pScan){
114239 int iCur; /* The cursor on the LHS of the term */
114240 int iColumn; /* The column on the LHS of the term. -1 for IPK */
114241 Expr *pX; /* An expression being tested */
114242 WhereClause *pWC; /* Shorthand for pScan->pWC */
114243 WhereTerm *pTerm; /* The term being tested */
114244 int k = pScan->k; /* Where to start scanning */
114246 while( pScan->iEquiv<=pScan->nEquiv ){
114247 iCur = pScan->aEquiv[pScan->iEquiv-2];
114248 iColumn = pScan->aEquiv[pScan->iEquiv-1];
114249 while( (pWC = pScan->pWC)!=0 ){
114250 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
114251 if( pTerm->leftCursor==iCur
114252 && pTerm->u.leftColumn==iColumn
114253 && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
114255 if( (pTerm->eOperator & WO_EQUIV)!=0
114256 && pScan->nEquiv<ArraySize(pScan->aEquiv)
114258 int j;
114259 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
114260 assert( pX->op==TK_COLUMN );
114261 for(j=0; j<pScan->nEquiv; j+=2){
114262 if( pScan->aEquiv[j]==pX->iTable
114263 && pScan->aEquiv[j+1]==pX->iColumn ){
114264 break;
114267 if( j==pScan->nEquiv ){
114268 pScan->aEquiv[j] = pX->iTable;
114269 pScan->aEquiv[j+1] = pX->iColumn;
114270 pScan->nEquiv += 2;
114273 if( (pTerm->eOperator & pScan->opMask)!=0 ){
114274 /* Verify the affinity and collating sequence match */
114275 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
114276 CollSeq *pColl;
114277 Parse *pParse = pWC->pWInfo->pParse;
114278 pX = pTerm->pExpr;
114279 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
114280 continue;
114282 assert(pX->pLeft);
114283 pColl = sqlite3BinaryCompareCollSeq(pParse,
114284 pX->pLeft, pX->pRight);
114285 if( pColl==0 ) pColl = pParse->db->pDfltColl;
114286 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
114287 continue;
114290 if( (pTerm->eOperator & WO_EQ)!=0
114291 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
114292 && pX->iTable==pScan->aEquiv[0]
114293 && pX->iColumn==pScan->aEquiv[1]
114295 continue;
114297 pScan->k = k+1;
114298 return pTerm;
114302 pScan->pWC = pScan->pWC->pOuter;
114303 k = 0;
114305 pScan->pWC = pScan->pOrigWC;
114306 k = 0;
114307 pScan->iEquiv += 2;
114309 return 0;
114313 ** Initialize a WHERE clause scanner object. Return a pointer to the
114314 ** first match. Return NULL if there are no matches.
114316 ** The scanner will be searching the WHERE clause pWC. It will look
114317 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
114318 ** iCur. The <op> must be one of the operators described by opMask.
114320 ** If the search is for X and the WHERE clause contains terms of the
114321 ** form X=Y then this routine might also return terms of the form
114322 ** "Y <op> <expr>". The number of levels of transitivity is limited,
114323 ** but is enough to handle most commonly occurring SQL statements.
114325 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
114326 ** index pIdx.
114328 static WhereTerm *whereScanInit(
114329 WhereScan *pScan, /* The WhereScan object being initialized */
114330 WhereClause *pWC, /* The WHERE clause to be scanned */
114331 int iCur, /* Cursor to scan for */
114332 int iColumn, /* Column to scan for */
114333 u32 opMask, /* Operator(s) to scan for */
114334 Index *pIdx /* Must be compatible with this index */
114336 int j;
114338 /* memset(pScan, 0, sizeof(*pScan)); */
114339 pScan->pOrigWC = pWC;
114340 pScan->pWC = pWC;
114341 if( pIdx && iColumn>=0 ){
114342 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
114343 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
114344 if( NEVER(j>pIdx->nColumn) ) return 0;
114346 pScan->zCollName = pIdx->azColl[j];
114347 }else{
114348 pScan->idxaff = 0;
114349 pScan->zCollName = 0;
114351 pScan->opMask = opMask;
114352 pScan->k = 0;
114353 pScan->aEquiv[0] = iCur;
114354 pScan->aEquiv[1] = iColumn;
114355 pScan->nEquiv = 2;
114356 pScan->iEquiv = 2;
114357 return whereScanNext(pScan);
114361 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
114362 ** where X is a reference to the iColumn of table iCur and <op> is one of
114363 ** the WO_xx operator codes specified by the op parameter.
114364 ** Return a pointer to the term. Return 0 if not found.
114366 ** The term returned might by Y=<expr> if there is another constraint in
114367 ** the WHERE clause that specifies that X=Y. Any such constraints will be
114368 ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
114369 ** aEquiv[] array holds X and all its equivalents, with each SQL variable
114370 ** taking up two slots in aEquiv[]. The first slot is for the cursor number
114371 ** and the second is for the column number. There are 22 slots in aEquiv[]
114372 ** so that means we can look for X plus up to 10 other equivalent values.
114373 ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
114374 ** and ... and A9=A10 and A10=<expr>.
114376 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
114377 ** then try for the one with no dependencies on <expr> - in other words where
114378 ** <expr> is a constant expression of some kind. Only return entries of
114379 ** the form "X <op> Y" where Y is a column in another table if no terms of
114380 ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
114381 ** exist, try to return a term that does not use WO_EQUIV.
114383 static WhereTerm *findTerm(
114384 WhereClause *pWC, /* The WHERE clause to be searched */
114385 int iCur, /* Cursor number of LHS */
114386 int iColumn, /* Column number of LHS */
114387 Bitmask notReady, /* RHS must not overlap with this mask */
114388 u32 op, /* Mask of WO_xx values describing operator */
114389 Index *pIdx /* Must be compatible with this index, if not NULL */
114391 WhereTerm *pResult = 0;
114392 WhereTerm *p;
114393 WhereScan scan;
114395 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
114396 while( p ){
114397 if( (p->prereqRight & notReady)==0 ){
114398 if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
114399 return p;
114401 if( pResult==0 ) pResult = p;
114403 p = whereScanNext(&scan);
114405 return pResult;
114408 /* Forward reference */
114409 static void exprAnalyze(SrcList*, WhereClause*, int);
114412 ** Call exprAnalyze on all terms in a WHERE clause.
114414 static void exprAnalyzeAll(
114415 SrcList *pTabList, /* the FROM clause */
114416 WhereClause *pWC /* the WHERE clause to be analyzed */
114418 int i;
114419 for(i=pWC->nTerm-1; i>=0; i--){
114420 exprAnalyze(pTabList, pWC, i);
114424 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
114426 ** Check to see if the given expression is a LIKE or GLOB operator that
114427 ** can be optimized using inequality constraints. Return TRUE if it is
114428 ** so and false if not.
114430 ** In order for the operator to be optimizible, the RHS must be a string
114431 ** literal that does not begin with a wildcard.
114433 static int isLikeOrGlob(
114434 Parse *pParse, /* Parsing and code generating context */
114435 Expr *pExpr, /* Test this expression */
114436 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
114437 int *pisComplete, /* True if the only wildcard is % in the last character */
114438 int *pnoCase /* True if uppercase is equivalent to lowercase */
114440 const char *z = 0; /* String on RHS of LIKE operator */
114441 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
114442 ExprList *pList; /* List of operands to the LIKE operator */
114443 int c; /* One character in z[] */
114444 int cnt; /* Number of non-wildcard prefix characters */
114445 char wc[3]; /* Wildcard characters */
114446 sqlite3 *db = pParse->db; /* Database connection */
114447 sqlite3_value *pVal = 0;
114448 int op; /* Opcode of pRight */
114450 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
114451 return 0;
114453 #ifdef SQLITE_EBCDIC
114454 if( *pnoCase ) return 0;
114455 #endif
114456 pList = pExpr->x.pList;
114457 pLeft = pList->a[1].pExpr;
114458 if( pLeft->op!=TK_COLUMN
114459 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
114460 || IsVirtual(pLeft->pTab)
114462 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
114463 ** be the name of an indexed column with TEXT affinity. */
114464 return 0;
114466 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
114468 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
114469 op = pRight->op;
114470 if( op==TK_VARIABLE ){
114471 Vdbe *pReprepare = pParse->pReprepare;
114472 int iCol = pRight->iColumn;
114473 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
114474 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
114475 z = (char *)sqlite3_value_text(pVal);
114477 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
114478 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
114479 }else if( op==TK_STRING ){
114480 z = pRight->u.zToken;
114482 if( z ){
114483 cnt = 0;
114484 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
114485 cnt++;
114487 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
114488 Expr *pPrefix;
114489 *pisComplete = c==wc[0] && z[cnt+1]==0;
114490 pPrefix = sqlite3Expr(db, TK_STRING, z);
114491 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
114492 *ppPrefix = pPrefix;
114493 if( op==TK_VARIABLE ){
114494 Vdbe *v = pParse->pVdbe;
114495 sqlite3VdbeSetVarmask(v, pRight->iColumn);
114496 if( *pisComplete && pRight->u.zToken[1] ){
114497 /* If the rhs of the LIKE expression is a variable, and the current
114498 ** value of the variable means there is no need to invoke the LIKE
114499 ** function, then no OP_Variable will be added to the program.
114500 ** This causes problems for the sqlite3_bind_parameter_name()
114501 ** API. To work around them, add a dummy OP_Variable here.
114503 int r1 = sqlite3GetTempReg(pParse);
114504 sqlite3ExprCodeTarget(pParse, pRight, r1);
114505 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
114506 sqlite3ReleaseTempReg(pParse, r1);
114509 }else{
114510 z = 0;
114514 sqlite3ValueFree(pVal);
114515 return (z!=0);
114517 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
114520 #ifndef SQLITE_OMIT_VIRTUALTABLE
114522 ** Check to see if the given expression is of the form
114524 ** column MATCH expr
114526 ** If it is then return TRUE. If not, return FALSE.
114528 static int isMatchOfColumn(
114529 Expr *pExpr /* Test this expression */
114531 ExprList *pList;
114533 if( pExpr->op!=TK_FUNCTION ){
114534 return 0;
114536 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
114537 return 0;
114539 pList = pExpr->x.pList;
114540 if( pList->nExpr!=2 ){
114541 return 0;
114543 if( pList->a[1].pExpr->op != TK_COLUMN ){
114544 return 0;
114546 return 1;
114548 #endif /* SQLITE_OMIT_VIRTUALTABLE */
114551 ** If the pBase expression originated in the ON or USING clause of
114552 ** a join, then transfer the appropriate markings over to derived.
114554 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
114555 if( pDerived ){
114556 pDerived->flags |= pBase->flags & EP_FromJoin;
114557 pDerived->iRightJoinTable = pBase->iRightJoinTable;
114561 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
114563 ** Analyze a term that consists of two or more OR-connected
114564 ** subterms. So in:
114566 ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
114567 ** ^^^^^^^^^^^^^^^^^^^^
114569 ** This routine analyzes terms such as the middle term in the above example.
114570 ** A WhereOrTerm object is computed and attached to the term under
114571 ** analysis, regardless of the outcome of the analysis. Hence:
114573 ** WhereTerm.wtFlags |= TERM_ORINFO
114574 ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
114576 ** The term being analyzed must have two or more of OR-connected subterms.
114577 ** A single subterm might be a set of AND-connected sub-subterms.
114578 ** Examples of terms under analysis:
114580 ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
114581 ** (B) x=expr1 OR expr2=x OR x=expr3
114582 ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
114583 ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
114584 ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
114586 ** CASE 1:
114588 ** If all subterms are of the form T.C=expr for some single column of C and
114589 ** a single table T (as shown in example B above) then create a new virtual
114590 ** term that is an equivalent IN expression. In other words, if the term
114591 ** being analyzed is:
114593 ** x = expr1 OR expr2 = x OR x = expr3
114595 ** then create a new virtual term like this:
114597 ** x IN (expr1,expr2,expr3)
114599 ** CASE 2:
114601 ** If all subterms are indexable by a single table T, then set
114603 ** WhereTerm.eOperator = WO_OR
114604 ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
114606 ** A subterm is "indexable" if it is of the form
114607 ** "T.C <op> <expr>" where C is any column of table T and
114608 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
114609 ** A subterm is also indexable if it is an AND of two or more
114610 ** subsubterms at least one of which is indexable. Indexable AND
114611 ** subterms have their eOperator set to WO_AND and they have
114612 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
114614 ** From another point of view, "indexable" means that the subterm could
114615 ** potentially be used with an index if an appropriate index exists.
114616 ** This analysis does not consider whether or not the index exists; that
114617 ** is decided elsewhere. This analysis only looks at whether subterms
114618 ** appropriate for indexing exist.
114620 ** All examples A through E above satisfy case 2. But if a term
114621 ** also satisfies case 1 (such as B) we know that the optimizer will
114622 ** always prefer case 1, so in that case we pretend that case 2 is not
114623 ** satisfied.
114625 ** It might be the case that multiple tables are indexable. For example,
114626 ** (E) above is indexable on tables P, Q, and R.
114628 ** Terms that satisfy case 2 are candidates for lookup by using
114629 ** separate indices to find rowids for each subterm and composing
114630 ** the union of all rowids using a RowSet object. This is similar
114631 ** to "bitmap indices" in other database engines.
114633 ** OTHERWISE:
114635 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
114636 ** zero. This term is not useful for search.
114638 static void exprAnalyzeOrTerm(
114639 SrcList *pSrc, /* the FROM clause */
114640 WhereClause *pWC, /* the complete WHERE clause */
114641 int idxTerm /* Index of the OR-term to be analyzed */
114643 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
114644 Parse *pParse = pWInfo->pParse; /* Parser context */
114645 sqlite3 *db = pParse->db; /* Database connection */
114646 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
114647 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
114648 int i; /* Loop counters */
114649 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
114650 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
114651 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
114652 Bitmask chngToIN; /* Tables that might satisfy case 1 */
114653 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
114656 ** Break the OR clause into its separate subterms. The subterms are
114657 ** stored in a WhereClause structure containing within the WhereOrInfo
114658 ** object that is attached to the original OR clause term.
114660 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
114661 assert( pExpr->op==TK_OR );
114662 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
114663 if( pOrInfo==0 ) return;
114664 pTerm->wtFlags |= TERM_ORINFO;
114665 pOrWc = &pOrInfo->wc;
114666 whereClauseInit(pOrWc, pWInfo);
114667 whereSplit(pOrWc, pExpr, TK_OR);
114668 exprAnalyzeAll(pSrc, pOrWc);
114669 if( db->mallocFailed ) return;
114670 assert( pOrWc->nTerm>=2 );
114673 ** Compute the set of tables that might satisfy cases 1 or 2.
114675 indexable = ~(Bitmask)0;
114676 chngToIN = ~(Bitmask)0;
114677 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
114678 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
114679 WhereAndInfo *pAndInfo;
114680 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
114681 chngToIN = 0;
114682 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
114683 if( pAndInfo ){
114684 WhereClause *pAndWC;
114685 WhereTerm *pAndTerm;
114686 int j;
114687 Bitmask b = 0;
114688 pOrTerm->u.pAndInfo = pAndInfo;
114689 pOrTerm->wtFlags |= TERM_ANDINFO;
114690 pOrTerm->eOperator = WO_AND;
114691 pAndWC = &pAndInfo->wc;
114692 whereClauseInit(pAndWC, pWC->pWInfo);
114693 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
114694 exprAnalyzeAll(pSrc, pAndWC);
114695 pAndWC->pOuter = pWC;
114696 testcase( db->mallocFailed );
114697 if( !db->mallocFailed ){
114698 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
114699 assert( pAndTerm->pExpr );
114700 if( allowedOp(pAndTerm->pExpr->op) ){
114701 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
114705 indexable &= b;
114707 }else if( pOrTerm->wtFlags & TERM_COPIED ){
114708 /* Skip this term for now. We revisit it when we process the
114709 ** corresponding TERM_VIRTUAL term */
114710 }else{
114711 Bitmask b;
114712 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
114713 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
114714 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
114715 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
114717 indexable &= b;
114718 if( (pOrTerm->eOperator & WO_EQ)==0 ){
114719 chngToIN = 0;
114720 }else{
114721 chngToIN &= b;
114727 ** Record the set of tables that satisfy case 2. The set might be
114728 ** empty.
114730 pOrInfo->indexable = indexable;
114731 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
114734 ** chngToIN holds a set of tables that *might* satisfy case 1. But
114735 ** we have to do some additional checking to see if case 1 really
114736 ** is satisfied.
114738 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
114739 ** that there is no possibility of transforming the OR clause into an
114740 ** IN operator because one or more terms in the OR clause contain
114741 ** something other than == on a column in the single table. The 1-bit
114742 ** case means that every term of the OR clause is of the form
114743 ** "table.column=expr" for some single table. The one bit that is set
114744 ** will correspond to the common table. We still need to check to make
114745 ** sure the same column is used on all terms. The 2-bit case is when
114746 ** the all terms are of the form "table1.column=table2.column". It
114747 ** might be possible to form an IN operator with either table1.column
114748 ** or table2.column as the LHS if either is common to every term of
114749 ** the OR clause.
114751 ** Note that terms of the form "table.column1=table.column2" (the
114752 ** same table on both sizes of the ==) cannot be optimized.
114754 if( chngToIN ){
114755 int okToChngToIN = 0; /* True if the conversion to IN is valid */
114756 int iColumn = -1; /* Column index on lhs of IN operator */
114757 int iCursor = -1; /* Table cursor common to all terms */
114758 int j = 0; /* Loop counter */
114760 /* Search for a table and column that appears on one side or the
114761 ** other of the == operator in every subterm. That table and column
114762 ** will be recorded in iCursor and iColumn. There might not be any
114763 ** such table and column. Set okToChngToIN if an appropriate table
114764 ** and column is found but leave okToChngToIN false if not found.
114766 for(j=0; j<2 && !okToChngToIN; j++){
114767 pOrTerm = pOrWc->a;
114768 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
114769 assert( pOrTerm->eOperator & WO_EQ );
114770 pOrTerm->wtFlags &= ~TERM_OR_OK;
114771 if( pOrTerm->leftCursor==iCursor ){
114772 /* This is the 2-bit case and we are on the second iteration and
114773 ** current term is from the first iteration. So skip this term. */
114774 assert( j==1 );
114775 continue;
114777 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
114778 /* This term must be of the form t1.a==t2.b where t2 is in the
114779 ** chngToIN set but t1 is not. This term will be either preceded
114780 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
114781 ** and use its inversion. */
114782 testcase( pOrTerm->wtFlags & TERM_COPIED );
114783 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
114784 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
114785 continue;
114787 iColumn = pOrTerm->u.leftColumn;
114788 iCursor = pOrTerm->leftCursor;
114789 break;
114791 if( i<0 ){
114792 /* No candidate table+column was found. This can only occur
114793 ** on the second iteration */
114794 assert( j==1 );
114795 assert( IsPowerOfTwo(chngToIN) );
114796 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
114797 break;
114799 testcase( j==1 );
114801 /* We have found a candidate table and column. Check to see if that
114802 ** table and column is common to every term in the OR clause */
114803 okToChngToIN = 1;
114804 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
114805 assert( pOrTerm->eOperator & WO_EQ );
114806 if( pOrTerm->leftCursor!=iCursor ){
114807 pOrTerm->wtFlags &= ~TERM_OR_OK;
114808 }else if( pOrTerm->u.leftColumn!=iColumn ){
114809 okToChngToIN = 0;
114810 }else{
114811 int affLeft, affRight;
114812 /* If the right-hand side is also a column, then the affinities
114813 ** of both right and left sides must be such that no type
114814 ** conversions are required on the right. (Ticket #2249)
114816 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
114817 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
114818 if( affRight!=0 && affRight!=affLeft ){
114819 okToChngToIN = 0;
114820 }else{
114821 pOrTerm->wtFlags |= TERM_OR_OK;
114827 /* At this point, okToChngToIN is true if original pTerm satisfies
114828 ** case 1. In that case, construct a new virtual term that is
114829 ** pTerm converted into an IN operator.
114831 if( okToChngToIN ){
114832 Expr *pDup; /* A transient duplicate expression */
114833 ExprList *pList = 0; /* The RHS of the IN operator */
114834 Expr *pLeft = 0; /* The LHS of the IN operator */
114835 Expr *pNew; /* The complete IN operator */
114837 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
114838 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
114839 assert( pOrTerm->eOperator & WO_EQ );
114840 assert( pOrTerm->leftCursor==iCursor );
114841 assert( pOrTerm->u.leftColumn==iColumn );
114842 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
114843 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
114844 pLeft = pOrTerm->pExpr->pLeft;
114846 assert( pLeft!=0 );
114847 pDup = sqlite3ExprDup(db, pLeft, 0);
114848 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
114849 if( pNew ){
114850 int idxNew;
114851 transferJoinMarkings(pNew, pExpr);
114852 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
114853 pNew->x.pList = pList;
114854 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
114855 testcase( idxNew==0 );
114856 exprAnalyze(pSrc, pWC, idxNew);
114857 pTerm = &pWC->a[idxTerm];
114858 pWC->a[idxNew].iParent = idxTerm;
114859 pTerm->nChild = 1;
114860 }else{
114861 sqlite3ExprListDelete(db, pList);
114863 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
114867 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
114870 ** The input to this routine is an WhereTerm structure with only the
114871 ** "pExpr" field filled in. The job of this routine is to analyze the
114872 ** subexpression and populate all the other fields of the WhereTerm
114873 ** structure.
114875 ** If the expression is of the form "<expr> <op> X" it gets commuted
114876 ** to the standard form of "X <op> <expr>".
114878 ** If the expression is of the form "X <op> Y" where both X and Y are
114879 ** columns, then the original expression is unchanged and a new virtual
114880 ** term of the form "Y <op> X" is added to the WHERE clause and
114881 ** analyzed separately. The original term is marked with TERM_COPIED
114882 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
114883 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
114884 ** is a commuted copy of a prior term.) The original term has nChild=1
114885 ** and the copy has idxParent set to the index of the original term.
114887 static void exprAnalyze(
114888 SrcList *pSrc, /* the FROM clause */
114889 WhereClause *pWC, /* the WHERE clause */
114890 int idxTerm /* Index of the term to be analyzed */
114892 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
114893 WhereTerm *pTerm; /* The term to be analyzed */
114894 WhereMaskSet *pMaskSet; /* Set of table index masks */
114895 Expr *pExpr; /* The expression to be analyzed */
114896 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
114897 Bitmask prereqAll; /* Prerequesites of pExpr */
114898 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
114899 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
114900 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
114901 int noCase = 0; /* LIKE/GLOB distinguishes case */
114902 int op; /* Top-level operator. pExpr->op */
114903 Parse *pParse = pWInfo->pParse; /* Parsing context */
114904 sqlite3 *db = pParse->db; /* Database connection */
114906 if( db->mallocFailed ){
114907 return;
114909 pTerm = &pWC->a[idxTerm];
114910 pMaskSet = &pWInfo->sMaskSet;
114911 pExpr = pTerm->pExpr;
114912 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
114913 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
114914 op = pExpr->op;
114915 if( op==TK_IN ){
114916 assert( pExpr->pRight==0 );
114917 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
114918 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
114919 }else{
114920 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
114922 }else if( op==TK_ISNULL ){
114923 pTerm->prereqRight = 0;
114924 }else{
114925 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
114927 prereqAll = exprTableUsage(pMaskSet, pExpr);
114928 if( ExprHasProperty(pExpr, EP_FromJoin) ){
114929 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
114930 prereqAll |= x;
114931 extraRight = x-1; /* ON clause terms may not be used with an index
114932 ** on left table of a LEFT JOIN. Ticket #3015 */
114934 pTerm->prereqAll = prereqAll;
114935 pTerm->leftCursor = -1;
114936 pTerm->iParent = -1;
114937 pTerm->eOperator = 0;
114938 if( allowedOp(op) ){
114939 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
114940 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
114941 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
114942 if( pLeft->op==TK_COLUMN ){
114943 pTerm->leftCursor = pLeft->iTable;
114944 pTerm->u.leftColumn = pLeft->iColumn;
114945 pTerm->eOperator = operatorMask(op) & opMask;
114947 if( pRight && pRight->op==TK_COLUMN ){
114948 WhereTerm *pNew;
114949 Expr *pDup;
114950 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
114951 if( pTerm->leftCursor>=0 ){
114952 int idxNew;
114953 pDup = sqlite3ExprDup(db, pExpr, 0);
114954 if( db->mallocFailed ){
114955 sqlite3ExprDelete(db, pDup);
114956 return;
114958 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
114959 if( idxNew==0 ) return;
114960 pNew = &pWC->a[idxNew];
114961 pNew->iParent = idxTerm;
114962 pTerm = &pWC->a[idxTerm];
114963 pTerm->nChild = 1;
114964 pTerm->wtFlags |= TERM_COPIED;
114965 if( pExpr->op==TK_EQ
114966 && !ExprHasProperty(pExpr, EP_FromJoin)
114967 && OptimizationEnabled(db, SQLITE_Transitive)
114969 pTerm->eOperator |= WO_EQUIV;
114970 eExtraOp = WO_EQUIV;
114972 }else{
114973 pDup = pExpr;
114974 pNew = pTerm;
114976 exprCommute(pParse, pDup);
114977 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
114978 pNew->leftCursor = pLeft->iTable;
114979 pNew->u.leftColumn = pLeft->iColumn;
114980 testcase( (prereqLeft | extraRight) != prereqLeft );
114981 pNew->prereqRight = prereqLeft | extraRight;
114982 pNew->prereqAll = prereqAll;
114983 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
114987 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
114988 /* If a term is the BETWEEN operator, create two new virtual terms
114989 ** that define the range that the BETWEEN implements. For example:
114991 ** a BETWEEN b AND c
114993 ** is converted into:
114995 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
114997 ** The two new terms are added onto the end of the WhereClause object.
114998 ** The new terms are "dynamic" and are children of the original BETWEEN
114999 ** term. That means that if the BETWEEN term is coded, the children are
115000 ** skipped. Or, if the children are satisfied by an index, the original
115001 ** BETWEEN term is skipped.
115003 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
115004 ExprList *pList = pExpr->x.pList;
115005 int i;
115006 static const u8 ops[] = {TK_GE, TK_LE};
115007 assert( pList!=0 );
115008 assert( pList->nExpr==2 );
115009 for(i=0; i<2; i++){
115010 Expr *pNewExpr;
115011 int idxNew;
115012 pNewExpr = sqlite3PExpr(pParse, ops[i],
115013 sqlite3ExprDup(db, pExpr->pLeft, 0),
115014 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
115015 transferJoinMarkings(pNewExpr, pExpr);
115016 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
115017 testcase( idxNew==0 );
115018 exprAnalyze(pSrc, pWC, idxNew);
115019 pTerm = &pWC->a[idxTerm];
115020 pWC->a[idxNew].iParent = idxTerm;
115022 pTerm->nChild = 2;
115024 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
115026 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
115027 /* Analyze a term that is composed of two or more subterms connected by
115028 ** an OR operator.
115030 else if( pExpr->op==TK_OR ){
115031 assert( pWC->op==TK_AND );
115032 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
115033 pTerm = &pWC->a[idxTerm];
115035 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
115037 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
115038 /* Add constraints to reduce the search space on a LIKE or GLOB
115039 ** operator.
115041 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
115043 ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
115045 ** The last character of the prefix "abc" is incremented to form the
115046 ** termination condition "abd".
115048 if( pWC->op==TK_AND
115049 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
115051 Expr *pLeft; /* LHS of LIKE/GLOB operator */
115052 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
115053 Expr *pNewExpr1;
115054 Expr *pNewExpr2;
115055 int idxNew1;
115056 int idxNew2;
115057 const char *zCollSeqName; /* Name of collating sequence */
115059 pLeft = pExpr->x.pList->a[1].pExpr;
115060 pStr2 = sqlite3ExprDup(db, pStr1, 0);
115061 if( !db->mallocFailed ){
115062 u8 c, *pC; /* Last character before the first wildcard */
115063 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
115064 c = *pC;
115065 if( noCase ){
115066 /* The point is to increment the last character before the first
115067 ** wildcard. But if we increment '@', that will push it into the
115068 ** alphabetic range where case conversions will mess up the
115069 ** inequality. To avoid this, make sure to also run the full
115070 ** LIKE on all candidate expressions by clearing the isComplete flag
115072 if( c=='A'-1 ) isComplete = 0;
115073 c = sqlite3UpperToLower[c];
115075 *pC = c + 1;
115077 zCollSeqName = noCase ? "NOCASE" : "BINARY";
115078 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
115079 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
115080 sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
115081 pStr1, 0);
115082 transferJoinMarkings(pNewExpr1, pExpr);
115083 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
115084 testcase( idxNew1==0 );
115085 exprAnalyze(pSrc, pWC, idxNew1);
115086 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
115087 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
115088 sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
115089 pStr2, 0);
115090 transferJoinMarkings(pNewExpr2, pExpr);
115091 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
115092 testcase( idxNew2==0 );
115093 exprAnalyze(pSrc, pWC, idxNew2);
115094 pTerm = &pWC->a[idxTerm];
115095 if( isComplete ){
115096 pWC->a[idxNew1].iParent = idxTerm;
115097 pWC->a[idxNew2].iParent = idxTerm;
115098 pTerm->nChild = 2;
115101 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
115103 #ifndef SQLITE_OMIT_VIRTUALTABLE
115104 /* Add a WO_MATCH auxiliary term to the constraint set if the
115105 ** current expression is of the form: column MATCH expr.
115106 ** This information is used by the xBestIndex methods of
115107 ** virtual tables. The native query optimizer does not attempt
115108 ** to do anything with MATCH functions.
115110 if( isMatchOfColumn(pExpr) ){
115111 int idxNew;
115112 Expr *pRight, *pLeft;
115113 WhereTerm *pNewTerm;
115114 Bitmask prereqColumn, prereqExpr;
115116 pRight = pExpr->x.pList->a[0].pExpr;
115117 pLeft = pExpr->x.pList->a[1].pExpr;
115118 prereqExpr = exprTableUsage(pMaskSet, pRight);
115119 prereqColumn = exprTableUsage(pMaskSet, pLeft);
115120 if( (prereqExpr & prereqColumn)==0 ){
115121 Expr *pNewExpr;
115122 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
115123 0, sqlite3ExprDup(db, pRight, 0), 0);
115124 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
115125 testcase( idxNew==0 );
115126 pNewTerm = &pWC->a[idxNew];
115127 pNewTerm->prereqRight = prereqExpr;
115128 pNewTerm->leftCursor = pLeft->iTable;
115129 pNewTerm->u.leftColumn = pLeft->iColumn;
115130 pNewTerm->eOperator = WO_MATCH;
115131 pNewTerm->iParent = idxTerm;
115132 pTerm = &pWC->a[idxTerm];
115133 pTerm->nChild = 1;
115134 pTerm->wtFlags |= TERM_COPIED;
115135 pNewTerm->prereqAll = pTerm->prereqAll;
115138 #endif /* SQLITE_OMIT_VIRTUALTABLE */
115140 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
115141 /* When sqlite_stat3 histogram data is available an operator of the
115142 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
115143 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
115144 ** virtual term of that form.
115146 ** Note that the virtual term must be tagged with TERM_VNULL. This
115147 ** TERM_VNULL tag will suppress the not-null check at the beginning
115148 ** of the loop. Without the TERM_VNULL flag, the not-null check at
115149 ** the start of the loop will prevent any results from being returned.
115151 if( pExpr->op==TK_NOTNULL
115152 && pExpr->pLeft->op==TK_COLUMN
115153 && pExpr->pLeft->iColumn>=0
115154 && OptimizationEnabled(db, SQLITE_Stat3)
115156 Expr *pNewExpr;
115157 Expr *pLeft = pExpr->pLeft;
115158 int idxNew;
115159 WhereTerm *pNewTerm;
115161 pNewExpr = sqlite3PExpr(pParse, TK_GT,
115162 sqlite3ExprDup(db, pLeft, 0),
115163 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
115165 idxNew = whereClauseInsert(pWC, pNewExpr,
115166 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
115167 if( idxNew ){
115168 pNewTerm = &pWC->a[idxNew];
115169 pNewTerm->prereqRight = 0;
115170 pNewTerm->leftCursor = pLeft->iTable;
115171 pNewTerm->u.leftColumn = pLeft->iColumn;
115172 pNewTerm->eOperator = WO_GT;
115173 pNewTerm->iParent = idxTerm;
115174 pTerm = &pWC->a[idxTerm];
115175 pTerm->nChild = 1;
115176 pTerm->wtFlags |= TERM_COPIED;
115177 pNewTerm->prereqAll = pTerm->prereqAll;
115180 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
115182 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
115183 ** an index for tables to the left of the join.
115185 pTerm->prereqRight |= extraRight;
115189 ** This function searches pList for an entry that matches the iCol-th column
115190 ** of index pIdx.
115192 ** If such an expression is found, its index in pList->a[] is returned. If
115193 ** no expression is found, -1 is returned.
115195 static int findIndexCol(
115196 Parse *pParse, /* Parse context */
115197 ExprList *pList, /* Expression list to search */
115198 int iBase, /* Cursor for table associated with pIdx */
115199 Index *pIdx, /* Index to match column of */
115200 int iCol /* Column of index to match */
115202 int i;
115203 const char *zColl = pIdx->azColl[iCol];
115205 for(i=0; i<pList->nExpr; i++){
115206 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
115207 if( p->op==TK_COLUMN
115208 && p->iColumn==pIdx->aiColumn[iCol]
115209 && p->iTable==iBase
115211 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
115212 if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
115213 return i;
115218 return -1;
115222 ** Return true if the DISTINCT expression-list passed as the third argument
115223 ** is redundant.
115225 ** A DISTINCT list is redundant if the database contains some subset of
115226 ** columns that are unique and non-null.
115228 static int isDistinctRedundant(
115229 Parse *pParse, /* Parsing context */
115230 SrcList *pTabList, /* The FROM clause */
115231 WhereClause *pWC, /* The WHERE clause */
115232 ExprList *pDistinct /* The result set that needs to be DISTINCT */
115234 Table *pTab;
115235 Index *pIdx;
115236 int i;
115237 int iBase;
115239 /* If there is more than one table or sub-select in the FROM clause of
115240 ** this query, then it will not be possible to show that the DISTINCT
115241 ** clause is redundant. */
115242 if( pTabList->nSrc!=1 ) return 0;
115243 iBase = pTabList->a[0].iCursor;
115244 pTab = pTabList->a[0].pTab;
115246 /* If any of the expressions is an IPK column on table iBase, then return
115247 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
115248 ** current SELECT is a correlated sub-query.
115250 for(i=0; i<pDistinct->nExpr; i++){
115251 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
115252 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
115255 /* Loop through all indices on the table, checking each to see if it makes
115256 ** the DISTINCT qualifier redundant. It does so if:
115258 ** 1. The index is itself UNIQUE, and
115260 ** 2. All of the columns in the index are either part of the pDistinct
115261 ** list, or else the WHERE clause contains a term of the form "col=X",
115262 ** where X is a constant value. The collation sequences of the
115263 ** comparison and select-list expressions must match those of the index.
115265 ** 3. All of those index columns for which the WHERE clause does not
115266 ** contain a "col=X" term are subject to a NOT NULL constraint.
115268 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
115269 if( !IsUniqueIndex(pIdx) ) continue;
115270 for(i=0; i<pIdx->nKeyCol; i++){
115271 i16 iCol = pIdx->aiColumn[i];
115272 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
115273 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
115274 if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
115275 break;
115279 if( i==pIdx->nKeyCol ){
115280 /* This index implies that the DISTINCT qualifier is redundant. */
115281 return 1;
115285 return 0;
115290 ** Estimate the logarithm of the input value to base 2.
115292 static LogEst estLog(LogEst N){
115293 return N<=10 ? 0 : sqlite3LogEst(N) - 33;
115297 ** Two routines for printing the content of an sqlite3_index_info
115298 ** structure. Used for testing and debugging only. If neither
115299 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
115300 ** are no-ops.
115302 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
115303 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
115304 int i;
115305 if( !sqlite3WhereTrace ) return;
115306 for(i=0; i<p->nConstraint; i++){
115307 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
115309 p->aConstraint[i].iColumn,
115310 p->aConstraint[i].iTermOffset,
115311 p->aConstraint[i].op,
115312 p->aConstraint[i].usable);
115314 for(i=0; i<p->nOrderBy; i++){
115315 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
115317 p->aOrderBy[i].iColumn,
115318 p->aOrderBy[i].desc);
115321 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
115322 int i;
115323 if( !sqlite3WhereTrace ) return;
115324 for(i=0; i<p->nConstraint; i++){
115325 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
115327 p->aConstraintUsage[i].argvIndex,
115328 p->aConstraintUsage[i].omit);
115330 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
115331 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
115332 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
115333 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
115334 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
115336 #else
115337 #define TRACE_IDX_INPUTS(A)
115338 #define TRACE_IDX_OUTPUTS(A)
115339 #endif
115341 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
115343 ** Return TRUE if the WHERE clause term pTerm is of a form where it
115344 ** could be used with an index to access pSrc, assuming an appropriate
115345 ** index existed.
115347 static int termCanDriveIndex(
115348 WhereTerm *pTerm, /* WHERE clause term to check */
115349 struct SrcList_item *pSrc, /* Table we are trying to access */
115350 Bitmask notReady /* Tables in outer loops of the join */
115352 char aff;
115353 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
115354 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
115355 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
115356 if( pTerm->u.leftColumn<0 ) return 0;
115357 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
115358 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
115359 return 1;
115361 #endif
115364 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
115366 ** Generate code to construct the Index object for an automatic index
115367 ** and to set up the WhereLevel object pLevel so that the code generator
115368 ** makes use of the automatic index.
115370 static void constructAutomaticIndex(
115371 Parse *pParse, /* The parsing context */
115372 WhereClause *pWC, /* The WHERE clause */
115373 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
115374 Bitmask notReady, /* Mask of cursors that are not available */
115375 WhereLevel *pLevel /* Write new index here */
115377 int nKeyCol; /* Number of columns in the constructed index */
115378 WhereTerm *pTerm; /* A single term of the WHERE clause */
115379 WhereTerm *pWCEnd; /* End of pWC->a[] */
115380 Index *pIdx; /* Object describing the transient index */
115381 Vdbe *v; /* Prepared statement under construction */
115382 int addrInit; /* Address of the initialization bypass jump */
115383 Table *pTable; /* The table being indexed */
115384 int addrTop; /* Top of the index fill loop */
115385 int regRecord; /* Register holding an index record */
115386 int n; /* Column counter */
115387 int i; /* Loop counter */
115388 int mxBitCol; /* Maximum column in pSrc->colUsed */
115389 CollSeq *pColl; /* Collating sequence to on a column */
115390 WhereLoop *pLoop; /* The Loop object */
115391 char *zNotUsed; /* Extra space on the end of pIdx */
115392 Bitmask idxCols; /* Bitmap of columns used for indexing */
115393 Bitmask extraCols; /* Bitmap of additional columns */
115394 u8 sentWarning = 0; /* True if a warnning has been issued */
115396 /* Generate code to skip over the creation and initialization of the
115397 ** transient index on 2nd and subsequent iterations of the loop. */
115398 v = pParse->pVdbe;
115399 assert( v!=0 );
115400 addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
115402 /* Count the number of columns that will be added to the index
115403 ** and used to match WHERE clause constraints */
115404 nKeyCol = 0;
115405 pTable = pSrc->pTab;
115406 pWCEnd = &pWC->a[pWC->nTerm];
115407 pLoop = pLevel->pWLoop;
115408 idxCols = 0;
115409 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
115410 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
115411 int iCol = pTerm->u.leftColumn;
115412 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
115413 testcase( iCol==BMS );
115414 testcase( iCol==BMS-1 );
115415 if( !sentWarning ){
115416 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
115417 "automatic index on %s(%s)", pTable->zName,
115418 pTable->aCol[iCol].zName);
115419 sentWarning = 1;
115421 if( (idxCols & cMask)==0 ){
115422 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ) return;
115423 pLoop->aLTerm[nKeyCol++] = pTerm;
115424 idxCols |= cMask;
115428 assert( nKeyCol>0 );
115429 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
115430 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
115431 | WHERE_AUTO_INDEX;
115433 /* Count the number of additional columns needed to create a
115434 ** covering index. A "covering index" is an index that contains all
115435 ** columns that are needed by the query. With a covering index, the
115436 ** original table never needs to be accessed. Automatic indices must
115437 ** be a covering index because the index will not be updated if the
115438 ** original table changes and the index and table cannot both be used
115439 ** if they go out of sync.
115441 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
115442 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
115443 testcase( pTable->nCol==BMS-1 );
115444 testcase( pTable->nCol==BMS-2 );
115445 for(i=0; i<mxBitCol; i++){
115446 if( extraCols & MASKBIT(i) ) nKeyCol++;
115448 if( pSrc->colUsed & MASKBIT(BMS-1) ){
115449 nKeyCol += pTable->nCol - BMS + 1;
115451 pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
115453 /* Construct the Index object to describe this index */
115454 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
115455 if( pIdx==0 ) return;
115456 pLoop->u.btree.pIndex = pIdx;
115457 pIdx->zName = "auto-index";
115458 pIdx->pTable = pTable;
115459 n = 0;
115460 idxCols = 0;
115461 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
115462 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
115463 int iCol = pTerm->u.leftColumn;
115464 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
115465 testcase( iCol==BMS-1 );
115466 testcase( iCol==BMS );
115467 if( (idxCols & cMask)==0 ){
115468 Expr *pX = pTerm->pExpr;
115469 idxCols |= cMask;
115470 pIdx->aiColumn[n] = pTerm->u.leftColumn;
115471 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
115472 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
115477 assert( (u32)n==pLoop->u.btree.nEq );
115479 /* Add additional columns needed to make the automatic index into
115480 ** a covering index */
115481 for(i=0; i<mxBitCol; i++){
115482 if( extraCols & MASKBIT(i) ){
115483 pIdx->aiColumn[n] = i;
115484 pIdx->azColl[n] = "BINARY";
115488 if( pSrc->colUsed & MASKBIT(BMS-1) ){
115489 for(i=BMS-1; i<pTable->nCol; i++){
115490 pIdx->aiColumn[n] = i;
115491 pIdx->azColl[n] = "BINARY";
115495 assert( n==nKeyCol );
115496 pIdx->aiColumn[n] = -1;
115497 pIdx->azColl[n] = "BINARY";
115499 /* Create the automatic index */
115500 assert( pLevel->iIdxCur>=0 );
115501 pLevel->iIdxCur = pParse->nTab++;
115502 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
115503 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
115504 VdbeComment((v, "for %s", pTable->zName));
115506 /* Fill the automatic index with content */
115507 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
115508 regRecord = sqlite3GetTempReg(pParse);
115509 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
115510 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
115511 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
115512 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
115513 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
115514 sqlite3VdbeJumpHere(v, addrTop);
115515 sqlite3ReleaseTempReg(pParse, regRecord);
115517 /* Jump here when skipping the initialization */
115518 sqlite3VdbeJumpHere(v, addrInit);
115520 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
115522 #ifndef SQLITE_OMIT_VIRTUALTABLE
115524 ** Allocate and populate an sqlite3_index_info structure. It is the
115525 ** responsibility of the caller to eventually release the structure
115526 ** by passing the pointer returned by this function to sqlite3_free().
115528 static sqlite3_index_info *allocateIndexInfo(
115529 Parse *pParse,
115530 WhereClause *pWC,
115531 struct SrcList_item *pSrc,
115532 ExprList *pOrderBy
115534 int i, j;
115535 int nTerm;
115536 struct sqlite3_index_constraint *pIdxCons;
115537 struct sqlite3_index_orderby *pIdxOrderBy;
115538 struct sqlite3_index_constraint_usage *pUsage;
115539 WhereTerm *pTerm;
115540 int nOrderBy;
115541 sqlite3_index_info *pIdxInfo;
115543 /* Count the number of possible WHERE clause constraints referring
115544 ** to this virtual table */
115545 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
115546 if( pTerm->leftCursor != pSrc->iCursor ) continue;
115547 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
115548 testcase( pTerm->eOperator & WO_IN );
115549 testcase( pTerm->eOperator & WO_ISNULL );
115550 testcase( pTerm->eOperator & WO_ALL );
115551 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
115552 if( pTerm->wtFlags & TERM_VNULL ) continue;
115553 nTerm++;
115556 /* If the ORDER BY clause contains only columns in the current
115557 ** virtual table then allocate space for the aOrderBy part of
115558 ** the sqlite3_index_info structure.
115560 nOrderBy = 0;
115561 if( pOrderBy ){
115562 int n = pOrderBy->nExpr;
115563 for(i=0; i<n; i++){
115564 Expr *pExpr = pOrderBy->a[i].pExpr;
115565 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
115567 if( i==n){
115568 nOrderBy = n;
115572 /* Allocate the sqlite3_index_info structure
115574 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
115575 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
115576 + sizeof(*pIdxOrderBy)*nOrderBy );
115577 if( pIdxInfo==0 ){
115578 sqlite3ErrorMsg(pParse, "out of memory");
115579 return 0;
115582 /* Initialize the structure. The sqlite3_index_info structure contains
115583 ** many fields that are declared "const" to prevent xBestIndex from
115584 ** changing them. We have to do some funky casting in order to
115585 ** initialize those fields.
115587 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
115588 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
115589 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
115590 *(int*)&pIdxInfo->nConstraint = nTerm;
115591 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
115592 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
115593 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
115594 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
115595 pUsage;
115597 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
115598 u8 op;
115599 if( pTerm->leftCursor != pSrc->iCursor ) continue;
115600 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
115601 testcase( pTerm->eOperator & WO_IN );
115602 testcase( pTerm->eOperator & WO_ISNULL );
115603 testcase( pTerm->eOperator & WO_ALL );
115604 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
115605 if( pTerm->wtFlags & TERM_VNULL ) continue;
115606 pIdxCons[j].iColumn = pTerm->u.leftColumn;
115607 pIdxCons[j].iTermOffset = i;
115608 op = (u8)pTerm->eOperator & WO_ALL;
115609 if( op==WO_IN ) op = WO_EQ;
115610 pIdxCons[j].op = op;
115611 /* The direct assignment in the previous line is possible only because
115612 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
115613 ** following asserts verify this fact. */
115614 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
115615 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
115616 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
115617 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
115618 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
115619 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
115620 assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
115623 for(i=0; i<nOrderBy; i++){
115624 Expr *pExpr = pOrderBy->a[i].pExpr;
115625 pIdxOrderBy[i].iColumn = pExpr->iColumn;
115626 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
115629 return pIdxInfo;
115633 ** The table object reference passed as the second argument to this function
115634 ** must represent a virtual table. This function invokes the xBestIndex()
115635 ** method of the virtual table with the sqlite3_index_info object that
115636 ** comes in as the 3rd argument to this function.
115638 ** If an error occurs, pParse is populated with an error message and a
115639 ** non-zero value is returned. Otherwise, 0 is returned and the output
115640 ** part of the sqlite3_index_info structure is left populated.
115642 ** Whether or not an error is returned, it is the responsibility of the
115643 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
115644 ** that this is required.
115646 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
115647 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
115648 int i;
115649 int rc;
115651 TRACE_IDX_INPUTS(p);
115652 rc = pVtab->pModule->xBestIndex(pVtab, p);
115653 TRACE_IDX_OUTPUTS(p);
115655 if( rc!=SQLITE_OK ){
115656 if( rc==SQLITE_NOMEM ){
115657 pParse->db->mallocFailed = 1;
115658 }else if( !pVtab->zErrMsg ){
115659 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
115660 }else{
115661 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
115664 sqlite3_free(pVtab->zErrMsg);
115665 pVtab->zErrMsg = 0;
115667 for(i=0; i<p->nConstraint; i++){
115668 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
115669 sqlite3ErrorMsg(pParse,
115670 "table %s: xBestIndex returned an invalid plan", pTab->zName);
115674 return pParse->nErr;
115676 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
115679 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
115681 ** Estimate the location of a particular key among all keys in an
115682 ** index. Store the results in aStat as follows:
115684 ** aStat[0] Est. number of rows less than pVal
115685 ** aStat[1] Est. number of rows equal to pVal
115687 ** Return SQLITE_OK on success.
115689 static void whereKeyStats(
115690 Parse *pParse, /* Database connection */
115691 Index *pIdx, /* Index to consider domain of */
115692 UnpackedRecord *pRec, /* Vector of values to consider */
115693 int roundUp, /* Round up if true. Round down if false */
115694 tRowcnt *aStat /* OUT: stats written here */
115696 IndexSample *aSample = pIdx->aSample;
115697 int iCol; /* Index of required stats in anEq[] etc. */
115698 int iMin = 0; /* Smallest sample not yet tested */
115699 int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
115700 int iTest; /* Next sample to test */
115701 int res; /* Result of comparison operation */
115703 #ifndef SQLITE_DEBUG
115704 UNUSED_PARAMETER( pParse );
115705 #endif
115706 assert( pRec!=0 );
115707 iCol = pRec->nField - 1;
115708 assert( pIdx->nSample>0 );
115709 assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
115711 iTest = (iMin+i)/2;
115712 res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
115713 if( res<0 ){
115714 iMin = iTest+1;
115715 }else{
115716 i = iTest;
115718 }while( res && iMin<i );
115720 #ifdef SQLITE_DEBUG
115721 /* The following assert statements check that the binary search code
115722 ** above found the right answer. This block serves no purpose other
115723 ** than to invoke the asserts. */
115724 if( res==0 ){
115725 /* If (res==0) is true, then sample $i must be equal to pRec */
115726 assert( i<pIdx->nSample );
115727 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
115728 || pParse->db->mallocFailed );
115729 }else{
115730 /* Otherwise, pRec must be smaller than sample $i and larger than
115731 ** sample ($i-1). */
115732 assert( i==pIdx->nSample
115733 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
115734 || pParse->db->mallocFailed );
115735 assert( i==0
115736 || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
115737 || pParse->db->mallocFailed );
115739 #endif /* ifdef SQLITE_DEBUG */
115741 /* At this point, aSample[i] is the first sample that is greater than
115742 ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
115743 ** than pVal. If aSample[i]==pVal, then res==0.
115745 if( res==0 ){
115746 aStat[0] = aSample[i].anLt[iCol];
115747 aStat[1] = aSample[i].anEq[iCol];
115748 }else{
115749 tRowcnt iLower, iUpper, iGap;
115750 if( i==0 ){
115751 iLower = 0;
115752 iUpper = aSample[0].anLt[iCol];
115753 }else{
115754 i64 nRow0 = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
115755 iUpper = i>=pIdx->nSample ? nRow0 : aSample[i].anLt[iCol];
115756 iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
115758 aStat[1] = pIdx->aAvgEq[iCol];
115759 if( iLower>=iUpper ){
115760 iGap = 0;
115761 }else{
115762 iGap = iUpper - iLower;
115764 if( roundUp ){
115765 iGap = (iGap*2)/3;
115766 }else{
115767 iGap = iGap/3;
115769 aStat[0] = iLower + iGap;
115772 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
115775 ** If it is not NULL, pTerm is a term that provides an upper or lower
115776 ** bound on a range scan. Without considering pTerm, it is estimated
115777 ** that the scan will visit nNew rows. This function returns the number
115778 ** estimated to be visited after taking pTerm into account.
115780 ** If the user explicitly specified a likelihood() value for this term,
115781 ** then the return value is the likelihood multiplied by the number of
115782 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
115783 ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
115785 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
115786 LogEst nRet = nNew;
115787 if( pTerm ){
115788 if( pTerm->truthProb<=0 ){
115789 nRet += pTerm->truthProb;
115790 }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
115791 nRet -= 20; assert( 20==sqlite3LogEst(4) );
115794 return nRet;
115797 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
115799 ** This function is called to estimate the number of rows visited by a
115800 ** range-scan on a skip-scan index. For example:
115802 ** CREATE INDEX i1 ON t1(a, b, c);
115803 ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
115805 ** Value pLoop->nOut is currently set to the estimated number of rows
115806 ** visited for scanning (a=? AND b=?). This function reduces that estimate
115807 ** by some factor to account for the (c BETWEEN ? AND ?) expression based
115808 ** on the stat4 data for the index. this scan will be peformed multiple
115809 ** times (once for each (a,b) combination that matches a=?) is dealt with
115810 ** by the caller.
115812 ** It does this by scanning through all stat4 samples, comparing values
115813 ** extracted from pLower and pUpper with the corresponding column in each
115814 ** sample. If L and U are the number of samples found to be less than or
115815 ** equal to the values extracted from pLower and pUpper respectively, and
115816 ** N is the total number of samples, the pLoop->nOut value is adjusted
115817 ** as follows:
115819 ** nOut = nOut * ( min(U - L, 1) / N )
115821 ** If pLower is NULL, or a value cannot be extracted from the term, L is
115822 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
115823 ** U is set to N.
115825 ** Normally, this function sets *pbDone to 1 before returning. However,
115826 ** if no value can be extracted from either pLower or pUpper (and so the
115827 ** estimate of the number of rows delivered remains unchanged), *pbDone
115828 ** is left as is.
115830 ** If an error occurs, an SQLite error code is returned. Otherwise,
115831 ** SQLITE_OK.
115833 static int whereRangeSkipScanEst(
115834 Parse *pParse, /* Parsing & code generating context */
115835 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
115836 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
115837 WhereLoop *pLoop, /* Update the .nOut value of this loop */
115838 int *pbDone /* Set to true if at least one expr. value extracted */
115840 Index *p = pLoop->u.btree.pIndex;
115841 int nEq = pLoop->u.btree.nEq;
115842 sqlite3 *db = pParse->db;
115843 int nLower = -1;
115844 int nUpper = p->nSample+1;
115845 int rc = SQLITE_OK;
115846 int iCol = p->aiColumn[nEq];
115847 u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
115848 CollSeq *pColl;
115850 sqlite3_value *p1 = 0; /* Value extracted from pLower */
115851 sqlite3_value *p2 = 0; /* Value extracted from pUpper */
115852 sqlite3_value *pVal = 0; /* Value extracted from record */
115854 pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
115855 if( pLower ){
115856 rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
115857 nLower = 0;
115859 if( pUpper && rc==SQLITE_OK ){
115860 rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
115861 nUpper = p2 ? 0 : p->nSample;
115864 if( p1 || p2 ){
115865 int i;
115866 int nDiff;
115867 for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
115868 rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
115869 if( rc==SQLITE_OK && p1 ){
115870 int res = sqlite3MemCompare(p1, pVal, pColl);
115871 if( res>=0 ) nLower++;
115873 if( rc==SQLITE_OK && p2 ){
115874 int res = sqlite3MemCompare(p2, pVal, pColl);
115875 if( res>=0 ) nUpper++;
115878 nDiff = (nUpper - nLower);
115879 if( nDiff<=0 ) nDiff = 1;
115881 /* If there is both an upper and lower bound specified, and the
115882 ** comparisons indicate that they are close together, use the fallback
115883 ** method (assume that the scan visits 1/64 of the rows) for estimating
115884 ** the number of rows visited. Otherwise, estimate the number of rows
115885 ** using the method described in the header comment for this function. */
115886 if( nDiff!=1 || pUpper==0 || pLower==0 ){
115887 int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
115888 pLoop->nOut -= nAdjust;
115889 *pbDone = 1;
115890 WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
115891 nLower, nUpper, nAdjust*-1, pLoop->nOut));
115894 }else{
115895 assert( *pbDone==0 );
115898 sqlite3ValueFree(p1);
115899 sqlite3ValueFree(p2);
115900 sqlite3ValueFree(pVal);
115902 return rc;
115904 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
115907 ** This function is used to estimate the number of rows that will be visited
115908 ** by scanning an index for a range of values. The range may have an upper
115909 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
115910 ** and lower bounds are represented by pLower and pUpper respectively. For
115911 ** example, assuming that index p is on t1(a):
115913 ** ... FROM t1 WHERE a > ? AND a < ? ...
115914 ** |_____| |_____|
115915 ** | |
115916 ** pLower pUpper
115918 ** If either of the upper or lower bound is not present, then NULL is passed in
115919 ** place of the corresponding WhereTerm.
115921 ** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
115922 ** column subject to the range constraint. Or, equivalently, the number of
115923 ** equality constraints optimized by the proposed index scan. For example,
115924 ** assuming index p is on t1(a, b), and the SQL query is:
115926 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
115928 ** then nEq is set to 1 (as the range restricted column, b, is the second
115929 ** left-most column of the index). Or, if the query is:
115931 ** ... FROM t1 WHERE a > ? AND a < ? ...
115933 ** then nEq is set to 0.
115935 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
115936 ** number of rows that the index scan is expected to visit without
115937 ** considering the range constraints. If nEq is 0, this is the number of
115938 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
115939 ** to account for the range constraints pLower and pUpper.
115941 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
115942 ** used, a single range inequality reduces the search space by a factor of 4.
115943 ** and a pair of constraints (x>? AND x<?) reduces the expected number of
115944 ** rows visited by a factor of 64.
115946 static int whereRangeScanEst(
115947 Parse *pParse, /* Parsing & code generating context */
115948 WhereLoopBuilder *pBuilder,
115949 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
115950 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
115951 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
115953 int rc = SQLITE_OK;
115954 int nOut = pLoop->nOut;
115955 LogEst nNew;
115957 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
115958 Index *p = pLoop->u.btree.pIndex;
115959 int nEq = pLoop->u.btree.nEq;
115961 if( p->nSample>0
115962 && nEq<p->nSampleCol
115963 && OptimizationEnabled(pParse->db, SQLITE_Stat3)
115965 if( nEq==pBuilder->nRecValid ){
115966 UnpackedRecord *pRec = pBuilder->pRec;
115967 tRowcnt a[2];
115968 u8 aff;
115970 /* Variable iLower will be set to the estimate of the number of rows in
115971 ** the index that are less than the lower bound of the range query. The
115972 ** lower bound being the concatenation of $P and $L, where $P is the
115973 ** key-prefix formed by the nEq values matched against the nEq left-most
115974 ** columns of the index, and $L is the value in pLower.
115976 ** Or, if pLower is NULL or $L cannot be extracted from it (because it
115977 ** is not a simple variable or literal value), the lower bound of the
115978 ** range is $P. Due to a quirk in the way whereKeyStats() works, even
115979 ** if $L is available, whereKeyStats() is called for both ($P) and
115980 ** ($P:$L) and the larger of the two returned values used.
115982 ** Similarly, iUpper is to be set to the estimate of the number of rows
115983 ** less than the upper bound of the range query. Where the upper bound
115984 ** is either ($P) or ($P:$U). Again, even if $U is available, both values
115985 ** of iUpper are requested of whereKeyStats() and the smaller used.
115987 tRowcnt iLower;
115988 tRowcnt iUpper;
115990 if( pRec ){
115991 testcase( pRec->nField!=pBuilder->nRecValid );
115992 pRec->nField = pBuilder->nRecValid;
115994 if( nEq==p->nKeyCol ){
115995 aff = SQLITE_AFF_INTEGER;
115996 }else{
115997 aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
115999 /* Determine iLower and iUpper using ($P) only. */
116000 if( nEq==0 ){
116001 iLower = 0;
116002 iUpper = sqlite3LogEstToInt(p->aiRowLogEst[0]);
116003 }else{
116004 /* Note: this call could be optimized away - since the same values must
116005 ** have been requested when testing key $P in whereEqualScanEst(). */
116006 whereKeyStats(pParse, p, pRec, 0, a);
116007 iLower = a[0];
116008 iUpper = a[0] + a[1];
116011 assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
116012 assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
116013 assert( p->aSortOrder!=0 );
116014 if( p->aSortOrder[nEq] ){
116015 /* The roles of pLower and pUpper are swapped for a DESC index */
116016 SWAP(WhereTerm*, pLower, pUpper);
116019 /* If possible, improve on the iLower estimate using ($P:$L). */
116020 if( pLower ){
116021 int bOk; /* True if value is extracted from pExpr */
116022 Expr *pExpr = pLower->pExpr->pRight;
116023 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
116024 if( rc==SQLITE_OK && bOk ){
116025 tRowcnt iNew;
116026 whereKeyStats(pParse, p, pRec, 0, a);
116027 iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
116028 if( iNew>iLower ) iLower = iNew;
116029 nOut--;
116030 pLower = 0;
116034 /* If possible, improve on the iUpper estimate using ($P:$U). */
116035 if( pUpper ){
116036 int bOk; /* True if value is extracted from pExpr */
116037 Expr *pExpr = pUpper->pExpr->pRight;
116038 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
116039 if( rc==SQLITE_OK && bOk ){
116040 tRowcnt iNew;
116041 whereKeyStats(pParse, p, pRec, 1, a);
116042 iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
116043 if( iNew<iUpper ) iUpper = iNew;
116044 nOut--;
116045 pUpper = 0;
116049 pBuilder->pRec = pRec;
116050 if( rc==SQLITE_OK ){
116051 if( iUpper>iLower ){
116052 nNew = sqlite3LogEst(iUpper - iLower);
116053 }else{
116054 nNew = 10; assert( 10==sqlite3LogEst(2) );
116056 if( nNew<nOut ){
116057 nOut = nNew;
116059 WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
116060 (u32)iLower, (u32)iUpper, nOut));
116062 }else{
116063 int bDone = 0;
116064 rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
116065 if( bDone ) return rc;
116068 #else
116069 UNUSED_PARAMETER(pParse);
116070 UNUSED_PARAMETER(pBuilder);
116071 assert( pLower || pUpper );
116072 #endif
116073 assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
116074 nNew = whereRangeAdjust(pLower, nOut);
116075 nNew = whereRangeAdjust(pUpper, nNew);
116077 /* TUNING: If there is both an upper and lower limit, assume the range is
116078 ** reduced by an additional 75%. This means that, by default, an open-ended
116079 ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
116080 ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
116081 ** match 1/64 of the index. */
116082 if( pLower && pUpper ) nNew -= 20;
116084 nOut -= (pLower!=0) + (pUpper!=0);
116085 if( nNew<10 ) nNew = 10;
116086 if( nNew<nOut ) nOut = nNew;
116087 #if defined(WHERETRACE_ENABLED)
116088 if( pLoop->nOut>nOut ){
116089 WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
116090 pLoop->nOut, nOut));
116092 #endif
116093 pLoop->nOut = (LogEst)nOut;
116094 return rc;
116097 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
116099 ** Estimate the number of rows that will be returned based on
116100 ** an equality constraint x=VALUE and where that VALUE occurs in
116101 ** the histogram data. This only works when x is the left-most
116102 ** column of an index and sqlite_stat3 histogram data is available
116103 ** for that index. When pExpr==NULL that means the constraint is
116104 ** "x IS NULL" instead of "x=VALUE".
116106 ** Write the estimated row count into *pnRow and return SQLITE_OK.
116107 ** If unable to make an estimate, leave *pnRow unchanged and return
116108 ** non-zero.
116110 ** This routine can fail if it is unable to load a collating sequence
116111 ** required for string comparison, or if unable to allocate memory
116112 ** for a UTF conversion required for comparison. The error is stored
116113 ** in the pParse structure.
116115 static int whereEqualScanEst(
116116 Parse *pParse, /* Parsing & code generating context */
116117 WhereLoopBuilder *pBuilder,
116118 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
116119 tRowcnt *pnRow /* Write the revised row estimate here */
116121 Index *p = pBuilder->pNew->u.btree.pIndex;
116122 int nEq = pBuilder->pNew->u.btree.nEq;
116123 UnpackedRecord *pRec = pBuilder->pRec;
116124 u8 aff; /* Column affinity */
116125 int rc; /* Subfunction return code */
116126 tRowcnt a[2]; /* Statistics */
116127 int bOk;
116129 assert( nEq>=1 );
116130 assert( nEq<=p->nColumn );
116131 assert( p->aSample!=0 );
116132 assert( p->nSample>0 );
116133 assert( pBuilder->nRecValid<nEq );
116135 /* If values are not available for all fields of the index to the left
116136 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
116137 if( pBuilder->nRecValid<(nEq-1) ){
116138 return SQLITE_NOTFOUND;
116141 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
116142 ** below would return the same value. */
116143 if( nEq>=p->nColumn ){
116144 *pnRow = 1;
116145 return SQLITE_OK;
116148 aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
116149 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
116150 pBuilder->pRec = pRec;
116151 if( rc!=SQLITE_OK ) return rc;
116152 if( bOk==0 ) return SQLITE_NOTFOUND;
116153 pBuilder->nRecValid = nEq;
116155 whereKeyStats(pParse, p, pRec, 0, a);
116156 WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
116157 *pnRow = a[1];
116159 return rc;
116161 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
116163 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
116165 ** Estimate the number of rows that will be returned based on
116166 ** an IN constraint where the right-hand side of the IN operator
116167 ** is a list of values. Example:
116169 ** WHERE x IN (1,2,3,4)
116171 ** Write the estimated row count into *pnRow and return SQLITE_OK.
116172 ** If unable to make an estimate, leave *pnRow unchanged and return
116173 ** non-zero.
116175 ** This routine can fail if it is unable to load a collating sequence
116176 ** required for string comparison, or if unable to allocate memory
116177 ** for a UTF conversion required for comparison. The error is stored
116178 ** in the pParse structure.
116180 static int whereInScanEst(
116181 Parse *pParse, /* Parsing & code generating context */
116182 WhereLoopBuilder *pBuilder,
116183 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
116184 tRowcnt *pnRow /* Write the revised row estimate here */
116186 Index *p = pBuilder->pNew->u.btree.pIndex;
116187 i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
116188 int nRecValid = pBuilder->nRecValid;
116189 int rc = SQLITE_OK; /* Subfunction return code */
116190 tRowcnt nEst; /* Number of rows for a single term */
116191 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
116192 int i; /* Loop counter */
116194 assert( p->aSample!=0 );
116195 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
116196 nEst = nRow0;
116197 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
116198 nRowEst += nEst;
116199 pBuilder->nRecValid = nRecValid;
116202 if( rc==SQLITE_OK ){
116203 if( nRowEst > nRow0 ) nRowEst = nRow0;
116204 *pnRow = nRowEst;
116205 WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
116207 assert( pBuilder->nRecValid==nRecValid );
116208 return rc;
116210 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
116213 ** Disable a term in the WHERE clause. Except, do not disable the term
116214 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
116215 ** or USING clause of that join.
116217 ** Consider the term t2.z='ok' in the following queries:
116219 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
116220 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
116221 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
116223 ** The t2.z='ok' is disabled in the in (2) because it originates
116224 ** in the ON clause. The term is disabled in (3) because it is not part
116225 ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
116227 ** Disabling a term causes that term to not be tested in the inner loop
116228 ** of the join. Disabling is an optimization. When terms are satisfied
116229 ** by indices, we disable them to prevent redundant tests in the inner
116230 ** loop. We would get the correct results if nothing were ever disabled,
116231 ** but joins might run a little slower. The trick is to disable as much
116232 ** as we can without disabling too much. If we disabled in (1), we'd get
116233 ** the wrong answer. See ticket #813.
116235 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
116236 if( pTerm
116237 && (pTerm->wtFlags & TERM_CODED)==0
116238 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
116239 && (pLevel->notReady & pTerm->prereqAll)==0
116241 pTerm->wtFlags |= TERM_CODED;
116242 if( pTerm->iParent>=0 ){
116243 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
116244 if( (--pOther->nChild)==0 ){
116245 disableTerm(pLevel, pOther);
116252 ** Code an OP_Affinity opcode to apply the column affinity string zAff
116253 ** to the n registers starting at base.
116255 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
116256 ** beginning and end of zAff are ignored. If all entries in zAff are
116257 ** SQLITE_AFF_NONE, then no code gets generated.
116259 ** This routine makes its own copy of zAff so that the caller is free
116260 ** to modify zAff after this routine returns.
116262 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
116263 Vdbe *v = pParse->pVdbe;
116264 if( zAff==0 ){
116265 assert( pParse->db->mallocFailed );
116266 return;
116268 assert( v!=0 );
116270 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
116271 ** and end of the affinity string.
116273 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
116275 base++;
116276 zAff++;
116278 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
116282 /* Code the OP_Affinity opcode if there is anything left to do. */
116283 if( n>0 ){
116284 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
116285 sqlite3VdbeChangeP4(v, -1, zAff, n);
116286 sqlite3ExprCacheAffinityChange(pParse, base, n);
116292 ** Generate code for a single equality term of the WHERE clause. An equality
116293 ** term can be either X=expr or X IN (...). pTerm is the term to be
116294 ** coded.
116296 ** The current value for the constraint is left in register iReg.
116298 ** For a constraint of the form X=expr, the expression is evaluated and its
116299 ** result is left on the stack. For constraints of the form X IN (...)
116300 ** this routine sets up a loop that will iterate over all values of X.
116302 static int codeEqualityTerm(
116303 Parse *pParse, /* The parsing context */
116304 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
116305 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
116306 int iEq, /* Index of the equality term within this level */
116307 int bRev, /* True for reverse-order IN operations */
116308 int iTarget /* Attempt to leave results in this register */
116310 Expr *pX = pTerm->pExpr;
116311 Vdbe *v = pParse->pVdbe;
116312 int iReg; /* Register holding results */
116314 assert( iTarget>0 );
116315 if( pX->op==TK_EQ ){
116316 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
116317 }else if( pX->op==TK_ISNULL ){
116318 iReg = iTarget;
116319 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
116320 #ifndef SQLITE_OMIT_SUBQUERY
116321 }else{
116322 int eType;
116323 int iTab;
116324 struct InLoop *pIn;
116325 WhereLoop *pLoop = pLevel->pWLoop;
116327 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
116328 && pLoop->u.btree.pIndex!=0
116329 && pLoop->u.btree.pIndex->aSortOrder[iEq]
116331 testcase( iEq==0 );
116332 testcase( bRev );
116333 bRev = !bRev;
116335 assert( pX->op==TK_IN );
116336 iReg = iTarget;
116337 eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
116338 if( eType==IN_INDEX_INDEX_DESC ){
116339 testcase( bRev );
116340 bRev = !bRev;
116342 iTab = pX->iTable;
116343 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
116344 VdbeCoverageIf(v, bRev);
116345 VdbeCoverageIf(v, !bRev);
116346 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
116347 pLoop->wsFlags |= WHERE_IN_ABLE;
116348 if( pLevel->u.in.nIn==0 ){
116349 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
116351 pLevel->u.in.nIn++;
116352 pLevel->u.in.aInLoop =
116353 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
116354 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
116355 pIn = pLevel->u.in.aInLoop;
116356 if( pIn ){
116357 pIn += pLevel->u.in.nIn - 1;
116358 pIn->iCur = iTab;
116359 if( eType==IN_INDEX_ROWID ){
116360 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
116361 }else{
116362 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
116364 pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
116365 sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
116366 }else{
116367 pLevel->u.in.nIn = 0;
116369 #endif
116371 disableTerm(pLevel, pTerm);
116372 return iReg;
116376 ** Generate code that will evaluate all == and IN constraints for an
116377 ** index scan.
116379 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
116380 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
116381 ** The index has as many as three equality constraints, but in this
116382 ** example, the third "c" value is an inequality. So only two
116383 ** constraints are coded. This routine will generate code to evaluate
116384 ** a==5 and b IN (1,2,3). The current values for a and b will be stored
116385 ** in consecutive registers and the index of the first register is returned.
116387 ** In the example above nEq==2. But this subroutine works for any value
116388 ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
116389 ** The only thing it does is allocate the pLevel->iMem memory cell and
116390 ** compute the affinity string.
116392 ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
116393 ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
116394 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
116395 ** occurs after the nEq quality constraints.
116397 ** This routine allocates a range of nEq+nExtraReg memory cells and returns
116398 ** the index of the first memory cell in that range. The code that
116399 ** calls this routine will use that memory range to store keys for
116400 ** start and termination conditions of the loop.
116401 ** key value of the loop. If one or more IN operators appear, then
116402 ** this routine allocates an additional nEq memory cells for internal
116403 ** use.
116405 ** Before returning, *pzAff is set to point to a buffer containing a
116406 ** copy of the column affinity string of the index allocated using
116407 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
116408 ** with equality constraints that use NONE affinity are set to
116409 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
116411 ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
116412 ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
116414 ** In the example above, the index on t1(a) has TEXT affinity. But since
116415 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
116416 ** no conversion should be attempted before using a t2.b value as part of
116417 ** a key to search the index. Hence the first byte in the returned affinity
116418 ** string in this example would be set to SQLITE_AFF_NONE.
116420 static int codeAllEqualityTerms(
116421 Parse *pParse, /* Parsing context */
116422 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
116423 int bRev, /* Reverse the order of IN operators */
116424 int nExtraReg, /* Number of extra registers to allocate */
116425 char **pzAff /* OUT: Set to point to affinity string */
116427 u16 nEq; /* The number of == or IN constraints to code */
116428 u16 nSkip; /* Number of left-most columns to skip */
116429 Vdbe *v = pParse->pVdbe; /* The vm under construction */
116430 Index *pIdx; /* The index being used for this loop */
116431 WhereTerm *pTerm; /* A single constraint term */
116432 WhereLoop *pLoop; /* The WhereLoop object */
116433 int j; /* Loop counter */
116434 int regBase; /* Base register */
116435 int nReg; /* Number of registers to allocate */
116436 char *zAff; /* Affinity string to return */
116438 /* This module is only called on query plans that use an index. */
116439 pLoop = pLevel->pWLoop;
116440 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
116441 nEq = pLoop->u.btree.nEq;
116442 nSkip = pLoop->u.btree.nSkip;
116443 pIdx = pLoop->u.btree.pIndex;
116444 assert( pIdx!=0 );
116446 /* Figure out how many memory cells we will need then allocate them.
116448 regBase = pParse->nMem + 1;
116449 nReg = pLoop->u.btree.nEq + nExtraReg;
116450 pParse->nMem += nReg;
116452 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
116453 if( !zAff ){
116454 pParse->db->mallocFailed = 1;
116457 if( nSkip ){
116458 int iIdxCur = pLevel->iIdxCur;
116459 sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
116460 VdbeCoverageIf(v, bRev==0);
116461 VdbeCoverageIf(v, bRev!=0);
116462 VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
116463 j = sqlite3VdbeAddOp0(v, OP_Goto);
116464 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
116465 iIdxCur, 0, regBase, nSkip);
116466 VdbeCoverageIf(v, bRev==0);
116467 VdbeCoverageIf(v, bRev!=0);
116468 sqlite3VdbeJumpHere(v, j);
116469 for(j=0; j<nSkip; j++){
116470 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
116471 assert( pIdx->aiColumn[j]>=0 );
116472 VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
116476 /* Evaluate the equality constraints
116478 assert( zAff==0 || (int)strlen(zAff)>=nEq );
116479 for(j=nSkip; j<nEq; j++){
116480 int r1;
116481 pTerm = pLoop->aLTerm[j];
116482 assert( pTerm!=0 );
116483 /* The following testcase is true for indices with redundant columns.
116484 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
116485 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
116486 testcase( pTerm->wtFlags & TERM_VIRTUAL );
116487 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
116488 if( r1!=regBase+j ){
116489 if( nReg==1 ){
116490 sqlite3ReleaseTempReg(pParse, regBase);
116491 regBase = r1;
116492 }else{
116493 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
116496 testcase( pTerm->eOperator & WO_ISNULL );
116497 testcase( pTerm->eOperator & WO_IN );
116498 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
116499 Expr *pRight = pTerm->pExpr->pRight;
116500 if( sqlite3ExprCanBeNull(pRight) ){
116501 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
116502 VdbeCoverage(v);
116504 if( zAff ){
116505 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
116506 zAff[j] = SQLITE_AFF_NONE;
116508 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
116509 zAff[j] = SQLITE_AFF_NONE;
116514 *pzAff = zAff;
116515 return regBase;
116518 #ifndef SQLITE_OMIT_EXPLAIN
116520 ** This routine is a helper for explainIndexRange() below
116522 ** pStr holds the text of an expression that we are building up one term
116523 ** at a time. This routine adds a new term to the end of the expression.
116524 ** Terms are separated by AND so add the "AND" text for second and subsequent
116525 ** terms only.
116527 static void explainAppendTerm(
116528 StrAccum *pStr, /* The text expression being built */
116529 int iTerm, /* Index of this term. First is zero */
116530 const char *zColumn, /* Name of the column */
116531 const char *zOp /* Name of the operator */
116533 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
116534 sqlite3StrAccumAppendAll(pStr, zColumn);
116535 sqlite3StrAccumAppend(pStr, zOp, 1);
116536 sqlite3StrAccumAppend(pStr, "?", 1);
116540 ** Argument pLevel describes a strategy for scanning table pTab. This
116541 ** function appends text to pStr that describes the subset of table
116542 ** rows scanned by the strategy in the form of an SQL expression.
116544 ** For example, if the query:
116546 ** SELECT * FROM t1 WHERE a=1 AND b>2;
116548 ** is run and there is an index on (a, b), then this function returns a
116549 ** string similar to:
116551 ** "a=? AND b>?"
116553 static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){
116554 Index *pIndex = pLoop->u.btree.pIndex;
116555 u16 nEq = pLoop->u.btree.nEq;
116556 u16 nSkip = pLoop->u.btree.nSkip;
116557 int i, j;
116558 Column *aCol = pTab->aCol;
116559 i16 *aiColumn = pIndex->aiColumn;
116561 if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
116562 sqlite3StrAccumAppend(pStr, " (", 2);
116563 for(i=0; i<nEq; i++){
116564 char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
116565 if( i>=nSkip ){
116566 explainAppendTerm(pStr, i, z, "=");
116567 }else{
116568 if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
116569 sqlite3XPrintf(pStr, 0, "ANY(%s)", z);
116573 j = i;
116574 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
116575 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
116576 explainAppendTerm(pStr, i++, z, ">");
116578 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
116579 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
116580 explainAppendTerm(pStr, i, z, "<");
116582 sqlite3StrAccumAppend(pStr, ")", 1);
116586 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
116587 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
116588 ** record is added to the output to describe the table scan strategy in
116589 ** pLevel.
116591 static void explainOneScan(
116592 Parse *pParse, /* Parse context */
116593 SrcList *pTabList, /* Table list this loop refers to */
116594 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
116595 int iLevel, /* Value for "level" column of output */
116596 int iFrom, /* Value for "from" column of output */
116597 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
116599 #ifndef SQLITE_DEBUG
116600 if( pParse->explain==2 )
116601 #endif
116603 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
116604 Vdbe *v = pParse->pVdbe; /* VM being constructed */
116605 sqlite3 *db = pParse->db; /* Database handle */
116606 int iId = pParse->iSelectId; /* Select id (left-most output column) */
116607 int isSearch; /* True for a SEARCH. False for SCAN. */
116608 WhereLoop *pLoop; /* The controlling WhereLoop object */
116609 u32 flags; /* Flags that describe this loop */
116610 char *zMsg; /* Text to add to EQP output */
116611 StrAccum str; /* EQP output string */
116612 char zBuf[100]; /* Initial space for EQP output string */
116614 pLoop = pLevel->pWLoop;
116615 flags = pLoop->wsFlags;
116616 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
116618 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
116619 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
116620 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
116622 sqlite3StrAccumInit(&str, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
116623 str.db = db;
116624 sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
116625 if( pItem->pSelect ){
116626 sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
116627 }else{
116628 sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
116631 if( pItem->zAlias ){
116632 sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
116634 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
116635 const char *zFmt = 0;
116636 Index *pIdx;
116638 assert( pLoop->u.btree.pIndex!=0 );
116639 pIdx = pLoop->u.btree.pIndex;
116640 assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
116641 if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
116642 if( isSearch ){
116643 zFmt = "PRIMARY KEY";
116645 }else if( flags & WHERE_AUTO_INDEX ){
116646 zFmt = "AUTOMATIC COVERING INDEX";
116647 }else if( flags & WHERE_IDX_ONLY ){
116648 zFmt = "COVERING INDEX %s";
116649 }else{
116650 zFmt = "INDEX %s";
116652 if( zFmt ){
116653 sqlite3StrAccumAppend(&str, " USING ", 7);
116654 sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
116655 explainIndexRange(&str, pLoop, pItem->pTab);
116657 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
116658 const char *zRange;
116659 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
116660 zRange = "(rowid=?)";
116661 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
116662 zRange = "(rowid>? AND rowid<?)";
116663 }else if( flags&WHERE_BTM_LIMIT ){
116664 zRange = "(rowid>?)";
116665 }else{
116666 assert( flags&WHERE_TOP_LIMIT);
116667 zRange = "(rowid<?)";
116669 sqlite3StrAccumAppendAll(&str, " USING INTEGER PRIMARY KEY ");
116670 sqlite3StrAccumAppendAll(&str, zRange);
116672 #ifndef SQLITE_OMIT_VIRTUALTABLE
116673 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
116674 sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
116675 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
116677 #endif
116678 #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
116679 if( pLoop->nOut>=10 ){
116680 sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
116681 }else{
116682 sqlite3StrAccumAppend(&str, " (~1 row)", 9);
116684 #endif
116685 zMsg = sqlite3StrAccumFinish(&str);
116686 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
116689 #else
116690 # define explainOneScan(u,v,w,x,y,z)
116691 #endif /* SQLITE_OMIT_EXPLAIN */
116695 ** Generate code for the start of the iLevel-th loop in the WHERE clause
116696 ** implementation described by pWInfo.
116698 static Bitmask codeOneLoopStart(
116699 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
116700 int iLevel, /* Which level of pWInfo->a[] should be coded */
116701 Bitmask notReady /* Which tables are currently available */
116703 int j, k; /* Loop counters */
116704 int iCur; /* The VDBE cursor for the table */
116705 int addrNxt; /* Where to jump to continue with the next IN case */
116706 int omitTable; /* True if we use the index only */
116707 int bRev; /* True if we need to scan in reverse order */
116708 WhereLevel *pLevel; /* The where level to be coded */
116709 WhereLoop *pLoop; /* The WhereLoop object being coded */
116710 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
116711 WhereTerm *pTerm; /* A WHERE clause term */
116712 Parse *pParse; /* Parsing context */
116713 sqlite3 *db; /* Database connection */
116714 Vdbe *v; /* The prepared stmt under constructions */
116715 struct SrcList_item *pTabItem; /* FROM clause term being coded */
116716 int addrBrk; /* Jump here to break out of the loop */
116717 int addrCont; /* Jump here to continue with next cycle */
116718 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
116719 int iReleaseReg = 0; /* Temp register to free before returning */
116721 pParse = pWInfo->pParse;
116722 v = pParse->pVdbe;
116723 pWC = &pWInfo->sWC;
116724 db = pParse->db;
116725 pLevel = &pWInfo->a[iLevel];
116726 pLoop = pLevel->pWLoop;
116727 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
116728 iCur = pTabItem->iCursor;
116729 pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
116730 bRev = (pWInfo->revMask>>iLevel)&1;
116731 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
116732 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
116733 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
116735 /* Create labels for the "break" and "continue" instructions
116736 ** for the current loop. Jump to addrBrk to break out of a loop.
116737 ** Jump to cont to go immediately to the next iteration of the
116738 ** loop.
116740 ** When there is an IN operator, we also have a "addrNxt" label that
116741 ** means to continue with the next IN value combination. When
116742 ** there are no IN operators in the constraints, the "addrNxt" label
116743 ** is the same as "addrBrk".
116745 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
116746 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
116748 /* If this is the right table of a LEFT OUTER JOIN, allocate and
116749 ** initialize a memory cell that records if this table matches any
116750 ** row of the left table of the join.
116752 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
116753 pLevel->iLeftJoin = ++pParse->nMem;
116754 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
116755 VdbeComment((v, "init LEFT JOIN no-match flag"));
116758 /* Special case of a FROM clause subquery implemented as a co-routine */
116759 if( pTabItem->viaCoroutine ){
116760 int regYield = pTabItem->regReturn;
116761 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
116762 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
116763 VdbeCoverage(v);
116764 VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
116765 pLevel->op = OP_Goto;
116766 }else
116768 #ifndef SQLITE_OMIT_VIRTUALTABLE
116769 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
116770 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
116771 ** to access the data.
116773 int iReg; /* P3 Value for OP_VFilter */
116774 int addrNotFound;
116775 int nConstraint = pLoop->nLTerm;
116777 sqlite3ExprCachePush(pParse);
116778 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
116779 addrNotFound = pLevel->addrBrk;
116780 for(j=0; j<nConstraint; j++){
116781 int iTarget = iReg+j+2;
116782 pTerm = pLoop->aLTerm[j];
116783 if( pTerm==0 ) continue;
116784 if( pTerm->eOperator & WO_IN ){
116785 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
116786 addrNotFound = pLevel->addrNxt;
116787 }else{
116788 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
116791 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
116792 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
116793 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
116794 pLoop->u.vtab.idxStr,
116795 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
116796 VdbeCoverage(v);
116797 pLoop->u.vtab.needFree = 0;
116798 for(j=0; j<nConstraint && j<16; j++){
116799 if( (pLoop->u.vtab.omitMask>>j)&1 ){
116800 disableTerm(pLevel, pLoop->aLTerm[j]);
116803 pLevel->op = OP_VNext;
116804 pLevel->p1 = iCur;
116805 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
116806 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
116807 sqlite3ExprCachePop(pParse);
116808 }else
116809 #endif /* SQLITE_OMIT_VIRTUALTABLE */
116811 if( (pLoop->wsFlags & WHERE_IPK)!=0
116812 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
116814 /* Case 2: We can directly reference a single row using an
116815 ** equality comparison against the ROWID field. Or
116816 ** we reference multiple rows using a "rowid IN (...)"
116817 ** construct.
116819 assert( pLoop->u.btree.nEq==1 );
116820 pTerm = pLoop->aLTerm[0];
116821 assert( pTerm!=0 );
116822 assert( pTerm->pExpr!=0 );
116823 assert( omitTable==0 );
116824 testcase( pTerm->wtFlags & TERM_VIRTUAL );
116825 iReleaseReg = ++pParse->nMem;
116826 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
116827 if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
116828 addrNxt = pLevel->addrNxt;
116829 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
116830 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
116831 VdbeCoverage(v);
116832 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
116833 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
116834 VdbeComment((v, "pk"));
116835 pLevel->op = OP_Noop;
116836 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
116837 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
116839 /* Case 3: We have an inequality comparison against the ROWID field.
116841 int testOp = OP_Noop;
116842 int start;
116843 int memEndValue = 0;
116844 WhereTerm *pStart, *pEnd;
116846 assert( omitTable==0 );
116847 j = 0;
116848 pStart = pEnd = 0;
116849 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
116850 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
116851 assert( pStart!=0 || pEnd!=0 );
116852 if( bRev ){
116853 pTerm = pStart;
116854 pStart = pEnd;
116855 pEnd = pTerm;
116857 if( pStart ){
116858 Expr *pX; /* The expression that defines the start bound */
116859 int r1, rTemp; /* Registers for holding the start boundary */
116861 /* The following constant maps TK_xx codes into corresponding
116862 ** seek opcodes. It depends on a particular ordering of TK_xx
116864 const u8 aMoveOp[] = {
116865 /* TK_GT */ OP_SeekGT,
116866 /* TK_LE */ OP_SeekLE,
116867 /* TK_LT */ OP_SeekLT,
116868 /* TK_GE */ OP_SeekGE
116870 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
116871 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
116872 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
116874 assert( (pStart->wtFlags & TERM_VNULL)==0 );
116875 testcase( pStart->wtFlags & TERM_VIRTUAL );
116876 pX = pStart->pExpr;
116877 assert( pX!=0 );
116878 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
116879 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
116880 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
116881 VdbeComment((v, "pk"));
116882 VdbeCoverageIf(v, pX->op==TK_GT);
116883 VdbeCoverageIf(v, pX->op==TK_LE);
116884 VdbeCoverageIf(v, pX->op==TK_LT);
116885 VdbeCoverageIf(v, pX->op==TK_GE);
116886 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
116887 sqlite3ReleaseTempReg(pParse, rTemp);
116888 disableTerm(pLevel, pStart);
116889 }else{
116890 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
116891 VdbeCoverageIf(v, bRev==0);
116892 VdbeCoverageIf(v, bRev!=0);
116894 if( pEnd ){
116895 Expr *pX;
116896 pX = pEnd->pExpr;
116897 assert( pX!=0 );
116898 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
116899 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
116900 testcase( pEnd->wtFlags & TERM_VIRTUAL );
116901 memEndValue = ++pParse->nMem;
116902 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
116903 if( pX->op==TK_LT || pX->op==TK_GT ){
116904 testOp = bRev ? OP_Le : OP_Ge;
116905 }else{
116906 testOp = bRev ? OP_Lt : OP_Gt;
116908 disableTerm(pLevel, pEnd);
116910 start = sqlite3VdbeCurrentAddr(v);
116911 pLevel->op = bRev ? OP_Prev : OP_Next;
116912 pLevel->p1 = iCur;
116913 pLevel->p2 = start;
116914 assert( pLevel->p5==0 );
116915 if( testOp!=OP_Noop ){
116916 iRowidReg = ++pParse->nMem;
116917 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
116918 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
116919 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
116920 VdbeCoverageIf(v, testOp==OP_Le);
116921 VdbeCoverageIf(v, testOp==OP_Lt);
116922 VdbeCoverageIf(v, testOp==OP_Ge);
116923 VdbeCoverageIf(v, testOp==OP_Gt);
116924 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
116926 }else if( pLoop->wsFlags & WHERE_INDEXED ){
116927 /* Case 4: A scan using an index.
116929 ** The WHERE clause may contain zero or more equality
116930 ** terms ("==" or "IN" operators) that refer to the N
116931 ** left-most columns of the index. It may also contain
116932 ** inequality constraints (>, <, >= or <=) on the indexed
116933 ** column that immediately follows the N equalities. Only
116934 ** the right-most column can be an inequality - the rest must
116935 ** use the "==" and "IN" operators. For example, if the
116936 ** index is on (x,y,z), then the following clauses are all
116937 ** optimized:
116939 ** x=5
116940 ** x=5 AND y=10
116941 ** x=5 AND y<10
116942 ** x=5 AND y>5 AND y<10
116943 ** x=5 AND y=5 AND z<=10
116945 ** The z<10 term of the following cannot be used, only
116946 ** the x=5 term:
116948 ** x=5 AND z<10
116950 ** N may be zero if there are inequality constraints.
116951 ** If there are no inequality constraints, then N is at
116952 ** least one.
116954 ** This case is also used when there are no WHERE clause
116955 ** constraints but an index is selected anyway, in order
116956 ** to force the output order to conform to an ORDER BY.
116958 static const u8 aStartOp[] = {
116961 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
116962 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
116963 OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
116964 OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
116965 OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
116966 OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
116968 static const u8 aEndOp[] = {
116969 OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
116970 OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
116971 OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
116972 OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
116974 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
116975 int regBase; /* Base register holding constraint values */
116976 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
116977 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
116978 int startEq; /* True if range start uses ==, >= or <= */
116979 int endEq; /* True if range end uses ==, >= or <= */
116980 int start_constraints; /* Start of range is constrained */
116981 int nConstraint; /* Number of constraint terms */
116982 Index *pIdx; /* The index we will be using */
116983 int iIdxCur; /* The VDBE cursor for the index */
116984 int nExtraReg = 0; /* Number of extra registers needed */
116985 int op; /* Instruction opcode */
116986 char *zStartAff; /* Affinity for start of range constraint */
116987 char cEndAff = 0; /* Affinity for end of range constraint */
116988 u8 bSeekPastNull = 0; /* True to seek past initial nulls */
116989 u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
116991 pIdx = pLoop->u.btree.pIndex;
116992 iIdxCur = pLevel->iIdxCur;
116993 assert( nEq>=pLoop->u.btree.nSkip );
116995 /* If this loop satisfies a sort order (pOrderBy) request that
116996 ** was passed to this function to implement a "SELECT min(x) ..."
116997 ** query, then the caller will only allow the loop to run for
116998 ** a single iteration. This means that the first row returned
116999 ** should not have a NULL value stored in 'x'. If column 'x' is
117000 ** the first one after the nEq equality constraints in the index,
117001 ** this requires some special handling.
117003 assert( pWInfo->pOrderBy==0
117004 || pWInfo->pOrderBy->nExpr==1
117005 || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
117006 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
117007 && pWInfo->nOBSat>0
117008 && (pIdx->nKeyCol>nEq)
117010 assert( pLoop->u.btree.nSkip==0 );
117011 bSeekPastNull = 1;
117012 nExtraReg = 1;
117015 /* Find any inequality constraint terms for the start and end
117016 ** of the range.
117018 j = nEq;
117019 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
117020 pRangeStart = pLoop->aLTerm[j++];
117021 nExtraReg = 1;
117023 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
117024 pRangeEnd = pLoop->aLTerm[j++];
117025 nExtraReg = 1;
117026 if( pRangeStart==0
117027 && (j = pIdx->aiColumn[nEq])>=0
117028 && pIdx->pTable->aCol[j].notNull==0
117030 bSeekPastNull = 1;
117033 assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
117035 /* Generate code to evaluate all constraint terms using == or IN
117036 ** and store the values of those terms in an array of registers
117037 ** starting at regBase.
117039 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
117040 assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
117041 if( zStartAff ) cEndAff = zStartAff[nEq];
117042 addrNxt = pLevel->addrNxt;
117044 /* If we are doing a reverse order scan on an ascending index, or
117045 ** a forward order scan on a descending index, interchange the
117046 ** start and end terms (pRangeStart and pRangeEnd).
117048 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
117049 || (bRev && pIdx->nKeyCol==nEq)
117051 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
117052 SWAP(u8, bSeekPastNull, bStopAtNull);
117055 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
117056 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
117057 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
117058 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
117059 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
117060 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
117061 start_constraints = pRangeStart || nEq>0;
117063 /* Seek the index cursor to the start of the range. */
117064 nConstraint = nEq;
117065 if( pRangeStart ){
117066 Expr *pRight = pRangeStart->pExpr->pRight;
117067 sqlite3ExprCode(pParse, pRight, regBase+nEq);
117068 if( (pRangeStart->wtFlags & TERM_VNULL)==0
117069 && sqlite3ExprCanBeNull(pRight)
117071 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
117072 VdbeCoverage(v);
117074 if( zStartAff ){
117075 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
117076 /* Since the comparison is to be performed with no conversions
117077 ** applied to the operands, set the affinity to apply to pRight to
117078 ** SQLITE_AFF_NONE. */
117079 zStartAff[nEq] = SQLITE_AFF_NONE;
117081 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
117082 zStartAff[nEq] = SQLITE_AFF_NONE;
117085 nConstraint++;
117086 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
117087 }else if( bSeekPastNull ){
117088 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
117089 nConstraint++;
117090 startEq = 0;
117091 start_constraints = 1;
117093 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
117094 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
117095 assert( op!=0 );
117096 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
117097 VdbeCoverage(v);
117098 VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
117099 VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
117100 VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
117101 VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
117102 VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
117103 VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
117105 /* Load the value for the inequality constraint at the end of the
117106 ** range (if any).
117108 nConstraint = nEq;
117109 if( pRangeEnd ){
117110 Expr *pRight = pRangeEnd->pExpr->pRight;
117111 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
117112 sqlite3ExprCode(pParse, pRight, regBase+nEq);
117113 if( (pRangeEnd->wtFlags & TERM_VNULL)==0
117114 && sqlite3ExprCanBeNull(pRight)
117116 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
117117 VdbeCoverage(v);
117119 if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
117120 && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
117122 codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
117124 nConstraint++;
117125 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
117126 }else if( bStopAtNull ){
117127 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
117128 endEq = 0;
117129 nConstraint++;
117131 sqlite3DbFree(db, zStartAff);
117133 /* Top of the loop body */
117134 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
117136 /* Check if the index cursor is past the end of the range. */
117137 if( nConstraint ){
117138 op = aEndOp[bRev*2 + endEq];
117139 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
117140 testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
117141 testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
117142 testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
117143 testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
117146 /* Seek the table cursor, if required */
117147 disableTerm(pLevel, pRangeStart);
117148 disableTerm(pLevel, pRangeEnd);
117149 if( omitTable ){
117150 /* pIdx is a covering index. No need to access the main table. */
117151 }else if( HasRowid(pIdx->pTable) ){
117152 iRowidReg = ++pParse->nMem;
117153 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
117154 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
117155 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
117156 }else if( iCur!=iIdxCur ){
117157 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
117158 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
117159 for(j=0; j<pPk->nKeyCol; j++){
117160 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
117161 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
117163 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
117164 iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
117167 /* Record the instruction used to terminate the loop. Disable
117168 ** WHERE clause terms made redundant by the index range scan.
117170 if( pLoop->wsFlags & WHERE_ONEROW ){
117171 pLevel->op = OP_Noop;
117172 }else if( bRev ){
117173 pLevel->op = OP_Prev;
117174 }else{
117175 pLevel->op = OP_Next;
117177 pLevel->p1 = iIdxCur;
117178 pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
117179 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
117180 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
117181 }else{
117182 assert( pLevel->p5==0 );
117184 }else
117186 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
117187 if( pLoop->wsFlags & WHERE_MULTI_OR ){
117188 /* Case 5: Two or more separately indexed terms connected by OR
117190 ** Example:
117192 ** CREATE TABLE t1(a,b,c,d);
117193 ** CREATE INDEX i1 ON t1(a);
117194 ** CREATE INDEX i2 ON t1(b);
117195 ** CREATE INDEX i3 ON t1(c);
117197 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
117199 ** In the example, there are three indexed terms connected by OR.
117200 ** The top of the loop looks like this:
117202 ** Null 1 # Zero the rowset in reg 1
117204 ** Then, for each indexed term, the following. The arguments to
117205 ** RowSetTest are such that the rowid of the current row is inserted
117206 ** into the RowSet. If it is already present, control skips the
117207 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
117209 ** sqlite3WhereBegin(<term>)
117210 ** RowSetTest # Insert rowid into rowset
117211 ** Gosub 2 A
117212 ** sqlite3WhereEnd()
117214 ** Following the above, code to terminate the loop. Label A, the target
117215 ** of the Gosub above, jumps to the instruction right after the Goto.
117217 ** Null 1 # Zero the rowset in reg 1
117218 ** Goto B # The loop is finished.
117220 ** A: <loop body> # Return data, whatever.
117222 ** Return 2 # Jump back to the Gosub
117224 ** B: <after the loop>
117226 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
117227 ** use an ephemeral index instead of a RowSet to record the primary
117228 ** keys of the rows we have already seen.
117231 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
117232 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
117233 Index *pCov = 0; /* Potential covering index (or NULL) */
117234 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
117236 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
117237 int regRowset = 0; /* Register for RowSet object */
117238 int regRowid = 0; /* Register holding rowid */
117239 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
117240 int iRetInit; /* Address of regReturn init */
117241 int untestedTerms = 0; /* Some terms not completely tested */
117242 int ii; /* Loop counter */
117243 u16 wctrlFlags; /* Flags for sub-WHERE clause */
117244 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
117245 Table *pTab = pTabItem->pTab;
117247 pTerm = pLoop->aLTerm[0];
117248 assert( pTerm!=0 );
117249 assert( pTerm->eOperator & WO_OR );
117250 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
117251 pOrWc = &pTerm->u.pOrInfo->wc;
117252 pLevel->op = OP_Return;
117253 pLevel->p1 = regReturn;
117255 /* Set up a new SrcList in pOrTab containing the table being scanned
117256 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
117257 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
117259 if( pWInfo->nLevel>1 ){
117260 int nNotReady; /* The number of notReady tables */
117261 struct SrcList_item *origSrc; /* Original list of tables */
117262 nNotReady = pWInfo->nLevel - iLevel - 1;
117263 pOrTab = sqlite3StackAllocRaw(db,
117264 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
117265 if( pOrTab==0 ) return notReady;
117266 pOrTab->nAlloc = (u8)(nNotReady + 1);
117267 pOrTab->nSrc = pOrTab->nAlloc;
117268 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
117269 origSrc = pWInfo->pTabList->a;
117270 for(k=1; k<=nNotReady; k++){
117271 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
117273 }else{
117274 pOrTab = pWInfo->pTabList;
117277 /* Initialize the rowset register to contain NULL. An SQL NULL is
117278 ** equivalent to an empty rowset. Or, create an ephemeral index
117279 ** capable of holding primary keys in the case of a WITHOUT ROWID.
117281 ** Also initialize regReturn to contain the address of the instruction
117282 ** immediately following the OP_Return at the bottom of the loop. This
117283 ** is required in a few obscure LEFT JOIN cases where control jumps
117284 ** over the top of the loop into the body of it. In this case the
117285 ** correct response for the end-of-loop code (the OP_Return) is to
117286 ** fall through to the next instruction, just as an OP_Next does if
117287 ** called on an uninitialized cursor.
117289 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
117290 if( HasRowid(pTab) ){
117291 regRowset = ++pParse->nMem;
117292 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
117293 }else{
117294 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
117295 regRowset = pParse->nTab++;
117296 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
117297 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
117299 regRowid = ++pParse->nMem;
117301 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
117303 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
117304 ** Then for every term xN, evaluate as the subexpression: xN AND z
117305 ** That way, terms in y that are factored into the disjunction will
117306 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
117308 ** Actually, each subexpression is converted to "xN AND w" where w is
117309 ** the "interesting" terms of z - terms that did not originate in the
117310 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
117311 ** indices.
117313 ** This optimization also only applies if the (x1 OR x2 OR ...) term
117314 ** is not contained in the ON clause of a LEFT JOIN.
117315 ** See ticket http://www.sqlite.org/src/info/f2369304e4
117317 if( pWC->nTerm>1 ){
117318 int iTerm;
117319 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
117320 Expr *pExpr = pWC->a[iTerm].pExpr;
117321 if( &pWC->a[iTerm] == pTerm ) continue;
117322 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
117323 testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
117324 testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
117325 if( pWC->a[iTerm].wtFlags & (TERM_ORINFO|TERM_VIRTUAL) ) continue;
117326 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
117327 pExpr = sqlite3ExprDup(db, pExpr, 0);
117328 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
117330 if( pAndExpr ){
117331 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
117335 /* Run a separate WHERE clause for each term of the OR clause. After
117336 ** eliminating duplicates from other WHERE clauses, the action for each
117337 ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
117339 wctrlFlags = WHERE_OMIT_OPEN_CLOSE
117340 | WHERE_FORCE_TABLE
117341 | WHERE_ONETABLE_ONLY;
117342 for(ii=0; ii<pOrWc->nTerm; ii++){
117343 WhereTerm *pOrTerm = &pOrWc->a[ii];
117344 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
117345 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
117346 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
117347 int j1 = 0; /* Address of jump operation */
117348 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
117349 pAndExpr->pLeft = pOrExpr;
117350 pOrExpr = pAndExpr;
117352 /* Loop through table entries that match term pOrTerm. */
117353 WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
117354 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
117355 wctrlFlags, iCovCur);
117356 assert( pSubWInfo || pParse->nErr || db->mallocFailed );
117357 if( pSubWInfo ){
117358 WhereLoop *pSubLoop;
117359 explainOneScan(
117360 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
117362 /* This is the sub-WHERE clause body. First skip over
117363 ** duplicate rows from prior sub-WHERE clauses, and record the
117364 ** rowid (or PRIMARY KEY) for the current row so that the same
117365 ** row will be skipped in subsequent sub-WHERE clauses.
117367 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
117368 int r;
117369 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
117370 if( HasRowid(pTab) ){
117371 r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
117372 j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
117373 VdbeCoverage(v);
117374 }else{
117375 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
117376 int nPk = pPk->nKeyCol;
117377 int iPk;
117379 /* Read the PK into an array of temp registers. */
117380 r = sqlite3GetTempRange(pParse, nPk);
117381 for(iPk=0; iPk<nPk; iPk++){
117382 int iCol = pPk->aiColumn[iPk];
117383 sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0);
117386 /* Check if the temp table already contains this key. If so,
117387 ** the row has already been included in the result set and
117388 ** can be ignored (by jumping past the Gosub below). Otherwise,
117389 ** insert the key into the temp table and proceed with processing
117390 ** the row.
117392 ** Use some of the same optimizations as OP_RowSetTest: If iSet
117393 ** is zero, assume that the key cannot already be present in
117394 ** the temp table. And if iSet is -1, assume that there is no
117395 ** need to insert the key into the temp table, as it will never
117396 ** be tested for. */
117397 if( iSet ){
117398 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
117399 VdbeCoverage(v);
117401 if( iSet>=0 ){
117402 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
117403 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
117404 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
117407 /* Release the array of temp registers */
117408 sqlite3ReleaseTempRange(pParse, r, nPk);
117412 /* Invoke the main loop body as a subroutine */
117413 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
117415 /* Jump here (skipping the main loop body subroutine) if the
117416 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
117417 if( j1 ) sqlite3VdbeJumpHere(v, j1);
117419 /* The pSubWInfo->untestedTerms flag means that this OR term
117420 ** contained one or more AND term from a notReady table. The
117421 ** terms from the notReady table could not be tested and will
117422 ** need to be tested later.
117424 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
117426 /* If all of the OR-connected terms are optimized using the same
117427 ** index, and the index is opened using the same cursor number
117428 ** by each call to sqlite3WhereBegin() made by this loop, it may
117429 ** be possible to use that index as a covering index.
117431 ** If the call to sqlite3WhereBegin() above resulted in a scan that
117432 ** uses an index, and this is either the first OR-connected term
117433 ** processed or the index is the same as that used by all previous
117434 ** terms, set pCov to the candidate covering index. Otherwise, set
117435 ** pCov to NULL to indicate that no candidate covering index will
117436 ** be available.
117438 pSubLoop = pSubWInfo->a[0].pWLoop;
117439 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
117440 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
117441 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
117442 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
117444 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
117445 pCov = pSubLoop->u.btree.pIndex;
117446 wctrlFlags |= WHERE_REOPEN_IDX;
117447 }else{
117448 pCov = 0;
117451 /* Finish the loop through table entries that match term pOrTerm. */
117452 sqlite3WhereEnd(pSubWInfo);
117456 pLevel->u.pCovidx = pCov;
117457 if( pCov ) pLevel->iIdxCur = iCovCur;
117458 if( pAndExpr ){
117459 pAndExpr->pLeft = 0;
117460 sqlite3ExprDelete(db, pAndExpr);
117462 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
117463 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
117464 sqlite3VdbeResolveLabel(v, iLoopBody);
117466 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
117467 if( !untestedTerms ) disableTerm(pLevel, pTerm);
117468 }else
117469 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
117472 /* Case 6: There is no usable index. We must do a complete
117473 ** scan of the entire table.
117475 static const u8 aStep[] = { OP_Next, OP_Prev };
117476 static const u8 aStart[] = { OP_Rewind, OP_Last };
117477 assert( bRev==0 || bRev==1 );
117478 if( pTabItem->isRecursive ){
117479 /* Tables marked isRecursive have only a single row that is stored in
117480 ** a pseudo-cursor. No need to Rewind or Next such cursors. */
117481 pLevel->op = OP_Noop;
117482 }else{
117483 pLevel->op = aStep[bRev];
117484 pLevel->p1 = iCur;
117485 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
117486 VdbeCoverageIf(v, bRev==0);
117487 VdbeCoverageIf(v, bRev!=0);
117488 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
117492 /* Insert code to test every subexpression that can be completely
117493 ** computed using the current set of tables.
117495 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
117496 Expr *pE;
117497 testcase( pTerm->wtFlags & TERM_VIRTUAL );
117498 testcase( pTerm->wtFlags & TERM_CODED );
117499 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
117500 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
117501 testcase( pWInfo->untestedTerms==0
117502 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
117503 pWInfo->untestedTerms = 1;
117504 continue;
117506 pE = pTerm->pExpr;
117507 assert( pE!=0 );
117508 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
117509 continue;
117511 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
117512 pTerm->wtFlags |= TERM_CODED;
117515 /* Insert code to test for implied constraints based on transitivity
117516 ** of the "==" operator.
117518 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
117519 ** and we are coding the t1 loop and the t2 loop has not yet coded,
117520 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
117521 ** the implied "t1.a=123" constraint.
117523 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
117524 Expr *pE, *pEAlt;
117525 WhereTerm *pAlt;
117526 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
117527 if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
117528 if( pTerm->leftCursor!=iCur ) continue;
117529 if( pLevel->iLeftJoin ) continue;
117530 pE = pTerm->pExpr;
117531 assert( !ExprHasProperty(pE, EP_FromJoin) );
117532 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
117533 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
117534 if( pAlt==0 ) continue;
117535 if( pAlt->wtFlags & (TERM_CODED) ) continue;
117536 testcase( pAlt->eOperator & WO_EQ );
117537 testcase( pAlt->eOperator & WO_IN );
117538 VdbeModuleComment((v, "begin transitive constraint"));
117539 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
117540 if( pEAlt ){
117541 *pEAlt = *pAlt->pExpr;
117542 pEAlt->pLeft = pE->pLeft;
117543 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
117544 sqlite3StackFree(db, pEAlt);
117548 /* For a LEFT OUTER JOIN, generate code that will record the fact that
117549 ** at least one row of the right table has matched the left table.
117551 if( pLevel->iLeftJoin ){
117552 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
117553 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
117554 VdbeComment((v, "record LEFT JOIN hit"));
117555 sqlite3ExprCacheClear(pParse);
117556 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
117557 testcase( pTerm->wtFlags & TERM_VIRTUAL );
117558 testcase( pTerm->wtFlags & TERM_CODED );
117559 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
117560 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
117561 assert( pWInfo->untestedTerms );
117562 continue;
117564 assert( pTerm->pExpr );
117565 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
117566 pTerm->wtFlags |= TERM_CODED;
117570 return pLevel->notReady;
117573 #ifdef WHERETRACE_ENABLED
117575 ** Print the content of a WhereTerm object
117577 static void whereTermPrint(WhereTerm *pTerm, int iTerm){
117578 if( pTerm==0 ){
117579 sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
117580 }else{
117581 char zType[4];
117582 memcpy(zType, "...", 4);
117583 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
117584 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
117585 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
117586 sqlite3DebugPrintf("TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x\n",
117587 iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
117588 pTerm->eOperator);
117589 sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
117592 #endif
117594 #ifdef WHERETRACE_ENABLED
117596 ** Print a WhereLoop object for debugging purposes
117598 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
117599 WhereInfo *pWInfo = pWC->pWInfo;
117600 int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
117601 struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
117602 Table *pTab = pItem->pTab;
117603 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
117604 p->iTab, nb, p->maskSelf, nb, p->prereq);
117605 sqlite3DebugPrintf(" %12s",
117606 pItem->zAlias ? pItem->zAlias : pTab->zName);
117607 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
117608 const char *zName;
117609 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
117610 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
117611 int i = sqlite3Strlen30(zName) - 1;
117612 while( zName[i]!='_' ) i--;
117613 zName += i;
117615 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
117616 }else{
117617 sqlite3DebugPrintf("%20s","");
117619 }else{
117620 char *z;
117621 if( p->u.vtab.idxStr ){
117622 z = sqlite3_mprintf("(%d,\"%s\",%x)",
117623 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
117624 }else{
117625 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
117627 sqlite3DebugPrintf(" %-19s", z);
117628 sqlite3_free(z);
117630 if( p->wsFlags & WHERE_SKIPSCAN ){
117631 sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->u.btree.nSkip);
117632 }else{
117633 sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
117635 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
117636 if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
117637 int i;
117638 for(i=0; i<p->nLTerm; i++){
117639 whereTermPrint(p->aLTerm[i], i);
117643 #endif
117646 ** Convert bulk memory into a valid WhereLoop that can be passed
117647 ** to whereLoopClear harmlessly.
117649 static void whereLoopInit(WhereLoop *p){
117650 p->aLTerm = p->aLTermSpace;
117651 p->nLTerm = 0;
117652 p->nLSlot = ArraySize(p->aLTermSpace);
117653 p->wsFlags = 0;
117657 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
117659 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
117660 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
117661 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
117662 sqlite3_free(p->u.vtab.idxStr);
117663 p->u.vtab.needFree = 0;
117664 p->u.vtab.idxStr = 0;
117665 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
117666 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
117667 sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo);
117668 sqlite3DbFree(db, p->u.btree.pIndex);
117669 p->u.btree.pIndex = 0;
117675 ** Deallocate internal memory used by a WhereLoop object
117677 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
117678 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
117679 whereLoopClearUnion(db, p);
117680 whereLoopInit(p);
117684 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
117686 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
117687 WhereTerm **paNew;
117688 if( p->nLSlot>=n ) return SQLITE_OK;
117689 n = (n+7)&~7;
117690 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
117691 if( paNew==0 ) return SQLITE_NOMEM;
117692 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
117693 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
117694 p->aLTerm = paNew;
117695 p->nLSlot = n;
117696 return SQLITE_OK;
117700 ** Transfer content from the second pLoop into the first.
117702 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
117703 whereLoopClearUnion(db, pTo);
117704 if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
117705 memset(&pTo->u, 0, sizeof(pTo->u));
117706 return SQLITE_NOMEM;
117708 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
117709 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
117710 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
117711 pFrom->u.vtab.needFree = 0;
117712 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
117713 pFrom->u.btree.pIndex = 0;
117715 return SQLITE_OK;
117719 ** Delete a WhereLoop object
117721 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
117722 whereLoopClear(db, p);
117723 sqlite3DbFree(db, p);
117727 ** Free a WhereInfo structure
117729 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
117730 if( ALWAYS(pWInfo) ){
117731 whereClauseClear(&pWInfo->sWC);
117732 while( pWInfo->pLoops ){
117733 WhereLoop *p = pWInfo->pLoops;
117734 pWInfo->pLoops = p->pNextLoop;
117735 whereLoopDelete(db, p);
117737 sqlite3DbFree(db, pWInfo);
117742 ** Return TRUE if both of the following are true:
117744 ** (1) X has the same or lower cost that Y
117745 ** (2) X is a proper subset of Y
117747 ** By "proper subset" we mean that X uses fewer WHERE clause terms
117748 ** than Y and that every WHERE clause term used by X is also used
117749 ** by Y.
117751 ** If X is a proper subset of Y then Y is a better choice and ought
117752 ** to have a lower cost. This routine returns TRUE when that cost
117753 ** relationship is inverted and needs to be adjusted.
117755 static int whereLoopCheaperProperSubset(
117756 const WhereLoop *pX, /* First WhereLoop to compare */
117757 const WhereLoop *pY /* Compare against this WhereLoop */
117759 int i, j;
117760 if( pX->nLTerm >= pY->nLTerm ) return 0; /* X is not a subset of Y */
117761 if( pX->rRun >= pY->rRun ){
117762 if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
117763 if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
117765 for(i=pX->nLTerm-1; i>=0; i--){
117766 for(j=pY->nLTerm-1; j>=0; j--){
117767 if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
117769 if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
117771 return 1; /* All conditions meet */
117775 ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
117776 ** that:
117778 ** (1) pTemplate costs less than any other WhereLoops that are a proper
117779 ** subset of pTemplate
117781 ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
117782 ** is a proper subset.
117784 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
117785 ** WHERE clause terms than Y and that every WHERE clause term used by X is
117786 ** also used by Y.
117788 ** This adjustment is omitted for SKIPSCAN loops. In a SKIPSCAN loop, the
117789 ** WhereLoop.nLTerm field is not an accurate measure of the number of WHERE
117790 ** clause terms covered, since some of the first nLTerm entries in aLTerm[]
117791 ** will be NULL (because they are skipped). That makes it more difficult
117792 ** to compare the loops. We could add extra code to do the comparison, and
117793 ** perhaps we will someday. But SKIPSCAN is sufficiently uncommon, and this
117794 ** adjustment is sufficient minor, that it is very difficult to construct
117795 ** a test case where the extra code would improve the query plan. Better
117796 ** to avoid the added complexity and just omit cost adjustments to SKIPSCAN
117797 ** loops.
117799 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
117800 if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
117801 if( (pTemplate->wsFlags & WHERE_SKIPSCAN)!=0 ) return;
117802 for(; p; p=p->pNextLoop){
117803 if( p->iTab!=pTemplate->iTab ) continue;
117804 if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
117805 if( (p->wsFlags & WHERE_SKIPSCAN)!=0 ) continue;
117806 if( whereLoopCheaperProperSubset(p, pTemplate) ){
117807 /* Adjust pTemplate cost downward so that it is cheaper than its
117808 ** subset p */
117809 pTemplate->rRun = p->rRun;
117810 pTemplate->nOut = p->nOut - 1;
117811 }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
117812 /* Adjust pTemplate cost upward so that it is costlier than p since
117813 ** pTemplate is a proper subset of p */
117814 pTemplate->rRun = p->rRun;
117815 pTemplate->nOut = p->nOut + 1;
117821 ** Search the list of WhereLoops in *ppPrev looking for one that can be
117822 ** supplanted by pTemplate.
117824 ** Return NULL if the WhereLoop list contains an entry that can supplant
117825 ** pTemplate, in other words if pTemplate does not belong on the list.
117827 ** If pX is a WhereLoop that pTemplate can supplant, then return the
117828 ** link that points to pX.
117830 ** If pTemplate cannot supplant any existing element of the list but needs
117831 ** to be added to the list, then return a pointer to the tail of the list.
117833 static WhereLoop **whereLoopFindLesser(
117834 WhereLoop **ppPrev,
117835 const WhereLoop *pTemplate
117837 WhereLoop *p;
117838 for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
117839 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
117840 /* If either the iTab or iSortIdx values for two WhereLoop are different
117841 ** then those WhereLoops need to be considered separately. Neither is
117842 ** a candidate to replace the other. */
117843 continue;
117845 /* In the current implementation, the rSetup value is either zero
117846 ** or the cost of building an automatic index (NlogN) and the NlogN
117847 ** is the same for compatible WhereLoops. */
117848 assert( p->rSetup==0 || pTemplate->rSetup==0
117849 || p->rSetup==pTemplate->rSetup );
117851 /* whereLoopAddBtree() always generates and inserts the automatic index
117852 ** case first. Hence compatible candidate WhereLoops never have a larger
117853 ** rSetup. Call this SETUP-INVARIANT */
117854 assert( p->rSetup>=pTemplate->rSetup );
117856 /* Any loop using an appliation-defined index (or PRIMARY KEY or
117857 ** UNIQUE constraint) with one or more == constraints is better
117858 ** than an automatic index. */
117859 if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
117860 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
117861 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
117862 && (p->prereq & pTemplate->prereq)==pTemplate->prereq
117864 break;
117867 /* If existing WhereLoop p is better than pTemplate, pTemplate can be
117868 ** discarded. WhereLoop p is better if:
117869 ** (1) p has no more dependencies than pTemplate, and
117870 ** (2) p has an equal or lower cost than pTemplate
117872 if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
117873 && p->rSetup<=pTemplate->rSetup /* (2a) */
117874 && p->rRun<=pTemplate->rRun /* (2b) */
117875 && p->nOut<=pTemplate->nOut /* (2c) */
117877 return 0; /* Discard pTemplate */
117880 /* If pTemplate is always better than p, then cause p to be overwritten
117881 ** with pTemplate. pTemplate is better than p if:
117882 ** (1) pTemplate has no more dependences than p, and
117883 ** (2) pTemplate has an equal or lower cost than p.
117885 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
117886 && p->rRun>=pTemplate->rRun /* (2a) */
117887 && p->nOut>=pTemplate->nOut /* (2b) */
117889 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
117890 break; /* Cause p to be overwritten by pTemplate */
117893 return ppPrev;
117897 ** Insert or replace a WhereLoop entry using the template supplied.
117899 ** An existing WhereLoop entry might be overwritten if the new template
117900 ** is better and has fewer dependencies. Or the template will be ignored
117901 ** and no insert will occur if an existing WhereLoop is faster and has
117902 ** fewer dependencies than the template. Otherwise a new WhereLoop is
117903 ** added based on the template.
117905 ** If pBuilder->pOrSet is not NULL then we care about only the
117906 ** prerequisites and rRun and nOut costs of the N best loops. That
117907 ** information is gathered in the pBuilder->pOrSet object. This special
117908 ** processing mode is used only for OR clause processing.
117910 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
117911 ** still might overwrite similar loops with the new template if the
117912 ** new template is better. Loops may be overwritten if the following
117913 ** conditions are met:
117915 ** (1) They have the same iTab.
117916 ** (2) They have the same iSortIdx.
117917 ** (3) The template has same or fewer dependencies than the current loop
117918 ** (4) The template has the same or lower cost than the current loop
117920 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
117921 WhereLoop **ppPrev, *p;
117922 WhereInfo *pWInfo = pBuilder->pWInfo;
117923 sqlite3 *db = pWInfo->pParse->db;
117925 /* If pBuilder->pOrSet is defined, then only keep track of the costs
117926 ** and prereqs.
117928 if( pBuilder->pOrSet!=0 ){
117929 #if WHERETRACE_ENABLED
117930 u16 n = pBuilder->pOrSet->n;
117931 int x =
117932 #endif
117933 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
117934 pTemplate->nOut);
117935 #if WHERETRACE_ENABLED /* 0x8 */
117936 if( sqlite3WhereTrace & 0x8 ){
117937 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
117938 whereLoopPrint(pTemplate, pBuilder->pWC);
117940 #endif
117941 return SQLITE_OK;
117944 /* Look for an existing WhereLoop to replace with pTemplate
117946 whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
117947 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
117949 if( ppPrev==0 ){
117950 /* There already exists a WhereLoop on the list that is better
117951 ** than pTemplate, so just ignore pTemplate */
117952 #if WHERETRACE_ENABLED /* 0x8 */
117953 if( sqlite3WhereTrace & 0x8 ){
117954 sqlite3DebugPrintf(" skip: ");
117955 whereLoopPrint(pTemplate, pBuilder->pWC);
117957 #endif
117958 return SQLITE_OK;
117959 }else{
117960 p = *ppPrev;
117963 /* If we reach this point it means that either p[] should be overwritten
117964 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
117965 ** WhereLoop and insert it.
117967 #if WHERETRACE_ENABLED /* 0x8 */
117968 if( sqlite3WhereTrace & 0x8 ){
117969 if( p!=0 ){
117970 sqlite3DebugPrintf("replace: ");
117971 whereLoopPrint(p, pBuilder->pWC);
117973 sqlite3DebugPrintf(" add: ");
117974 whereLoopPrint(pTemplate, pBuilder->pWC);
117976 #endif
117977 if( p==0 ){
117978 /* Allocate a new WhereLoop to add to the end of the list */
117979 *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
117980 if( p==0 ) return SQLITE_NOMEM;
117981 whereLoopInit(p);
117982 p->pNextLoop = 0;
117983 }else{
117984 /* We will be overwriting WhereLoop p[]. But before we do, first
117985 ** go through the rest of the list and delete any other entries besides
117986 ** p[] that are also supplated by pTemplate */
117987 WhereLoop **ppTail = &p->pNextLoop;
117988 WhereLoop *pToDel;
117989 while( *ppTail ){
117990 ppTail = whereLoopFindLesser(ppTail, pTemplate);
117991 if( ppTail==0 ) break;
117992 pToDel = *ppTail;
117993 if( pToDel==0 ) break;
117994 *ppTail = pToDel->pNextLoop;
117995 #if WHERETRACE_ENABLED /* 0x8 */
117996 if( sqlite3WhereTrace & 0x8 ){
117997 sqlite3DebugPrintf(" delete: ");
117998 whereLoopPrint(pToDel, pBuilder->pWC);
118000 #endif
118001 whereLoopDelete(db, pToDel);
118004 whereLoopXfer(db, p, pTemplate);
118005 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
118006 Index *pIndex = p->u.btree.pIndex;
118007 if( pIndex && pIndex->tnum==0 ){
118008 p->u.btree.pIndex = 0;
118011 return SQLITE_OK;
118015 ** Adjust the WhereLoop.nOut value downward to account for terms of the
118016 ** WHERE clause that reference the loop but which are not used by an
118017 ** index.
118019 ** In the current implementation, the first extra WHERE clause term reduces
118020 ** the number of output rows by a factor of 10 and each additional term
118021 ** reduces the number of output rows by sqrt(2).
118023 static void whereLoopOutputAdjust(
118024 WhereClause *pWC, /* The WHERE clause */
118025 WhereLoop *pLoop, /* The loop to adjust downward */
118026 LogEst nRow /* Number of rows in the entire table */
118028 WhereTerm *pTerm, *pX;
118029 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
118030 int i, j;
118031 int nEq = 0; /* Number of = constraints not within likely()/unlikely() */
118033 for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
118034 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
118035 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
118036 if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
118037 for(j=pLoop->nLTerm-1; j>=0; j--){
118038 pX = pLoop->aLTerm[j];
118039 if( pX==0 ) continue;
118040 if( pX==pTerm ) break;
118041 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
118043 if( j<0 ){
118044 if( pTerm->truthProb<=0 ){
118045 pLoop->nOut += pTerm->truthProb;
118046 }else{
118047 pLoop->nOut--;
118048 if( pTerm->eOperator&WO_EQ ) nEq++;
118052 /* TUNING: If there is at least one equality constraint in the WHERE
118053 ** clause that does not have a likelihood() explicitly assigned to it
118054 ** then do not let the estimated number of output rows exceed half
118055 ** the number of rows in the table. */
118056 if( nEq && pLoop->nOut>nRow-10 ){
118057 pLoop->nOut = nRow - 10;
118062 ** Adjust the cost C by the costMult facter T. This only occurs if
118063 ** compiled with -DSQLITE_ENABLE_COSTMULT
118065 #ifdef SQLITE_ENABLE_COSTMULT
118066 # define ApplyCostMultiplier(C,T) C += T
118067 #else
118068 # define ApplyCostMultiplier(C,T)
118069 #endif
118072 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
118073 ** index pIndex. Try to match one more.
118075 ** When this function is called, pBuilder->pNew->nOut contains the
118076 ** number of rows expected to be visited by filtering using the nEq
118077 ** terms only. If it is modified, this value is restored before this
118078 ** function returns.
118080 ** If pProbe->tnum==0, that means pIndex is a fake index used for the
118081 ** INTEGER PRIMARY KEY.
118083 static int whereLoopAddBtreeIndex(
118084 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
118085 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
118086 Index *pProbe, /* An index on pSrc */
118087 LogEst nInMul /* log(Number of iterations due to IN) */
118089 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
118090 Parse *pParse = pWInfo->pParse; /* Parsing context */
118091 sqlite3 *db = pParse->db; /* Database connection malloc context */
118092 WhereLoop *pNew; /* Template WhereLoop under construction */
118093 WhereTerm *pTerm; /* A WhereTerm under consideration */
118094 int opMask; /* Valid operators for constraints */
118095 WhereScan scan; /* Iterator for WHERE terms */
118096 Bitmask saved_prereq; /* Original value of pNew->prereq */
118097 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
118098 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
118099 u16 saved_nSkip; /* Original value of pNew->u.btree.nSkip */
118100 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
118101 LogEst saved_nOut; /* Original value of pNew->nOut */
118102 int iCol; /* Index of the column in the table */
118103 int rc = SQLITE_OK; /* Return code */
118104 LogEst rSize; /* Number of rows in the table */
118105 LogEst rLogSize; /* Logarithm of table size */
118106 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
118108 pNew = pBuilder->pNew;
118109 if( db->mallocFailed ) return SQLITE_NOMEM;
118111 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
118112 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
118113 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
118114 opMask = WO_LT|WO_LE;
118115 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
118116 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
118117 }else{
118118 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
118120 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
118122 assert( pNew->u.btree.nEq<pProbe->nColumn );
118123 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
118125 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
118126 opMask, pProbe);
118127 saved_nEq = pNew->u.btree.nEq;
118128 saved_nSkip = pNew->u.btree.nSkip;
118129 saved_nLTerm = pNew->nLTerm;
118130 saved_wsFlags = pNew->wsFlags;
118131 saved_prereq = pNew->prereq;
118132 saved_nOut = pNew->nOut;
118133 pNew->rSetup = 0;
118134 rSize = pProbe->aiRowLogEst[0];
118135 rLogSize = estLog(rSize);
118137 /* Consider using a skip-scan if there are no WHERE clause constraints
118138 ** available for the left-most terms of the index, and if the average
118139 ** number of repeats in the left-most terms is at least 18.
118141 ** The magic number 18 is selected on the basis that scanning 17 rows
118142 ** is almost always quicker than an index seek (even though if the index
118143 ** contains fewer than 2^17 rows we assume otherwise in other parts of
118144 ** the code). And, even if it is not, it should not be too much slower.
118145 ** On the other hand, the extra seeks could end up being significantly
118146 ** more expensive. */
118147 assert( 42==sqlite3LogEst(18) );
118148 if( saved_nEq==saved_nSkip
118149 && saved_nEq+1<pProbe->nKeyCol
118150 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
118151 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
118153 LogEst nIter;
118154 pNew->u.btree.nEq++;
118155 pNew->u.btree.nSkip++;
118156 pNew->aLTerm[pNew->nLTerm++] = 0;
118157 pNew->wsFlags |= WHERE_SKIPSCAN;
118158 nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
118159 if( pTerm ){
118160 /* TUNING: When estimating skip-scan for a term that is also indexable,
118161 ** multiply the cost of the skip-scan by 2.0, to make it a little less
118162 ** desirable than the regular index lookup. */
118163 nIter += 10; assert( 10==sqlite3LogEst(2) );
118165 pNew->nOut -= nIter;
118166 /* TUNING: Because uncertainties in the estimates for skip-scan queries,
118167 ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
118168 nIter += 5;
118169 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
118170 pNew->nOut = saved_nOut;
118171 pNew->u.btree.nEq = saved_nEq;
118172 pNew->u.btree.nSkip = saved_nSkip;
118174 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
118175 u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
118176 LogEst rCostIdx;
118177 LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
118178 int nIn = 0;
118179 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118180 int nRecValid = pBuilder->nRecValid;
118181 #endif
118182 if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
118183 && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
118185 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
118187 if( pTerm->prereqRight & pNew->maskSelf ) continue;
118189 pNew->wsFlags = saved_wsFlags;
118190 pNew->u.btree.nEq = saved_nEq;
118191 pNew->nLTerm = saved_nLTerm;
118192 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
118193 pNew->aLTerm[pNew->nLTerm++] = pTerm;
118194 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
118196 assert( nInMul==0
118197 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
118198 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
118199 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
118202 if( eOp & WO_IN ){
118203 Expr *pExpr = pTerm->pExpr;
118204 pNew->wsFlags |= WHERE_COLUMN_IN;
118205 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
118206 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
118207 nIn = 46; assert( 46==sqlite3LogEst(25) );
118208 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
118209 /* "x IN (value, value, ...)" */
118210 nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
118212 assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
118213 ** changes "x IN (?)" into "x=?". */
118215 }else if( eOp & (WO_EQ) ){
118216 pNew->wsFlags |= WHERE_COLUMN_EQ;
118217 if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
118218 if( iCol>=0 && !IsUniqueIndex(pProbe) ){
118219 pNew->wsFlags |= WHERE_UNQ_WANTED;
118220 }else{
118221 pNew->wsFlags |= WHERE_ONEROW;
118224 }else if( eOp & WO_ISNULL ){
118225 pNew->wsFlags |= WHERE_COLUMN_NULL;
118226 }else if( eOp & (WO_GT|WO_GE) ){
118227 testcase( eOp & WO_GT );
118228 testcase( eOp & WO_GE );
118229 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
118230 pBtm = pTerm;
118231 pTop = 0;
118232 }else{
118233 assert( eOp & (WO_LT|WO_LE) );
118234 testcase( eOp & WO_LT );
118235 testcase( eOp & WO_LE );
118236 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
118237 pTop = pTerm;
118238 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
118239 pNew->aLTerm[pNew->nLTerm-2] : 0;
118242 /* At this point pNew->nOut is set to the number of rows expected to
118243 ** be visited by the index scan before considering term pTerm, or the
118244 ** values of nIn and nInMul. In other words, assuming that all
118245 ** "x IN(...)" terms are replaced with "x = ?". This block updates
118246 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
118247 assert( pNew->nOut==saved_nOut );
118248 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
118249 /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
118250 ** data, using some other estimate. */
118251 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
118252 }else{
118253 int nEq = ++pNew->u.btree.nEq;
118254 assert( eOp & (WO_ISNULL|WO_EQ|WO_IN) );
118256 assert( pNew->nOut==saved_nOut );
118257 if( pTerm->truthProb<=0 && iCol>=0 ){
118258 assert( (eOp & WO_IN) || nIn==0 );
118259 testcase( eOp & WO_IN );
118260 pNew->nOut += pTerm->truthProb;
118261 pNew->nOut -= nIn;
118262 }else{
118263 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118264 tRowcnt nOut = 0;
118265 if( nInMul==0
118266 && pProbe->nSample
118267 && pNew->u.btree.nEq<=pProbe->nSampleCol
118268 && OptimizationEnabled(db, SQLITE_Stat3)
118269 && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
118271 Expr *pExpr = pTerm->pExpr;
118272 if( (eOp & (WO_EQ|WO_ISNULL))!=0 ){
118273 testcase( eOp & WO_EQ );
118274 testcase( eOp & WO_ISNULL );
118275 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
118276 }else{
118277 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
118279 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
118280 if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
118281 if( nOut ){
118282 pNew->nOut = sqlite3LogEst(nOut);
118283 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
118284 pNew->nOut -= nIn;
118287 if( nOut==0 )
118288 #endif
118290 pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
118291 if( eOp & WO_ISNULL ){
118292 /* TUNING: If there is no likelihood() value, assume that a
118293 ** "col IS NULL" expression matches twice as many rows
118294 ** as (col=?). */
118295 pNew->nOut += 10;
118301 /* Set rCostIdx to the cost of visiting selected rows in index. Add
118302 ** it to pNew->rRun, which is currently set to the cost of the index
118303 ** seek only. Then, if this is a non-covering index, add the cost of
118304 ** visiting the rows in the main table. */
118305 rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
118306 pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
118307 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
118308 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
118310 ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
118312 nOutUnadjusted = pNew->nOut;
118313 pNew->rRun += nInMul + nIn;
118314 pNew->nOut += nInMul + nIn;
118315 whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
118316 rc = whereLoopInsert(pBuilder, pNew);
118318 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
118319 pNew->nOut = saved_nOut;
118320 }else{
118321 pNew->nOut = nOutUnadjusted;
118324 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
118325 && pNew->u.btree.nEq<pProbe->nColumn
118327 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
118329 pNew->nOut = saved_nOut;
118330 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118331 pBuilder->nRecValid = nRecValid;
118332 #endif
118334 pNew->prereq = saved_prereq;
118335 pNew->u.btree.nEq = saved_nEq;
118336 pNew->u.btree.nSkip = saved_nSkip;
118337 pNew->wsFlags = saved_wsFlags;
118338 pNew->nOut = saved_nOut;
118339 pNew->nLTerm = saved_nLTerm;
118340 return rc;
118344 ** Return True if it is possible that pIndex might be useful in
118345 ** implementing the ORDER BY clause in pBuilder.
118347 ** Return False if pBuilder does not contain an ORDER BY clause or
118348 ** if there is no way for pIndex to be useful in implementing that
118349 ** ORDER BY clause.
118351 static int indexMightHelpWithOrderBy(
118352 WhereLoopBuilder *pBuilder,
118353 Index *pIndex,
118354 int iCursor
118356 ExprList *pOB;
118357 int ii, jj;
118359 if( pIndex->bUnordered ) return 0;
118360 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
118361 for(ii=0; ii<pOB->nExpr; ii++){
118362 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
118363 if( pExpr->op!=TK_COLUMN ) return 0;
118364 if( pExpr->iTable==iCursor ){
118365 if( pExpr->iColumn<0 ) return 1;
118366 for(jj=0; jj<pIndex->nKeyCol; jj++){
118367 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
118371 return 0;
118375 ** Return a bitmask where 1s indicate that the corresponding column of
118376 ** the table is used by an index. Only the first 63 columns are considered.
118378 static Bitmask columnsInIndex(Index *pIdx){
118379 Bitmask m = 0;
118380 int j;
118381 for(j=pIdx->nColumn-1; j>=0; j--){
118382 int x = pIdx->aiColumn[j];
118383 if( x>=0 ){
118384 testcase( x==BMS-1 );
118385 testcase( x==BMS-2 );
118386 if( x<BMS-1 ) m |= MASKBIT(x);
118389 return m;
118392 /* Check to see if a partial index with pPartIndexWhere can be used
118393 ** in the current query. Return true if it can be and false if not.
118395 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
118396 int i;
118397 WhereTerm *pTerm;
118398 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
118399 if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
118401 return 0;
118405 ** Add all WhereLoop objects for a single table of the join where the table
118406 ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
118407 ** a b-tree table, not a virtual table.
118409 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
118410 ** are calculated as follows:
118412 ** For a full scan, assuming the table (or index) contains nRow rows:
118414 ** cost = nRow * 3.0 // full-table scan
118415 ** cost = nRow * K // scan of covering index
118416 ** cost = nRow * (K+3.0) // scan of non-covering index
118418 ** where K is a value between 1.1 and 3.0 set based on the relative
118419 ** estimated average size of the index and table records.
118421 ** For an index scan, where nVisit is the number of index rows visited
118422 ** by the scan, and nSeek is the number of seek operations required on
118423 ** the index b-tree:
118425 ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
118426 ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
118428 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
118429 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
118430 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
118432 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
118433 ** of uncertainty. For this reason, scoring is designed to pick plans that
118434 ** "do the least harm" if the estimates are inaccurate. For example, a
118435 ** log(nRow) factor is omitted from a non-covering index scan in order to
118436 ** bias the scoring in favor of using an index, since the worst-case
118437 ** performance of using an index is far better than the worst-case performance
118438 ** of a full table scan.
118440 static int whereLoopAddBtree(
118441 WhereLoopBuilder *pBuilder, /* WHERE clause information */
118442 Bitmask mExtra /* Extra prerequesites for using this table */
118444 WhereInfo *pWInfo; /* WHERE analysis context */
118445 Index *pProbe; /* An index we are evaluating */
118446 Index sPk; /* A fake index object for the primary key */
118447 LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
118448 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
118449 SrcList *pTabList; /* The FROM clause */
118450 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
118451 WhereLoop *pNew; /* Template WhereLoop object */
118452 int rc = SQLITE_OK; /* Return code */
118453 int iSortIdx = 1; /* Index number */
118454 int b; /* A boolean value */
118455 LogEst rSize; /* number of rows in the table */
118456 LogEst rLogSize; /* Logarithm of the number of rows in the table */
118457 WhereClause *pWC; /* The parsed WHERE clause */
118458 Table *pTab; /* Table being queried */
118460 pNew = pBuilder->pNew;
118461 pWInfo = pBuilder->pWInfo;
118462 pTabList = pWInfo->pTabList;
118463 pSrc = pTabList->a + pNew->iTab;
118464 pTab = pSrc->pTab;
118465 pWC = pBuilder->pWC;
118466 assert( !IsVirtual(pSrc->pTab) );
118468 if( pSrc->pIndex ){
118469 /* An INDEXED BY clause specifies a particular index to use */
118470 pProbe = pSrc->pIndex;
118471 }else if( !HasRowid(pTab) ){
118472 pProbe = pTab->pIndex;
118473 }else{
118474 /* There is no INDEXED BY clause. Create a fake Index object in local
118475 ** variable sPk to represent the rowid primary key index. Make this
118476 ** fake index the first in a chain of Index objects with all of the real
118477 ** indices to follow */
118478 Index *pFirst; /* First of real indices on the table */
118479 memset(&sPk, 0, sizeof(Index));
118480 sPk.nKeyCol = 1;
118481 sPk.nColumn = 1;
118482 sPk.aiColumn = &aiColumnPk;
118483 sPk.aiRowLogEst = aiRowEstPk;
118484 sPk.onError = OE_Replace;
118485 sPk.pTable = pTab;
118486 sPk.szIdxRow = pTab->szTabRow;
118487 aiRowEstPk[0] = pTab->nRowLogEst;
118488 aiRowEstPk[1] = 0;
118489 pFirst = pSrc->pTab->pIndex;
118490 if( pSrc->notIndexed==0 ){
118491 /* The real indices of the table are only considered if the
118492 ** NOT INDEXED qualifier is omitted from the FROM clause */
118493 sPk.pNext = pFirst;
118495 pProbe = &sPk;
118497 rSize = pTab->nRowLogEst;
118498 rLogSize = estLog(rSize);
118500 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
118501 /* Automatic indexes */
118502 if( !pBuilder->pOrSet
118503 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
118504 && pSrc->pIndex==0
118505 && !pSrc->viaCoroutine
118506 && !pSrc->notIndexed
118507 && HasRowid(pTab)
118508 && !pSrc->isCorrelated
118509 && !pSrc->isRecursive
118511 /* Generate auto-index WhereLoops */
118512 WhereTerm *pTerm;
118513 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
118514 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
118515 if( pTerm->prereqRight & pNew->maskSelf ) continue;
118516 if( termCanDriveIndex(pTerm, pSrc, 0) ){
118517 pNew->u.btree.nEq = 1;
118518 pNew->u.btree.nSkip = 0;
118519 pNew->u.btree.pIndex = 0;
118520 pNew->nLTerm = 1;
118521 pNew->aLTerm[0] = pTerm;
118522 /* TUNING: One-time cost for computing the automatic index is
118523 ** estimated to be X*N*log2(N) where N is the number of rows in
118524 ** the table being indexed and where X is 7 (LogEst=28) for normal
118525 ** tables or 1.375 (LogEst=4) for views and subqueries. The value
118526 ** of X is smaller for views and subqueries so that the query planner
118527 ** will be more aggressive about generating automatic indexes for
118528 ** those objects, since there is no opportunity to add schema
118529 ** indexes on subqueries and views. */
118530 pNew->rSetup = rLogSize + rSize + 4;
118531 if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
118532 pNew->rSetup += 24;
118534 ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
118535 /* TUNING: Each index lookup yields 20 rows in the table. This
118536 ** is more than the usual guess of 10 rows, since we have no way
118537 ** of knowing how selective the index will ultimately be. It would
118538 ** not be unreasonable to make this value much larger. */
118539 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
118540 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
118541 pNew->wsFlags = WHERE_AUTO_INDEX;
118542 pNew->prereq = mExtra | pTerm->prereqRight;
118543 rc = whereLoopInsert(pBuilder, pNew);
118547 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
118549 /* Loop over all indices
118551 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
118552 if( pProbe->pPartIdxWhere!=0
118553 && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
118554 testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
118555 continue; /* Partial index inappropriate for this query */
118557 rSize = pProbe->aiRowLogEst[0];
118558 pNew->u.btree.nEq = 0;
118559 pNew->u.btree.nSkip = 0;
118560 pNew->nLTerm = 0;
118561 pNew->iSortIdx = 0;
118562 pNew->rSetup = 0;
118563 pNew->prereq = mExtra;
118564 pNew->nOut = rSize;
118565 pNew->u.btree.pIndex = pProbe;
118566 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
118567 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
118568 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
118569 if( pProbe->tnum<=0 ){
118570 /* Integer primary key index */
118571 pNew->wsFlags = WHERE_IPK;
118573 /* Full table scan */
118574 pNew->iSortIdx = b ? iSortIdx : 0;
118575 /* TUNING: Cost of full table scan is (N*3.0). */
118576 pNew->rRun = rSize + 16;
118577 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
118578 whereLoopOutputAdjust(pWC, pNew, rSize);
118579 rc = whereLoopInsert(pBuilder, pNew);
118580 pNew->nOut = rSize;
118581 if( rc ) break;
118582 }else{
118583 Bitmask m;
118584 if( pProbe->isCovering ){
118585 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
118586 m = 0;
118587 }else{
118588 m = pSrc->colUsed & ~columnsInIndex(pProbe);
118589 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
118592 /* Full scan via index */
118593 if( b
118594 || !HasRowid(pTab)
118595 || ( m==0
118596 && pProbe->bUnordered==0
118597 && (pProbe->szIdxRow<pTab->szTabRow)
118598 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
118599 && sqlite3GlobalConfig.bUseCis
118600 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
118603 pNew->iSortIdx = b ? iSortIdx : 0;
118605 /* The cost of visiting the index rows is N*K, where K is
118606 ** between 1.1 and 3.0, depending on the relative sizes of the
118607 ** index and table rows. If this is a non-covering index scan,
118608 ** also add the cost of visiting table rows (N*3.0). */
118609 pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
118610 if( m!=0 ){
118611 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
118613 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
118614 whereLoopOutputAdjust(pWC, pNew, rSize);
118615 rc = whereLoopInsert(pBuilder, pNew);
118616 pNew->nOut = rSize;
118617 if( rc ) break;
118621 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
118622 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118623 sqlite3Stat4ProbeFree(pBuilder->pRec);
118624 pBuilder->nRecValid = 0;
118625 pBuilder->pRec = 0;
118626 #endif
118628 /* If there was an INDEXED BY clause, then only that one index is
118629 ** considered. */
118630 if( pSrc->pIndex ) break;
118632 return rc;
118635 #ifndef SQLITE_OMIT_VIRTUALTABLE
118637 ** Add all WhereLoop objects for a table of the join identified by
118638 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
118640 static int whereLoopAddVirtual(
118641 WhereLoopBuilder *pBuilder, /* WHERE clause information */
118642 Bitmask mExtra
118644 WhereInfo *pWInfo; /* WHERE analysis context */
118645 Parse *pParse; /* The parsing context */
118646 WhereClause *pWC; /* The WHERE clause */
118647 struct SrcList_item *pSrc; /* The FROM clause term to search */
118648 Table *pTab;
118649 sqlite3 *db;
118650 sqlite3_index_info *pIdxInfo;
118651 struct sqlite3_index_constraint *pIdxCons;
118652 struct sqlite3_index_constraint_usage *pUsage;
118653 WhereTerm *pTerm;
118654 int i, j;
118655 int iTerm, mxTerm;
118656 int nConstraint;
118657 int seenIn = 0; /* True if an IN operator is seen */
118658 int seenVar = 0; /* True if a non-constant constraint is seen */
118659 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
118660 WhereLoop *pNew;
118661 int rc = SQLITE_OK;
118663 pWInfo = pBuilder->pWInfo;
118664 pParse = pWInfo->pParse;
118665 db = pParse->db;
118666 pWC = pBuilder->pWC;
118667 pNew = pBuilder->pNew;
118668 pSrc = &pWInfo->pTabList->a[pNew->iTab];
118669 pTab = pSrc->pTab;
118670 assert( IsVirtual(pTab) );
118671 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
118672 if( pIdxInfo==0 ) return SQLITE_NOMEM;
118673 pNew->prereq = 0;
118674 pNew->rSetup = 0;
118675 pNew->wsFlags = WHERE_VIRTUALTABLE;
118676 pNew->nLTerm = 0;
118677 pNew->u.vtab.needFree = 0;
118678 pUsage = pIdxInfo->aConstraintUsage;
118679 nConstraint = pIdxInfo->nConstraint;
118680 if( whereLoopResize(db, pNew, nConstraint) ){
118681 sqlite3DbFree(db, pIdxInfo);
118682 return SQLITE_NOMEM;
118685 for(iPhase=0; iPhase<=3; iPhase++){
118686 if( !seenIn && (iPhase&1)!=0 ){
118687 iPhase++;
118688 if( iPhase>3 ) break;
118690 if( !seenVar && iPhase>1 ) break;
118691 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
118692 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
118693 j = pIdxCons->iTermOffset;
118694 pTerm = &pWC->a[j];
118695 switch( iPhase ){
118696 case 0: /* Constants without IN operator */
118697 pIdxCons->usable = 0;
118698 if( (pTerm->eOperator & WO_IN)!=0 ){
118699 seenIn = 1;
118701 if( pTerm->prereqRight!=0 ){
118702 seenVar = 1;
118703 }else if( (pTerm->eOperator & WO_IN)==0 ){
118704 pIdxCons->usable = 1;
118706 break;
118707 case 1: /* Constants with IN operators */
118708 assert( seenIn );
118709 pIdxCons->usable = (pTerm->prereqRight==0);
118710 break;
118711 case 2: /* Variables without IN */
118712 assert( seenVar );
118713 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
118714 break;
118715 default: /* Variables with IN */
118716 assert( seenVar && seenIn );
118717 pIdxCons->usable = 1;
118718 break;
118721 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
118722 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
118723 pIdxInfo->idxStr = 0;
118724 pIdxInfo->idxNum = 0;
118725 pIdxInfo->needToFreeIdxStr = 0;
118726 pIdxInfo->orderByConsumed = 0;
118727 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
118728 pIdxInfo->estimatedRows = 25;
118729 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
118730 if( rc ) goto whereLoopAddVtab_exit;
118731 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
118732 pNew->prereq = mExtra;
118733 mxTerm = -1;
118734 assert( pNew->nLSlot>=nConstraint );
118735 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
118736 pNew->u.vtab.omitMask = 0;
118737 for(i=0; i<nConstraint; i++, pIdxCons++){
118738 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
118739 j = pIdxCons->iTermOffset;
118740 if( iTerm>=nConstraint
118741 || j<0
118742 || j>=pWC->nTerm
118743 || pNew->aLTerm[iTerm]!=0
118745 rc = SQLITE_ERROR;
118746 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
118747 goto whereLoopAddVtab_exit;
118749 testcase( iTerm==nConstraint-1 );
118750 testcase( j==0 );
118751 testcase( j==pWC->nTerm-1 );
118752 pTerm = &pWC->a[j];
118753 pNew->prereq |= pTerm->prereqRight;
118754 assert( iTerm<pNew->nLSlot );
118755 pNew->aLTerm[iTerm] = pTerm;
118756 if( iTerm>mxTerm ) mxTerm = iTerm;
118757 testcase( iTerm==15 );
118758 testcase( iTerm==16 );
118759 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
118760 if( (pTerm->eOperator & WO_IN)!=0 ){
118761 if( pUsage[i].omit==0 ){
118762 /* Do not attempt to use an IN constraint if the virtual table
118763 ** says that the equivalent EQ constraint cannot be safely omitted.
118764 ** If we do attempt to use such a constraint, some rows might be
118765 ** repeated in the output. */
118766 break;
118768 /* A virtual table that is constrained by an IN clause may not
118769 ** consume the ORDER BY clause because (1) the order of IN terms
118770 ** is not necessarily related to the order of output terms and
118771 ** (2) Multiple outputs from a single IN value will not merge
118772 ** together. */
118773 pIdxInfo->orderByConsumed = 0;
118777 if( i>=nConstraint ){
118778 pNew->nLTerm = mxTerm+1;
118779 assert( pNew->nLTerm<=pNew->nLSlot );
118780 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
118781 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
118782 pIdxInfo->needToFreeIdxStr = 0;
118783 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
118784 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
118785 pIdxInfo->nOrderBy : 0);
118786 pNew->rSetup = 0;
118787 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
118788 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
118789 whereLoopInsert(pBuilder, pNew);
118790 if( pNew->u.vtab.needFree ){
118791 sqlite3_free(pNew->u.vtab.idxStr);
118792 pNew->u.vtab.needFree = 0;
118797 whereLoopAddVtab_exit:
118798 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
118799 sqlite3DbFree(db, pIdxInfo);
118800 return rc;
118802 #endif /* SQLITE_OMIT_VIRTUALTABLE */
118805 ** Add WhereLoop entries to handle OR terms. This works for either
118806 ** btrees or virtual tables.
118808 static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
118809 WhereInfo *pWInfo = pBuilder->pWInfo;
118810 WhereClause *pWC;
118811 WhereLoop *pNew;
118812 WhereTerm *pTerm, *pWCEnd;
118813 int rc = SQLITE_OK;
118814 int iCur;
118815 WhereClause tempWC;
118816 WhereLoopBuilder sSubBuild;
118817 WhereOrSet sSum, sCur;
118818 struct SrcList_item *pItem;
118820 pWC = pBuilder->pWC;
118821 pWCEnd = pWC->a + pWC->nTerm;
118822 pNew = pBuilder->pNew;
118823 memset(&sSum, 0, sizeof(sSum));
118824 pItem = pWInfo->pTabList->a + pNew->iTab;
118825 iCur = pItem->iCursor;
118827 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
118828 if( (pTerm->eOperator & WO_OR)!=0
118829 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
118831 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
118832 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
118833 WhereTerm *pOrTerm;
118834 int once = 1;
118835 int i, j;
118837 sSubBuild = *pBuilder;
118838 sSubBuild.pOrderBy = 0;
118839 sSubBuild.pOrSet = &sCur;
118841 WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
118842 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
118843 if( (pOrTerm->eOperator & WO_AND)!=0 ){
118844 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
118845 }else if( pOrTerm->leftCursor==iCur ){
118846 tempWC.pWInfo = pWC->pWInfo;
118847 tempWC.pOuter = pWC;
118848 tempWC.op = TK_AND;
118849 tempWC.nTerm = 1;
118850 tempWC.a = pOrTerm;
118851 sSubBuild.pWC = &tempWC;
118852 }else{
118853 continue;
118855 sCur.n = 0;
118856 #ifdef WHERETRACE_ENABLED
118857 WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
118858 (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
118859 if( sqlite3WhereTrace & 0x400 ){
118860 for(i=0; i<sSubBuild.pWC->nTerm; i++){
118861 whereTermPrint(&sSubBuild.pWC->a[i], i);
118864 #endif
118865 #ifndef SQLITE_OMIT_VIRTUALTABLE
118866 if( IsVirtual(pItem->pTab) ){
118867 rc = whereLoopAddVirtual(&sSubBuild, mExtra);
118868 }else
118869 #endif
118871 rc = whereLoopAddBtree(&sSubBuild, mExtra);
118873 if( rc==SQLITE_OK ){
118874 rc = whereLoopAddOr(&sSubBuild, mExtra);
118876 assert( rc==SQLITE_OK || sCur.n==0 );
118877 if( sCur.n==0 ){
118878 sSum.n = 0;
118879 break;
118880 }else if( once ){
118881 whereOrMove(&sSum, &sCur);
118882 once = 0;
118883 }else{
118884 WhereOrSet sPrev;
118885 whereOrMove(&sPrev, &sSum);
118886 sSum.n = 0;
118887 for(i=0; i<sPrev.n; i++){
118888 for(j=0; j<sCur.n; j++){
118889 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
118890 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
118891 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
118896 pNew->nLTerm = 1;
118897 pNew->aLTerm[0] = pTerm;
118898 pNew->wsFlags = WHERE_MULTI_OR;
118899 pNew->rSetup = 0;
118900 pNew->iSortIdx = 0;
118901 memset(&pNew->u, 0, sizeof(pNew->u));
118902 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
118903 /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
118904 ** of all sub-scans required by the OR-scan. However, due to rounding
118905 ** errors, it may be that the cost of the OR-scan is equal to its
118906 ** most expensive sub-scan. Add the smallest possible penalty
118907 ** (equivalent to multiplying the cost by 1.07) to ensure that
118908 ** this does not happen. Otherwise, for WHERE clauses such as the
118909 ** following where there is an index on "y":
118911 ** WHERE likelihood(x=?, 0.99) OR y=?
118913 ** the planner may elect to "OR" together a full-table scan and an
118914 ** index lookup. And other similarly odd results. */
118915 pNew->rRun = sSum.a[i].rRun + 1;
118916 pNew->nOut = sSum.a[i].nOut;
118917 pNew->prereq = sSum.a[i].prereq;
118918 rc = whereLoopInsert(pBuilder, pNew);
118920 WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
118923 return rc;
118927 ** Add all WhereLoop objects for all tables
118929 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
118930 WhereInfo *pWInfo = pBuilder->pWInfo;
118931 Bitmask mExtra = 0;
118932 Bitmask mPrior = 0;
118933 int iTab;
118934 SrcList *pTabList = pWInfo->pTabList;
118935 struct SrcList_item *pItem;
118936 sqlite3 *db = pWInfo->pParse->db;
118937 int nTabList = pWInfo->nLevel;
118938 int rc = SQLITE_OK;
118939 u8 priorJoinType = 0;
118940 WhereLoop *pNew;
118942 /* Loop over the tables in the join, from left to right */
118943 pNew = pBuilder->pNew;
118944 whereLoopInit(pNew);
118945 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
118946 pNew->iTab = iTab;
118947 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
118948 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
118949 mExtra = mPrior;
118951 priorJoinType = pItem->jointype;
118952 if( IsVirtual(pItem->pTab) ){
118953 rc = whereLoopAddVirtual(pBuilder, mExtra);
118954 }else{
118955 rc = whereLoopAddBtree(pBuilder, mExtra);
118957 if( rc==SQLITE_OK ){
118958 rc = whereLoopAddOr(pBuilder, mExtra);
118960 mPrior |= pNew->maskSelf;
118961 if( rc || db->mallocFailed ) break;
118963 whereLoopClear(db, pNew);
118964 return rc;
118968 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
118969 ** parameters) to see if it outputs rows in the requested ORDER BY
118970 ** (or GROUP BY) without requiring a separate sort operation. Return N:
118972 ** N>0: N terms of the ORDER BY clause are satisfied
118973 ** N==0: No terms of the ORDER BY clause are satisfied
118974 ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
118976 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
118977 ** strict. With GROUP BY and DISTINCT the only requirement is that
118978 ** equivalent rows appear immediately adjacent to one another. GROUP BY
118979 ** and DISTINCT do not require rows to appear in any particular order as long
118980 ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
118981 ** the pOrderBy terms can be matched in any order. With ORDER BY, the
118982 ** pOrderBy terms must be matched in strict left-to-right order.
118984 static i8 wherePathSatisfiesOrderBy(
118985 WhereInfo *pWInfo, /* The WHERE clause */
118986 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
118987 WherePath *pPath, /* The WherePath to check */
118988 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
118989 u16 nLoop, /* Number of entries in pPath->aLoop[] */
118990 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
118991 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
118993 u8 revSet; /* True if rev is known */
118994 u8 rev; /* Composite sort order */
118995 u8 revIdx; /* Index sort order */
118996 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
118997 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
118998 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
118999 u16 nKeyCol; /* Number of key columns in pIndex */
119000 u16 nColumn; /* Total number of ordered columns in the index */
119001 u16 nOrderBy; /* Number terms in the ORDER BY clause */
119002 int iLoop; /* Index of WhereLoop in pPath being processed */
119003 int i, j; /* Loop counters */
119004 int iCur; /* Cursor number for current WhereLoop */
119005 int iColumn; /* A column number within table iCur */
119006 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
119007 WhereTerm *pTerm; /* A single term of the WHERE clause */
119008 Expr *pOBExpr; /* An expression from the ORDER BY clause */
119009 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
119010 Index *pIndex; /* The index associated with pLoop */
119011 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
119012 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
119013 Bitmask obDone; /* Mask of all ORDER BY terms */
119014 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
119015 Bitmask ready; /* Mask of inner loops */
119018 ** We say the WhereLoop is "one-row" if it generates no more than one
119019 ** row of output. A WhereLoop is one-row if all of the following are true:
119020 ** (a) All index columns match with WHERE_COLUMN_EQ.
119021 ** (b) The index is unique
119022 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
119023 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
119025 ** We say the WhereLoop is "order-distinct" if the set of columns from
119026 ** that WhereLoop that are in the ORDER BY clause are different for every
119027 ** row of the WhereLoop. Every one-row WhereLoop is automatically
119028 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
119029 ** is not order-distinct. To be order-distinct is not quite the same as being
119030 ** UNIQUE since a UNIQUE column or index can have multiple rows that
119031 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
119032 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
119034 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
119035 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
119036 ** automatically order-distinct.
119039 assert( pOrderBy!=0 );
119040 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
119042 nOrderBy = pOrderBy->nExpr;
119043 testcase( nOrderBy==BMS-1 );
119044 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
119045 isOrderDistinct = 1;
119046 obDone = MASKBIT(nOrderBy)-1;
119047 orderDistinctMask = 0;
119048 ready = 0;
119049 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
119050 if( iLoop>0 ) ready |= pLoop->maskSelf;
119051 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
119052 if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
119053 if( pLoop->u.vtab.isOrdered ) obSat = obDone;
119054 break;
119056 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
119058 /* Mark off any ORDER BY term X that is a column in the table of
119059 ** the current loop for which there is term in the WHERE
119060 ** clause of the form X IS NULL or X=? that reference only outer
119061 ** loops.
119063 for(i=0; i<nOrderBy; i++){
119064 if( MASKBIT(i) & obSat ) continue;
119065 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
119066 if( pOBExpr->op!=TK_COLUMN ) continue;
119067 if( pOBExpr->iTable!=iCur ) continue;
119068 pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
119069 ~ready, WO_EQ|WO_ISNULL, 0);
119070 if( pTerm==0 ) continue;
119071 if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
119072 const char *z1, *z2;
119073 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
119074 if( !pColl ) pColl = db->pDfltColl;
119075 z1 = pColl->zName;
119076 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
119077 if( !pColl ) pColl = db->pDfltColl;
119078 z2 = pColl->zName;
119079 if( sqlite3StrICmp(z1, z2)!=0 ) continue;
119081 obSat |= MASKBIT(i);
119084 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
119085 if( pLoop->wsFlags & WHERE_IPK ){
119086 pIndex = 0;
119087 nKeyCol = 0;
119088 nColumn = 1;
119089 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
119090 return 0;
119091 }else{
119092 nKeyCol = pIndex->nKeyCol;
119093 nColumn = pIndex->nColumn;
119094 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
119095 assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
119096 isOrderDistinct = IsUniqueIndex(pIndex);
119099 /* Loop through all columns of the index and deal with the ones
119100 ** that are not constrained by == or IN.
119102 rev = revSet = 0;
119103 distinctColumns = 0;
119104 for(j=0; j<nColumn; j++){
119105 u8 bOnce; /* True to run the ORDER BY search loop */
119107 /* Skip over == and IS NULL terms */
119108 if( j<pLoop->u.btree.nEq
119109 && pLoop->u.btree.nSkip==0
119110 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
119112 if( i & WO_ISNULL ){
119113 testcase( isOrderDistinct );
119114 isOrderDistinct = 0;
119116 continue;
119119 /* Get the column number in the table (iColumn) and sort order
119120 ** (revIdx) for the j-th column of the index.
119122 if( pIndex ){
119123 iColumn = pIndex->aiColumn[j];
119124 revIdx = pIndex->aSortOrder[j];
119125 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
119126 }else{
119127 iColumn = -1;
119128 revIdx = 0;
119131 /* An unconstrained column that might be NULL means that this
119132 ** WhereLoop is not well-ordered
119134 if( isOrderDistinct
119135 && iColumn>=0
119136 && j>=pLoop->u.btree.nEq
119137 && pIndex->pTable->aCol[iColumn].notNull==0
119139 isOrderDistinct = 0;
119142 /* Find the ORDER BY term that corresponds to the j-th column
119143 ** of the index and mark that ORDER BY term off
119145 bOnce = 1;
119146 isMatch = 0;
119147 for(i=0; bOnce && i<nOrderBy; i++){
119148 if( MASKBIT(i) & obSat ) continue;
119149 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
119150 testcase( wctrlFlags & WHERE_GROUPBY );
119151 testcase( wctrlFlags & WHERE_DISTINCTBY );
119152 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
119153 if( pOBExpr->op!=TK_COLUMN ) continue;
119154 if( pOBExpr->iTable!=iCur ) continue;
119155 if( pOBExpr->iColumn!=iColumn ) continue;
119156 if( iColumn>=0 ){
119157 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
119158 if( !pColl ) pColl = db->pDfltColl;
119159 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
119161 isMatch = 1;
119162 break;
119164 if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
119165 /* Make sure the sort order is compatible in an ORDER BY clause.
119166 ** Sort order is irrelevant for a GROUP BY clause. */
119167 if( revSet ){
119168 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
119169 }else{
119170 rev = revIdx ^ pOrderBy->a[i].sortOrder;
119171 if( rev ) *pRevMask |= MASKBIT(iLoop);
119172 revSet = 1;
119175 if( isMatch ){
119176 if( iColumn<0 ){
119177 testcase( distinctColumns==0 );
119178 distinctColumns = 1;
119180 obSat |= MASKBIT(i);
119181 }else{
119182 /* No match found */
119183 if( j==0 || j<nKeyCol ){
119184 testcase( isOrderDistinct!=0 );
119185 isOrderDistinct = 0;
119187 break;
119189 } /* end Loop over all index columns */
119190 if( distinctColumns ){
119191 testcase( isOrderDistinct==0 );
119192 isOrderDistinct = 1;
119194 } /* end-if not one-row */
119196 /* Mark off any other ORDER BY terms that reference pLoop */
119197 if( isOrderDistinct ){
119198 orderDistinctMask |= pLoop->maskSelf;
119199 for(i=0; i<nOrderBy; i++){
119200 Expr *p;
119201 Bitmask mTerm;
119202 if( MASKBIT(i) & obSat ) continue;
119203 p = pOrderBy->a[i].pExpr;
119204 mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
119205 if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
119206 if( (mTerm&~orderDistinctMask)==0 ){
119207 obSat |= MASKBIT(i);
119211 } /* End the loop over all WhereLoops from outer-most down to inner-most */
119212 if( obSat==obDone ) return (i8)nOrderBy;
119213 if( !isOrderDistinct ){
119214 for(i=nOrderBy-1; i>0; i--){
119215 Bitmask m = MASKBIT(i) - 1;
119216 if( (obSat&m)==m ) return i;
119218 return 0;
119220 return -1;
119225 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
119226 ** the planner assumes that the specified pOrderBy list is actually a GROUP
119227 ** BY clause - and so any order that groups rows as required satisfies the
119228 ** request.
119230 ** Normally, in this case it is not possible for the caller to determine
119231 ** whether or not the rows are really being delivered in sorted order, or
119232 ** just in some other order that provides the required grouping. However,
119233 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
119234 ** this function may be called on the returned WhereInfo object. It returns
119235 ** true if the rows really will be sorted in the specified order, or false
119236 ** otherwise.
119238 ** For example, assuming:
119240 ** CREATE INDEX i1 ON t1(x, Y);
119242 ** then
119244 ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
119245 ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
119247 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
119248 assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
119249 assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
119250 return pWInfo->sorted;
119253 #ifdef WHERETRACE_ENABLED
119254 /* For debugging use only: */
119255 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
119256 static char zName[65];
119257 int i;
119258 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
119259 if( pLast ) zName[i++] = pLast->cId;
119260 zName[i] = 0;
119261 return zName;
119263 #endif
119266 ** Return the cost of sorting nRow rows, assuming that the keys have
119267 ** nOrderby columns and that the first nSorted columns are already in
119268 ** order.
119270 static LogEst whereSortingCost(
119271 WhereInfo *pWInfo,
119272 LogEst nRow,
119273 int nOrderBy,
119274 int nSorted
119276 /* TUNING: Estimated cost of a full external sort, where N is
119277 ** the number of rows to sort is:
119279 ** cost = (3.0 * N * log(N)).
119281 ** Or, if the order-by clause has X terms but only the last Y
119282 ** terms are out of order, then block-sorting will reduce the
119283 ** sorting cost to:
119285 ** cost = (3.0 * N * log(N)) * (Y/X)
119287 ** The (Y/X) term is implemented using stack variable rScale
119288 ** below. */
119289 LogEst rScale, rSortCost;
119290 assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
119291 rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
119292 rSortCost = nRow + estLog(nRow) + rScale + 16;
119294 /* TUNING: The cost of implementing DISTINCT using a B-TREE is
119295 ** similar but with a larger constant of proportionality.
119296 ** Multiply by an additional factor of 3.0. */
119297 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
119298 rSortCost += 16;
119301 return rSortCost;
119305 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
119306 ** attempts to find the lowest cost path that visits each WhereLoop
119307 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
119309 ** Assume that the total number of output rows that will need to be sorted
119310 ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
119311 ** costs if nRowEst==0.
119313 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
119314 ** error occurs.
119316 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
119317 int mxChoice; /* Maximum number of simultaneous paths tracked */
119318 int nLoop; /* Number of terms in the join */
119319 Parse *pParse; /* Parsing context */
119320 sqlite3 *db; /* The database connection */
119321 int iLoop; /* Loop counter over the terms of the join */
119322 int ii, jj; /* Loop counters */
119323 int mxI = 0; /* Index of next entry to replace */
119324 int nOrderBy; /* Number of ORDER BY clause terms */
119325 LogEst mxCost = 0; /* Maximum cost of a set of paths */
119326 LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
119327 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
119328 WherePath *aFrom; /* All nFrom paths at the previous level */
119329 WherePath *aTo; /* The nTo best paths at the current level */
119330 WherePath *pFrom; /* An element of aFrom[] that we are working on */
119331 WherePath *pTo; /* An element of aTo[] that we are working on */
119332 WhereLoop *pWLoop; /* One of the WhereLoop objects */
119333 WhereLoop **pX; /* Used to divy up the pSpace memory */
119334 LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
119335 char *pSpace; /* Temporary memory used by this routine */
119336 int nSpace; /* Bytes of space allocated at pSpace */
119338 pParse = pWInfo->pParse;
119339 db = pParse->db;
119340 nLoop = pWInfo->nLevel;
119341 /* TUNING: For simple queries, only the best path is tracked.
119342 ** For 2-way joins, the 5 best paths are followed.
119343 ** For joins of 3 or more tables, track the 10 best paths */
119344 mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
119345 assert( nLoop<=pWInfo->pTabList->nSrc );
119346 WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
119348 /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
119349 ** case the purpose of this call is to estimate the number of rows returned
119350 ** by the overall query. Once this estimate has been obtained, the caller
119351 ** will invoke this function a second time, passing the estimate as the
119352 ** nRowEst parameter. */
119353 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
119354 nOrderBy = 0;
119355 }else{
119356 nOrderBy = pWInfo->pOrderBy->nExpr;
119359 /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
119360 nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
119361 nSpace += sizeof(LogEst) * nOrderBy;
119362 pSpace = sqlite3DbMallocRaw(db, nSpace);
119363 if( pSpace==0 ) return SQLITE_NOMEM;
119364 aTo = (WherePath*)pSpace;
119365 aFrom = aTo+mxChoice;
119366 memset(aFrom, 0, sizeof(aFrom[0]));
119367 pX = (WhereLoop**)(aFrom+mxChoice);
119368 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
119369 pFrom->aLoop = pX;
119371 if( nOrderBy ){
119372 /* If there is an ORDER BY clause and it is not being ignored, set up
119373 ** space for the aSortCost[] array. Each element of the aSortCost array
119374 ** is either zero - meaning it has not yet been initialized - or the
119375 ** cost of sorting nRowEst rows of data where the first X terms of
119376 ** the ORDER BY clause are already in order, where X is the array
119377 ** index. */
119378 aSortCost = (LogEst*)pX;
119379 memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
119381 assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
119382 assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
119384 /* Seed the search with a single WherePath containing zero WhereLoops.
119386 ** TUNING: Do not let the number of iterations go above 25. If the cost
119387 ** of computing an automatic index is not paid back within the first 25
119388 ** rows, then do not use the automatic index. */
119389 aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) );
119390 nFrom = 1;
119391 assert( aFrom[0].isOrdered==0 );
119392 if( nOrderBy ){
119393 /* If nLoop is zero, then there are no FROM terms in the query. Since
119394 ** in this case the query may return a maximum of one row, the results
119395 ** are already in the requested order. Set isOrdered to nOrderBy to
119396 ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
119397 ** -1, indicating that the result set may or may not be ordered,
119398 ** depending on the loops added to the current plan. */
119399 aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
119402 /* Compute successively longer WherePaths using the previous generation
119403 ** of WherePaths as the basis for the next. Keep track of the mxChoice
119404 ** best paths at each generation */
119405 for(iLoop=0; iLoop<nLoop; iLoop++){
119406 nTo = 0;
119407 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
119408 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
119409 LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
119410 LogEst rCost; /* Cost of path (pFrom+pWLoop) */
119411 LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
119412 i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
119413 Bitmask maskNew; /* Mask of src visited by (..) */
119414 Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
119416 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
119417 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
119418 /* At this point, pWLoop is a candidate to be the next loop.
119419 ** Compute its cost */
119420 rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
119421 rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
119422 nOut = pFrom->nRow + pWLoop->nOut;
119423 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
119424 if( isOrdered<0 ){
119425 isOrdered = wherePathSatisfiesOrderBy(pWInfo,
119426 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
119427 iLoop, pWLoop, &revMask);
119428 }else{
119429 revMask = pFrom->revLoop;
119431 if( isOrdered>=0 && isOrdered<nOrderBy ){
119432 if( aSortCost[isOrdered]==0 ){
119433 aSortCost[isOrdered] = whereSortingCost(
119434 pWInfo, nRowEst, nOrderBy, isOrdered
119437 rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
119439 WHERETRACE(0x002,
119440 ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
119441 aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
119442 rUnsorted, rCost));
119443 }else{
119444 rCost = rUnsorted;
119447 /* Check to see if pWLoop should be added to the set of
119448 ** mxChoice best-so-far paths.
119450 ** First look for an existing path among best-so-far paths
119451 ** that covers the same set of loops and has the same isOrdered
119452 ** setting as the current path candidate.
119454 ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
119455 ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
119456 ** of legal values for isOrdered, -1..64.
119458 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
119459 if( pTo->maskLoop==maskNew
119460 && ((pTo->isOrdered^isOrdered)&0x80)==0
119462 testcase( jj==nTo-1 );
119463 break;
119466 if( jj>=nTo ){
119467 /* None of the existing best-so-far paths match the candidate. */
119468 if( nTo>=mxChoice
119469 && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
119471 /* The current candidate is no better than any of the mxChoice
119472 ** paths currently in the best-so-far buffer. So discard
119473 ** this candidate as not viable. */
119474 #ifdef WHERETRACE_ENABLED /* 0x4 */
119475 if( sqlite3WhereTrace&0x4 ){
119476 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
119477 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
119478 isOrdered>=0 ? isOrdered+'0' : '?');
119480 #endif
119481 continue;
119483 /* If we reach this points it means that the new candidate path
119484 ** needs to be added to the set of best-so-far paths. */
119485 if( nTo<mxChoice ){
119486 /* Increase the size of the aTo set by one */
119487 jj = nTo++;
119488 }else{
119489 /* New path replaces the prior worst to keep count below mxChoice */
119490 jj = mxI;
119492 pTo = &aTo[jj];
119493 #ifdef WHERETRACE_ENABLED /* 0x4 */
119494 if( sqlite3WhereTrace&0x4 ){
119495 sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
119496 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
119497 isOrdered>=0 ? isOrdered+'0' : '?');
119499 #endif
119500 }else{
119501 /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
119502 ** same set of loops and has the sam isOrdered setting as the
119503 ** candidate path. Check to see if the candidate should replace
119504 ** pTo or if the candidate should be skipped */
119505 if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
119506 #ifdef WHERETRACE_ENABLED /* 0x4 */
119507 if( sqlite3WhereTrace&0x4 ){
119508 sqlite3DebugPrintf(
119509 "Skip %s cost=%-3d,%3d order=%c",
119510 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
119511 isOrdered>=0 ? isOrdered+'0' : '?');
119512 sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
119513 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
119514 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
119516 #endif
119517 /* Discard the candidate path from further consideration */
119518 testcase( pTo->rCost==rCost );
119519 continue;
119521 testcase( pTo->rCost==rCost+1 );
119522 /* Control reaches here if the candidate path is better than the
119523 ** pTo path. Replace pTo with the candidate. */
119524 #ifdef WHERETRACE_ENABLED /* 0x4 */
119525 if( sqlite3WhereTrace&0x4 ){
119526 sqlite3DebugPrintf(
119527 "Update %s cost=%-3d,%3d order=%c",
119528 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
119529 isOrdered>=0 ? isOrdered+'0' : '?');
119530 sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
119531 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
119532 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
119534 #endif
119536 /* pWLoop is a winner. Add it to the set of best so far */
119537 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
119538 pTo->revLoop = revMask;
119539 pTo->nRow = nOut;
119540 pTo->rCost = rCost;
119541 pTo->rUnsorted = rUnsorted;
119542 pTo->isOrdered = isOrdered;
119543 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
119544 pTo->aLoop[iLoop] = pWLoop;
119545 if( nTo>=mxChoice ){
119546 mxI = 0;
119547 mxCost = aTo[0].rCost;
119548 mxUnsorted = aTo[0].nRow;
119549 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
119550 if( pTo->rCost>mxCost
119551 || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
119553 mxCost = pTo->rCost;
119554 mxUnsorted = pTo->rUnsorted;
119555 mxI = jj;
119562 #ifdef WHERETRACE_ENABLED /* >=2 */
119563 if( sqlite3WhereTrace>=2 ){
119564 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
119565 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
119566 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
119567 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
119568 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
119569 if( pTo->isOrdered>0 ){
119570 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
119571 }else{
119572 sqlite3DebugPrintf("\n");
119576 #endif
119578 /* Swap the roles of aFrom and aTo for the next generation */
119579 pFrom = aTo;
119580 aTo = aFrom;
119581 aFrom = pFrom;
119582 nFrom = nTo;
119585 if( nFrom==0 ){
119586 sqlite3ErrorMsg(pParse, "no query solution");
119587 sqlite3DbFree(db, pSpace);
119588 return SQLITE_ERROR;
119591 /* Find the lowest cost path. pFrom will be left pointing to that path */
119592 pFrom = aFrom;
119593 for(ii=1; ii<nFrom; ii++){
119594 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
119596 assert( pWInfo->nLevel==nLoop );
119597 /* Load the lowest cost path into pWInfo */
119598 for(iLoop=0; iLoop<nLoop; iLoop++){
119599 WhereLevel *pLevel = pWInfo->a + iLoop;
119600 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
119601 pLevel->iFrom = pWLoop->iTab;
119602 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
119604 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
119605 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
119606 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
119607 && nRowEst
119609 Bitmask notUsed;
119610 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
119611 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
119612 if( rc==pWInfo->pResultSet->nExpr ){
119613 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
119616 if( pWInfo->pOrderBy ){
119617 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
119618 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
119619 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
119621 }else{
119622 pWInfo->nOBSat = pFrom->isOrdered;
119623 if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
119624 pWInfo->revMask = pFrom->revLoop;
119626 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
119627 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr
119629 Bitmask revMask = 0;
119630 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
119631 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
119633 assert( pWInfo->sorted==0 );
119634 if( nOrder==pWInfo->pOrderBy->nExpr ){
119635 pWInfo->sorted = 1;
119636 pWInfo->revMask = revMask;
119642 pWInfo->nRowOut = pFrom->nRow;
119644 /* Free temporary memory and return success */
119645 sqlite3DbFree(db, pSpace);
119646 return SQLITE_OK;
119650 ** Most queries use only a single table (they are not joins) and have
119651 ** simple == constraints against indexed fields. This routine attempts
119652 ** to plan those simple cases using much less ceremony than the
119653 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
119654 ** times for the common case.
119656 ** Return non-zero on success, if this query can be handled by this
119657 ** no-frills query planner. Return zero if this query needs the
119658 ** general-purpose query planner.
119660 static int whereShortCut(WhereLoopBuilder *pBuilder){
119661 WhereInfo *pWInfo;
119662 struct SrcList_item *pItem;
119663 WhereClause *pWC;
119664 WhereTerm *pTerm;
119665 WhereLoop *pLoop;
119666 int iCur;
119667 int j;
119668 Table *pTab;
119669 Index *pIdx;
119671 pWInfo = pBuilder->pWInfo;
119672 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
119673 assert( pWInfo->pTabList->nSrc>=1 );
119674 pItem = pWInfo->pTabList->a;
119675 pTab = pItem->pTab;
119676 if( IsVirtual(pTab) ) return 0;
119677 if( pItem->zIndex ) return 0;
119678 iCur = pItem->iCursor;
119679 pWC = &pWInfo->sWC;
119680 pLoop = pBuilder->pNew;
119681 pLoop->wsFlags = 0;
119682 pLoop->u.btree.nSkip = 0;
119683 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
119684 if( pTerm ){
119685 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
119686 pLoop->aLTerm[0] = pTerm;
119687 pLoop->nLTerm = 1;
119688 pLoop->u.btree.nEq = 1;
119689 /* TUNING: Cost of a rowid lookup is 10 */
119690 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
119691 }else{
119692 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
119693 assert( pLoop->aLTermSpace==pLoop->aLTerm );
119694 assert( ArraySize(pLoop->aLTermSpace)==4 );
119695 if( !IsUniqueIndex(pIdx)
119696 || pIdx->pPartIdxWhere!=0
119697 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
119698 ) continue;
119699 for(j=0; j<pIdx->nKeyCol; j++){
119700 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
119701 if( pTerm==0 ) break;
119702 pLoop->aLTerm[j] = pTerm;
119704 if( j!=pIdx->nKeyCol ) continue;
119705 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
119706 if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
119707 pLoop->wsFlags |= WHERE_IDX_ONLY;
119709 pLoop->nLTerm = j;
119710 pLoop->u.btree.nEq = j;
119711 pLoop->u.btree.pIndex = pIdx;
119712 /* TUNING: Cost of a unique index lookup is 15 */
119713 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
119714 break;
119717 if( pLoop->wsFlags ){
119718 pLoop->nOut = (LogEst)1;
119719 pWInfo->a[0].pWLoop = pLoop;
119720 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
119721 pWInfo->a[0].iTabCur = iCur;
119722 pWInfo->nRowOut = 1;
119723 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
119724 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
119725 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
119727 #ifdef SQLITE_DEBUG
119728 pLoop->cId = '0';
119729 #endif
119730 return 1;
119732 return 0;
119736 ** Generate the beginning of the loop used for WHERE clause processing.
119737 ** The return value is a pointer to an opaque structure that contains
119738 ** information needed to terminate the loop. Later, the calling routine
119739 ** should invoke sqlite3WhereEnd() with the return value of this function
119740 ** in order to complete the WHERE clause processing.
119742 ** If an error occurs, this routine returns NULL.
119744 ** The basic idea is to do a nested loop, one loop for each table in
119745 ** the FROM clause of a select. (INSERT and UPDATE statements are the
119746 ** same as a SELECT with only a single table in the FROM clause.) For
119747 ** example, if the SQL is this:
119749 ** SELECT * FROM t1, t2, t3 WHERE ...;
119751 ** Then the code generated is conceptually like the following:
119753 ** foreach row1 in t1 do \ Code generated
119754 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
119755 ** foreach row3 in t3 do /
119756 ** ...
119757 ** end \ Code generated
119758 ** end |-- by sqlite3WhereEnd()
119759 ** end /
119761 ** Note that the loops might not be nested in the order in which they
119762 ** appear in the FROM clause if a different order is better able to make
119763 ** use of indices. Note also that when the IN operator appears in
119764 ** the WHERE clause, it might result in additional nested loops for
119765 ** scanning through all values on the right-hand side of the IN.
119767 ** There are Btree cursors associated with each table. t1 uses cursor
119768 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
119769 ** And so forth. This routine generates code to open those VDBE cursors
119770 ** and sqlite3WhereEnd() generates the code to close them.
119772 ** The code that sqlite3WhereBegin() generates leaves the cursors named
119773 ** in pTabList pointing at their appropriate entries. The [...] code
119774 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
119775 ** data from the various tables of the loop.
119777 ** If the WHERE clause is empty, the foreach loops must each scan their
119778 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
119779 ** the tables have indices and there are terms in the WHERE clause that
119780 ** refer to those indices, a complete table scan can be avoided and the
119781 ** code will run much faster. Most of the work of this routine is checking
119782 ** to see if there are indices that can be used to speed up the loop.
119784 ** Terms of the WHERE clause are also used to limit which rows actually
119785 ** make it to the "..." in the middle of the loop. After each "foreach",
119786 ** terms of the WHERE clause that use only terms in that loop and outer
119787 ** loops are evaluated and if false a jump is made around all subsequent
119788 ** inner loops (or around the "..." if the test occurs within the inner-
119789 ** most loop)
119791 ** OUTER JOINS
119793 ** An outer join of tables t1 and t2 is conceptally coded as follows:
119795 ** foreach row1 in t1 do
119796 ** flag = 0
119797 ** foreach row2 in t2 do
119798 ** start:
119799 ** ...
119800 ** flag = 1
119801 ** end
119802 ** if flag==0 then
119803 ** move the row2 cursor to a null row
119804 ** goto start
119805 ** fi
119806 ** end
119808 ** ORDER BY CLAUSE PROCESSING
119810 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
119811 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
119812 ** if there is one. If there is no ORDER BY clause or if this routine
119813 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
119815 ** The iIdxCur parameter is the cursor number of an index. If
119816 ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
119817 ** to use for OR clause processing. The WHERE clause should use this
119818 ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
119819 ** the first cursor in an array of cursors for all indices. iIdxCur should
119820 ** be used to compute the appropriate cursor depending on which index is
119821 ** used.
119823 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
119824 Parse *pParse, /* The parser context */
119825 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
119826 Expr *pWhere, /* The WHERE clause */
119827 ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
119828 ExprList *pResultSet, /* Result set of the query */
119829 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
119830 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
119832 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
119833 int nTabList; /* Number of elements in pTabList */
119834 WhereInfo *pWInfo; /* Will become the return value of this function */
119835 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
119836 Bitmask notReady; /* Cursors that are not yet positioned */
119837 WhereLoopBuilder sWLB; /* The WhereLoop builder */
119838 WhereMaskSet *pMaskSet; /* The expression mask set */
119839 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
119840 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
119841 int ii; /* Loop counter */
119842 sqlite3 *db; /* Database connection */
119843 int rc; /* Return code */
119846 /* Variable initialization */
119847 db = pParse->db;
119848 memset(&sWLB, 0, sizeof(sWLB));
119850 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
119851 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
119852 if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
119853 sWLB.pOrderBy = pOrderBy;
119855 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
119856 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
119857 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
119858 wctrlFlags &= ~WHERE_WANT_DISTINCT;
119861 /* The number of tables in the FROM clause is limited by the number of
119862 ** bits in a Bitmask
119864 testcase( pTabList->nSrc==BMS );
119865 if( pTabList->nSrc>BMS ){
119866 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
119867 return 0;
119870 /* This function normally generates a nested loop for all tables in
119871 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
119872 ** only generate code for the first table in pTabList and assume that
119873 ** any cursors associated with subsequent tables are uninitialized.
119875 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
119877 /* Allocate and initialize the WhereInfo structure that will become the
119878 ** return value. A single allocation is used to store the WhereInfo
119879 ** struct, the contents of WhereInfo.a[], the WhereClause structure
119880 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
119881 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
119882 ** some architectures. Hence the ROUND8() below.
119884 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
119885 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
119886 if( db->mallocFailed ){
119887 sqlite3DbFree(db, pWInfo);
119888 pWInfo = 0;
119889 goto whereBeginError;
119891 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
119892 pWInfo->nLevel = nTabList;
119893 pWInfo->pParse = pParse;
119894 pWInfo->pTabList = pTabList;
119895 pWInfo->pOrderBy = pOrderBy;
119896 pWInfo->pResultSet = pResultSet;
119897 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
119898 pWInfo->wctrlFlags = wctrlFlags;
119899 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
119900 pMaskSet = &pWInfo->sMaskSet;
119901 sWLB.pWInfo = pWInfo;
119902 sWLB.pWC = &pWInfo->sWC;
119903 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
119904 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
119905 whereLoopInit(sWLB.pNew);
119906 #ifdef SQLITE_DEBUG
119907 sWLB.pNew->cId = '*';
119908 #endif
119910 /* Split the WHERE clause into separate subexpressions where each
119911 ** subexpression is separated by an AND operator.
119913 initMaskSet(pMaskSet);
119914 whereClauseInit(&pWInfo->sWC, pWInfo);
119915 whereSplit(&pWInfo->sWC, pWhere, TK_AND);
119917 /* Special case: a WHERE clause that is constant. Evaluate the
119918 ** expression and either jump over all of the code or fall thru.
119920 for(ii=0; ii<sWLB.pWC->nTerm; ii++){
119921 if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
119922 sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
119923 SQLITE_JUMPIFNULL);
119924 sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
119928 /* Special case: No FROM clause
119930 if( nTabList==0 ){
119931 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
119932 if( wctrlFlags & WHERE_WANT_DISTINCT ){
119933 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
119937 /* Assign a bit from the bitmask to every term in the FROM clause.
119939 ** When assigning bitmask values to FROM clause cursors, it must be
119940 ** the case that if X is the bitmask for the N-th FROM clause term then
119941 ** the bitmask for all FROM clause terms to the left of the N-th term
119942 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
119943 ** its Expr.iRightJoinTable value to find the bitmask of the right table
119944 ** of the join. Subtracting one from the right table bitmask gives a
119945 ** bitmask for all tables to the left of the join. Knowing the bitmask
119946 ** for all tables to the left of a left join is important. Ticket #3015.
119948 ** Note that bitmasks are created for all pTabList->nSrc tables in
119949 ** pTabList, not just the first nTabList tables. nTabList is normally
119950 ** equal to pTabList->nSrc but might be shortened to 1 if the
119951 ** WHERE_ONETABLE_ONLY flag is set.
119953 for(ii=0; ii<pTabList->nSrc; ii++){
119954 createMask(pMaskSet, pTabList->a[ii].iCursor);
119956 #ifndef NDEBUG
119958 Bitmask toTheLeft = 0;
119959 for(ii=0; ii<pTabList->nSrc; ii++){
119960 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
119961 assert( (m-1)==toTheLeft );
119962 toTheLeft |= m;
119965 #endif
119967 /* Analyze all of the subexpressions. Note that exprAnalyze() might
119968 ** add new virtual terms onto the end of the WHERE clause. We do not
119969 ** want to analyze these virtual terms, so start analyzing at the end
119970 ** and work forward so that the added virtual terms are never processed.
119972 exprAnalyzeAll(pTabList, &pWInfo->sWC);
119973 if( db->mallocFailed ){
119974 goto whereBeginError;
119977 if( wctrlFlags & WHERE_WANT_DISTINCT ){
119978 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
119979 /* The DISTINCT marking is pointless. Ignore it. */
119980 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
119981 }else if( pOrderBy==0 ){
119982 /* Try to ORDER BY the result set to make distinct processing easier */
119983 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
119984 pWInfo->pOrderBy = pResultSet;
119988 /* Construct the WhereLoop objects */
119989 WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
119990 #if defined(WHERETRACE_ENABLED)
119991 /* Display all terms of the WHERE clause */
119992 if( sqlite3WhereTrace & 0x100 ){
119993 int i;
119994 for(i=0; i<sWLB.pWC->nTerm; i++){
119995 whereTermPrint(&sWLB.pWC->a[i], i);
119998 #endif
120000 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
120001 rc = whereLoopAddAll(&sWLB);
120002 if( rc ) goto whereBeginError;
120004 /* Display all of the WhereLoop objects if wheretrace is enabled */
120005 #ifdef WHERETRACE_ENABLED /* !=0 */
120006 if( sqlite3WhereTrace ){
120007 WhereLoop *p;
120008 int i;
120009 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
120010 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
120011 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
120012 p->cId = zLabel[i%sizeof(zLabel)];
120013 whereLoopPrint(p, sWLB.pWC);
120016 #endif
120018 wherePathSolver(pWInfo, 0);
120019 if( db->mallocFailed ) goto whereBeginError;
120020 if( pWInfo->pOrderBy ){
120021 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
120022 if( db->mallocFailed ) goto whereBeginError;
120025 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
120026 pWInfo->revMask = (Bitmask)(-1);
120028 if( pParse->nErr || NEVER(db->mallocFailed) ){
120029 goto whereBeginError;
120031 #ifdef WHERETRACE_ENABLED /* !=0 */
120032 if( sqlite3WhereTrace ){
120033 int ii;
120034 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
120035 if( pWInfo->nOBSat>0 ){
120036 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
120038 switch( pWInfo->eDistinct ){
120039 case WHERE_DISTINCT_UNIQUE: {
120040 sqlite3DebugPrintf(" DISTINCT=unique");
120041 break;
120043 case WHERE_DISTINCT_ORDERED: {
120044 sqlite3DebugPrintf(" DISTINCT=ordered");
120045 break;
120047 case WHERE_DISTINCT_UNORDERED: {
120048 sqlite3DebugPrintf(" DISTINCT=unordered");
120049 break;
120052 sqlite3DebugPrintf("\n");
120053 for(ii=0; ii<pWInfo->nLevel; ii++){
120054 whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
120057 #endif
120058 /* Attempt to omit tables from the join that do not effect the result */
120059 if( pWInfo->nLevel>=2
120060 && pResultSet!=0
120061 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
120063 Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
120064 if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
120065 while( pWInfo->nLevel>=2 ){
120066 WhereTerm *pTerm, *pEnd;
120067 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
120068 if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
120069 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
120070 && (pLoop->wsFlags & WHERE_ONEROW)==0
120072 break;
120074 if( (tabUsed & pLoop->maskSelf)!=0 ) break;
120075 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
120076 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
120077 if( (pTerm->prereqAll & pLoop->maskSelf)!=0
120078 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
120080 break;
120083 if( pTerm<pEnd ) break;
120084 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
120085 pWInfo->nLevel--;
120086 nTabList--;
120089 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
120090 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
120092 /* If the caller is an UPDATE or DELETE statement that is requesting
120093 ** to use a one-pass algorithm, determine if this is appropriate.
120094 ** The one-pass algorithm only works if the WHERE clause constrains
120095 ** the statement to update a single row.
120097 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
120098 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
120099 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
120100 pWInfo->okOnePass = 1;
120101 if( HasRowid(pTabList->a[0].pTab) ){
120102 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
120106 /* Open all tables in the pTabList and any indices selected for
120107 ** searching those tables.
120109 notReady = ~(Bitmask)0;
120110 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
120111 Table *pTab; /* Table to open */
120112 int iDb; /* Index of database containing table/index */
120113 struct SrcList_item *pTabItem;
120115 pTabItem = &pTabList->a[pLevel->iFrom];
120116 pTab = pTabItem->pTab;
120117 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
120118 pLoop = pLevel->pWLoop;
120119 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
120120 /* Do nothing */
120121 }else
120122 #ifndef SQLITE_OMIT_VIRTUALTABLE
120123 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
120124 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
120125 int iCur = pTabItem->iCursor;
120126 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
120127 }else if( IsVirtual(pTab) ){
120128 /* noop */
120129 }else
120130 #endif
120131 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
120132 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
120133 int op = OP_OpenRead;
120134 if( pWInfo->okOnePass ){
120135 op = OP_OpenWrite;
120136 pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
120138 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
120139 assert( pTabItem->iCursor==pLevel->iTabCur );
120140 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
120141 testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
120142 if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
120143 Bitmask b = pTabItem->colUsed;
120144 int n = 0;
120145 for(; b; b=b>>1, n++){}
120146 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
120147 SQLITE_INT_TO_PTR(n), P4_INT32);
120148 assert( n<=pTab->nCol );
120150 }else{
120151 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
120153 if( pLoop->wsFlags & WHERE_INDEXED ){
120154 Index *pIx = pLoop->u.btree.pIndex;
120155 int iIndexCur;
120156 int op = OP_OpenRead;
120157 /* iIdxCur is always set if to a positive value if ONEPASS is possible */
120158 assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
120159 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
120160 && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
120162 /* This is one term of an OR-optimization using the PRIMARY KEY of a
120163 ** WITHOUT ROWID table. No need for a separate index */
120164 iIndexCur = pLevel->iTabCur;
120165 op = 0;
120166 }else if( pWInfo->okOnePass ){
120167 Index *pJ = pTabItem->pTab->pIndex;
120168 iIndexCur = iIdxCur;
120169 assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
120170 while( ALWAYS(pJ) && pJ!=pIx ){
120171 iIndexCur++;
120172 pJ = pJ->pNext;
120174 op = OP_OpenWrite;
120175 pWInfo->aiCurOnePass[1] = iIndexCur;
120176 }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
120177 iIndexCur = iIdxCur;
120178 if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
120179 }else{
120180 iIndexCur = pParse->nTab++;
120182 pLevel->iIdxCur = iIndexCur;
120183 assert( pIx->pSchema==pTab->pSchema );
120184 assert( iIndexCur>=0 );
120185 if( op ){
120186 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
120187 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
120188 VdbeComment((v, "%s", pIx->zName));
120191 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
120192 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
120194 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
120195 if( db->mallocFailed ) goto whereBeginError;
120197 /* Generate the code to do the search. Each iteration of the for
120198 ** loop below generates code for a single nested loop of the VM
120199 ** program.
120201 notReady = ~(Bitmask)0;
120202 for(ii=0; ii<nTabList; ii++){
120203 pLevel = &pWInfo->a[ii];
120204 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
120205 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
120206 constructAutomaticIndex(pParse, &pWInfo->sWC,
120207 &pTabList->a[pLevel->iFrom], notReady, pLevel);
120208 if( db->mallocFailed ) goto whereBeginError;
120210 #endif
120211 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
120212 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
120213 notReady = codeOneLoopStart(pWInfo, ii, notReady);
120214 pWInfo->iContinue = pLevel->addrCont;
120217 /* Done. */
120218 VdbeModuleComment((v, "Begin WHERE-core"));
120219 return pWInfo;
120221 /* Jump here if malloc fails */
120222 whereBeginError:
120223 if( pWInfo ){
120224 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
120225 whereInfoFree(db, pWInfo);
120227 return 0;
120231 ** Generate the end of the WHERE loop. See comments on
120232 ** sqlite3WhereBegin() for additional information.
120234 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
120235 Parse *pParse = pWInfo->pParse;
120236 Vdbe *v = pParse->pVdbe;
120237 int i;
120238 WhereLevel *pLevel;
120239 WhereLoop *pLoop;
120240 SrcList *pTabList = pWInfo->pTabList;
120241 sqlite3 *db = pParse->db;
120243 /* Generate loop termination code.
120245 VdbeModuleComment((v, "End WHERE-core"));
120246 sqlite3ExprCacheClear(pParse);
120247 for(i=pWInfo->nLevel-1; i>=0; i--){
120248 int addr;
120249 pLevel = &pWInfo->a[i];
120250 pLoop = pLevel->pWLoop;
120251 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
120252 if( pLevel->op!=OP_Noop ){
120253 sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
120254 sqlite3VdbeChangeP5(v, pLevel->p5);
120255 VdbeCoverage(v);
120256 VdbeCoverageIf(v, pLevel->op==OP_Next);
120257 VdbeCoverageIf(v, pLevel->op==OP_Prev);
120258 VdbeCoverageIf(v, pLevel->op==OP_VNext);
120260 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
120261 struct InLoop *pIn;
120262 int j;
120263 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
120264 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
120265 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
120266 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
120267 VdbeCoverage(v);
120268 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
120269 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
120270 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
120272 sqlite3DbFree(db, pLevel->u.in.aInLoop);
120274 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
120275 if( pLevel->addrSkip ){
120276 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
120277 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
120278 sqlite3VdbeJumpHere(v, pLevel->addrSkip);
120279 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
120281 if( pLevel->iLeftJoin ){
120282 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
120283 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
120284 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
120285 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
120286 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
120288 if( pLoop->wsFlags & WHERE_INDEXED ){
120289 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
120291 if( pLevel->op==OP_Return ){
120292 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
120293 }else{
120294 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
120296 sqlite3VdbeJumpHere(v, addr);
120298 VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
120299 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
120302 /* The "break" point is here, just past the end of the outer loop.
120303 ** Set it.
120305 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
120307 assert( pWInfo->nLevel<=pTabList->nSrc );
120308 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
120309 int k, last;
120310 VdbeOp *pOp;
120311 Index *pIdx = 0;
120312 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
120313 Table *pTab = pTabItem->pTab;
120314 assert( pTab!=0 );
120315 pLoop = pLevel->pWLoop;
120317 /* For a co-routine, change all OP_Column references to the table of
120318 ** the co-routine into OP_SCopy of result contained in a register.
120319 ** OP_Rowid becomes OP_Null.
120321 if( pTabItem->viaCoroutine && !db->mallocFailed ){
120322 last = sqlite3VdbeCurrentAddr(v);
120323 k = pLevel->addrBody;
120324 pOp = sqlite3VdbeGetOp(v, k);
120325 for(; k<last; k++, pOp++){
120326 if( pOp->p1!=pLevel->iTabCur ) continue;
120327 if( pOp->opcode==OP_Column ){
120328 pOp->opcode = OP_Copy;
120329 pOp->p1 = pOp->p2 + pTabItem->regResult;
120330 pOp->p2 = pOp->p3;
120331 pOp->p3 = 0;
120332 }else if( pOp->opcode==OP_Rowid ){
120333 pOp->opcode = OP_Null;
120334 pOp->p1 = 0;
120335 pOp->p3 = 0;
120338 continue;
120341 /* Close all of the cursors that were opened by sqlite3WhereBegin.
120342 ** Except, do not close cursors that will be reused by the OR optimization
120343 ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
120344 ** created for the ONEPASS optimization.
120346 if( (pTab->tabFlags & TF_Ephemeral)==0
120347 && pTab->pSelect==0
120348 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
120350 int ws = pLoop->wsFlags;
120351 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
120352 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
120354 if( (ws & WHERE_INDEXED)!=0
120355 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
120356 && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
120358 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
120362 /* If this scan uses an index, make VDBE code substitutions to read data
120363 ** from the index instead of from the table where possible. In some cases
120364 ** this optimization prevents the table from ever being read, which can
120365 ** yield a significant performance boost.
120367 ** Calls to the code generator in between sqlite3WhereBegin and
120368 ** sqlite3WhereEnd will have created code that references the table
120369 ** directly. This loop scans all that code looking for opcodes
120370 ** that reference the table and converts them into opcodes that
120371 ** reference the index.
120373 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
120374 pIdx = pLoop->u.btree.pIndex;
120375 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
120376 pIdx = pLevel->u.pCovidx;
120378 if( pIdx && !db->mallocFailed ){
120379 last = sqlite3VdbeCurrentAddr(v);
120380 k = pLevel->addrBody;
120381 pOp = sqlite3VdbeGetOp(v, k);
120382 for(; k<last; k++, pOp++){
120383 if( pOp->p1!=pLevel->iTabCur ) continue;
120384 if( pOp->opcode==OP_Column ){
120385 int x = pOp->p2;
120386 assert( pIdx->pTable==pTab );
120387 if( !HasRowid(pTab) ){
120388 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
120389 x = pPk->aiColumn[x];
120391 x = sqlite3ColumnOfIndex(pIdx, x);
120392 if( x>=0 ){
120393 pOp->p2 = x;
120394 pOp->p1 = pLevel->iIdxCur;
120396 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
120397 }else if( pOp->opcode==OP_Rowid ){
120398 pOp->p1 = pLevel->iIdxCur;
120399 pOp->opcode = OP_IdxRowid;
120405 /* Final cleanup
120407 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
120408 whereInfoFree(db, pWInfo);
120409 return;
120412 /************** End of where.c ***********************************************/
120413 /************** Begin file parse.c *******************************************/
120414 /* Driver template for the LEMON parser generator.
120415 ** The author disclaims copyright to this source code.
120417 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
120418 ** The only modifications are the addition of a couple of NEVER()
120419 ** macros to disable tests that are needed in the case of a general
120420 ** LALR(1) grammar but which are always false in the
120421 ** specific grammar used by SQLite.
120423 /* First off, code is included that follows the "include" declaration
120424 ** in the input grammar file. */
120425 /* #include <stdio.h> */
120429 ** Disable all error recovery processing in the parser push-down
120430 ** automaton.
120432 #define YYNOERRORRECOVERY 1
120435 ** Make yytestcase() the same as testcase()
120437 #define yytestcase(X) testcase(X)
120440 ** An instance of this structure holds information about the
120441 ** LIMIT clause of a SELECT statement.
120443 struct LimitVal {
120444 Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
120445 Expr *pOffset; /* The OFFSET expression. NULL if there is none */
120449 ** An instance of this structure is used to store the LIKE,
120450 ** GLOB, NOT LIKE, and NOT GLOB operators.
120452 struct LikeOp {
120453 Token eOperator; /* "like" or "glob" or "regexp" */
120454 int bNot; /* True if the NOT keyword is present */
120458 ** An instance of the following structure describes the event of a
120459 ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
120460 ** TK_DELETE, or TK_INSTEAD. If the event is of the form
120462 ** UPDATE ON (a,b,c)
120464 ** Then the "b" IdList records the list "a,b,c".
120466 struct TrigEvent { int a; IdList * b; };
120469 ** An instance of this structure holds the ATTACH key and the key type.
120471 struct AttachKey { int type; Token key; };
120474 /* This is a utility routine used to set the ExprSpan.zStart and
120475 ** ExprSpan.zEnd values of pOut so that the span covers the complete
120476 ** range of text beginning with pStart and going to the end of pEnd.
120478 static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
120479 pOut->zStart = pStart->z;
120480 pOut->zEnd = &pEnd->z[pEnd->n];
120483 /* Construct a new Expr object from a single identifier. Use the
120484 ** new Expr to populate pOut. Set the span of pOut to be the identifier
120485 ** that created the expression.
120487 static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
120488 pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
120489 pOut->zStart = pValue->z;
120490 pOut->zEnd = &pValue->z[pValue->n];
120493 /* This routine constructs a binary expression node out of two ExprSpan
120494 ** objects and uses the result to populate a new ExprSpan object.
120496 static void spanBinaryExpr(
120497 ExprSpan *pOut, /* Write the result here */
120498 Parse *pParse, /* The parsing context. Errors accumulate here */
120499 int op, /* The binary operation */
120500 ExprSpan *pLeft, /* The left operand */
120501 ExprSpan *pRight /* The right operand */
120503 pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
120504 pOut->zStart = pLeft->zStart;
120505 pOut->zEnd = pRight->zEnd;
120508 /* Construct an expression node for a unary postfix operator
120510 static void spanUnaryPostfix(
120511 ExprSpan *pOut, /* Write the new expression node here */
120512 Parse *pParse, /* Parsing context to record errors */
120513 int op, /* The operator */
120514 ExprSpan *pOperand, /* The operand */
120515 Token *pPostOp /* The operand token for setting the span */
120517 pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
120518 pOut->zStart = pOperand->zStart;
120519 pOut->zEnd = &pPostOp->z[pPostOp->n];
120522 /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
120523 ** unary TK_ISNULL or TK_NOTNULL expression. */
120524 static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
120525 sqlite3 *db = pParse->db;
120526 if( pY && pA && pY->op==TK_NULL ){
120527 pA->op = (u8)op;
120528 sqlite3ExprDelete(db, pA->pRight);
120529 pA->pRight = 0;
120533 /* Construct an expression node for a unary prefix operator
120535 static void spanUnaryPrefix(
120536 ExprSpan *pOut, /* Write the new expression node here */
120537 Parse *pParse, /* Parsing context to record errors */
120538 int op, /* The operator */
120539 ExprSpan *pOperand, /* The operand */
120540 Token *pPreOp /* The operand token for setting the span */
120542 pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
120543 pOut->zStart = pPreOp->z;
120544 pOut->zEnd = pOperand->zEnd;
120546 /* Next is all token values, in a form suitable for use by makeheaders.
120547 ** This section will be null unless lemon is run with the -m switch.
120550 ** These constants (all generated automatically by the parser generator)
120551 ** specify the various kinds of tokens (terminals) that the parser
120552 ** understands.
120554 ** Each symbol here is a terminal symbol in the grammar.
120556 /* Make sure the INTERFACE macro is defined.
120558 #ifndef INTERFACE
120559 # define INTERFACE 1
120560 #endif
120561 /* The next thing included is series of defines which control
120562 ** various aspects of the generated parser.
120563 ** YYCODETYPE is the data type used for storing terminal
120564 ** and nonterminal numbers. "unsigned char" is
120565 ** used if there are fewer than 250 terminals
120566 ** and nonterminals. "int" is used otherwise.
120567 ** YYNOCODE is a number of type YYCODETYPE which corresponds
120568 ** to no legal terminal or nonterminal number. This
120569 ** number is used to fill in empty slots of the hash
120570 ** table.
120571 ** YYFALLBACK If defined, this indicates that one or more tokens
120572 ** have fall-back values which should be used if the
120573 ** original value of the token will not parse.
120574 ** YYACTIONTYPE is the data type used for storing terminal
120575 ** and nonterminal numbers. "unsigned char" is
120576 ** used if there are fewer than 250 rules and
120577 ** states combined. "int" is used otherwise.
120578 ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
120579 ** directly to the parser from the tokenizer.
120580 ** YYMINORTYPE is the data type used for all minor tokens.
120581 ** This is typically a union of many types, one of
120582 ** which is sqlite3ParserTOKENTYPE. The entry in the union
120583 ** for base tokens is called "yy0".
120584 ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
120585 ** zero the stack is dynamically sized using realloc()
120586 ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
120587 ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
120588 ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
120589 ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
120590 ** YYNSTATE the combined number of states.
120591 ** YYNRULE the number of rules in the grammar
120592 ** YYERRORSYMBOL is the code number of the error symbol. If not
120593 ** defined, then do no error processing.
120595 #define YYCODETYPE unsigned char
120596 #define YYNOCODE 254
120597 #define YYACTIONTYPE unsigned short int
120598 #define YYWILDCARD 70
120599 #define sqlite3ParserTOKENTYPE Token
120600 typedef union {
120601 int yyinit;
120602 sqlite3ParserTOKENTYPE yy0;
120603 Select* yy3;
120604 ExprList* yy14;
120605 With* yy59;
120606 SrcList* yy65;
120607 struct LikeOp yy96;
120608 Expr* yy132;
120609 u8 yy186;
120610 int yy328;
120611 ExprSpan yy346;
120612 struct TrigEvent yy378;
120613 u16 yy381;
120614 IdList* yy408;
120615 struct {int value; int mask;} yy429;
120616 TriggerStep* yy473;
120617 struct LimitVal yy476;
120618 } YYMINORTYPE;
120619 #ifndef YYSTACKDEPTH
120620 #define YYSTACKDEPTH 100
120621 #endif
120622 #define sqlite3ParserARG_SDECL Parse *pParse;
120623 #define sqlite3ParserARG_PDECL ,Parse *pParse
120624 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
120625 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
120626 #define YYNSTATE 642
120627 #define YYNRULE 327
120628 #define YYFALLBACK 1
120629 #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
120630 #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
120631 #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
120633 /* The yyzerominor constant is used to initialize instances of
120634 ** YYMINORTYPE objects to zero. */
120635 static const YYMINORTYPE yyzerominor = { 0 };
120637 /* Define the yytestcase() macro to be a no-op if is not already defined
120638 ** otherwise.
120640 ** Applications can choose to define yytestcase() in the %include section
120641 ** to a macro that can assist in verifying code coverage. For production
120642 ** code the yytestcase() macro should be turned off. But it is useful
120643 ** for testing.
120645 #ifndef yytestcase
120646 # define yytestcase(X)
120647 #endif
120650 /* Next are the tables used to determine what action to take based on the
120651 ** current state and lookahead token. These tables are used to implement
120652 ** functions that take a state number and lookahead value and return an
120653 ** action integer.
120655 ** Suppose the action integer is N. Then the action is determined as
120656 ** follows
120658 ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
120659 ** token onto the stack and goto state N.
120661 ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
120663 ** N == YYNSTATE+YYNRULE A syntax error has occurred.
120665 ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
120667 ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
120668 ** slots in the yy_action[] table.
120670 ** The action table is constructed as a single large table named yy_action[].
120671 ** Given state S and lookahead X, the action is computed as
120673 ** yy_action[ yy_shift_ofst[S] + X ]
120675 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
120676 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
120677 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
120678 ** and that yy_default[S] should be used instead.
120680 ** The formula above is for computing the action when the lookahead is
120681 ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
120682 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
120683 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
120684 ** YY_SHIFT_USE_DFLT.
120686 ** The following are the tables generated in this section:
120688 ** yy_action[] A single table containing all actions.
120689 ** yy_lookahead[] A table containing the lookahead for each entry in
120690 ** yy_action. Used to detect hash collisions.
120691 ** yy_shift_ofst[] For each state, the offset into yy_action for
120692 ** shifting terminals.
120693 ** yy_reduce_ofst[] For each state, the offset into yy_action for
120694 ** shifting non-terminals after a reduce.
120695 ** yy_default[] Default action for each state.
120697 #define YY_ACTTAB_COUNT (1497)
120698 static const YYACTIONTYPE yy_action[] = {
120699 /* 0 */ 306, 212, 432, 955, 639, 191, 955, 295, 559, 88,
120700 /* 10 */ 88, 88, 88, 81, 86, 86, 86, 86, 85, 85,
120701 /* 20 */ 84, 84, 84, 83, 330, 185, 184, 183, 635, 635,
120702 /* 30 */ 292, 606, 606, 88, 88, 88, 88, 683, 86, 86,
120703 /* 40 */ 86, 86, 85, 85, 84, 84, 84, 83, 330, 16,
120704 /* 50 */ 436, 597, 89, 90, 80, 600, 599, 601, 601, 87,
120705 /* 60 */ 87, 88, 88, 88, 88, 684, 86, 86, 86, 86,
120706 /* 70 */ 85, 85, 84, 84, 84, 83, 330, 306, 559, 84,
120707 /* 80 */ 84, 84, 83, 330, 65, 86, 86, 86, 86, 85,
120708 /* 90 */ 85, 84, 84, 84, 83, 330, 635, 635, 634, 633,
120709 /* 100 */ 182, 682, 550, 379, 376, 375, 17, 322, 606, 606,
120710 /* 110 */ 371, 198, 479, 91, 374, 82, 79, 165, 85, 85,
120711 /* 120 */ 84, 84, 84, 83, 330, 598, 635, 635, 107, 89,
120712 /* 130 */ 90, 80, 600, 599, 601, 601, 87, 87, 88, 88,
120713 /* 140 */ 88, 88, 186, 86, 86, 86, 86, 85, 85, 84,
120714 /* 150 */ 84, 84, 83, 330, 306, 594, 594, 142, 328, 327,
120715 /* 160 */ 484, 249, 344, 238, 635, 635, 634, 633, 585, 448,
120716 /* 170 */ 526, 525, 229, 388, 1, 394, 450, 584, 449, 635,
120717 /* 180 */ 635, 635, 635, 319, 395, 606, 606, 199, 157, 273,
120718 /* 190 */ 382, 268, 381, 187, 635, 635, 634, 633, 311, 555,
120719 /* 200 */ 266, 593, 593, 266, 347, 588, 89, 90, 80, 600,
120720 /* 210 */ 599, 601, 601, 87, 87, 88, 88, 88, 88, 478,
120721 /* 220 */ 86, 86, 86, 86, 85, 85, 84, 84, 84, 83,
120722 /* 230 */ 330, 306, 272, 536, 634, 633, 146, 610, 197, 310,
120723 /* 240 */ 575, 182, 482, 271, 379, 376, 375, 506, 21, 634,
120724 /* 250 */ 633, 634, 633, 635, 635, 374, 611, 574, 548, 440,
120725 /* 260 */ 111, 563, 606, 606, 634, 633, 324, 479, 608, 608,
120726 /* 270 */ 608, 300, 435, 573, 119, 407, 210, 162, 562, 883,
120727 /* 280 */ 592, 592, 306, 89, 90, 80, 600, 599, 601, 601,
120728 /* 290 */ 87, 87, 88, 88, 88, 88, 506, 86, 86, 86,
120729 /* 300 */ 86, 85, 85, 84, 84, 84, 83, 330, 620, 111,
120730 /* 310 */ 635, 635, 361, 606, 606, 358, 249, 349, 248, 433,
120731 /* 320 */ 243, 479, 586, 634, 633, 195, 611, 93, 119, 221,
120732 /* 330 */ 575, 497, 534, 534, 89, 90, 80, 600, 599, 601,
120733 /* 340 */ 601, 87, 87, 88, 88, 88, 88, 574, 86, 86,
120734 /* 350 */ 86, 86, 85, 85, 84, 84, 84, 83, 330, 306,
120735 /* 360 */ 77, 429, 638, 573, 589, 530, 240, 230, 242, 105,
120736 /* 370 */ 249, 349, 248, 515, 588, 208, 460, 529, 564, 173,
120737 /* 380 */ 634, 633, 970, 144, 430, 2, 424, 228, 380, 557,
120738 /* 390 */ 606, 606, 190, 153, 159, 158, 514, 51, 632, 631,
120739 /* 400 */ 630, 71, 536, 432, 954, 196, 610, 954, 614, 45,
120740 /* 410 */ 18, 89, 90, 80, 600, 599, 601, 601, 87, 87,
120741 /* 420 */ 88, 88, 88, 88, 261, 86, 86, 86, 86, 85,
120742 /* 430 */ 85, 84, 84, 84, 83, 330, 306, 608, 608, 608,
120743 /* 440 */ 542, 424, 402, 385, 241, 506, 451, 320, 211, 543,
120744 /* 450 */ 164, 436, 386, 293, 451, 587, 108, 496, 111, 334,
120745 /* 460 */ 391, 591, 424, 614, 27, 452, 453, 606, 606, 72,
120746 /* 470 */ 257, 70, 259, 452, 339, 342, 564, 582, 68, 415,
120747 /* 480 */ 469, 328, 327, 62, 614, 45, 110, 393, 89, 90,
120748 /* 490 */ 80, 600, 599, 601, 601, 87, 87, 88, 88, 88,
120749 /* 500 */ 88, 152, 86, 86, 86, 86, 85, 85, 84, 84,
120750 /* 510 */ 84, 83, 330, 306, 110, 499, 520, 538, 402, 389,
120751 /* 520 */ 424, 110, 566, 500, 593, 593, 454, 82, 79, 165,
120752 /* 530 */ 424, 591, 384, 564, 340, 615, 188, 162, 424, 350,
120753 /* 540 */ 616, 424, 614, 44, 606, 606, 445, 582, 300, 434,
120754 /* 550 */ 151, 19, 614, 9, 568, 580, 348, 615, 469, 567,
120755 /* 560 */ 614, 26, 616, 614, 45, 89, 90, 80, 600, 599,
120756 /* 570 */ 601, 601, 87, 87, 88, 88, 88, 88, 411, 86,
120757 /* 580 */ 86, 86, 86, 85, 85, 84, 84, 84, 83, 330,
120758 /* 590 */ 306, 579, 110, 578, 521, 282, 433, 398, 400, 255,
120759 /* 600 */ 486, 82, 79, 165, 487, 164, 82, 79, 165, 488,
120760 /* 610 */ 488, 364, 387, 424, 544, 544, 509, 350, 362, 155,
120761 /* 620 */ 191, 606, 606, 559, 642, 640, 333, 82, 79, 165,
120762 /* 630 */ 305, 564, 507, 312, 357, 614, 45, 329, 596, 595,
120763 /* 640 */ 194, 337, 89, 90, 80, 600, 599, 601, 601, 87,
120764 /* 650 */ 87, 88, 88, 88, 88, 424, 86, 86, 86, 86,
120765 /* 660 */ 85, 85, 84, 84, 84, 83, 330, 306, 20, 323,
120766 /* 670 */ 150, 263, 211, 543, 421, 596, 595, 614, 22, 424,
120767 /* 680 */ 193, 424, 284, 424, 391, 424, 509, 424, 577, 424,
120768 /* 690 */ 186, 335, 424, 559, 424, 313, 120, 546, 606, 606,
120769 /* 700 */ 67, 614, 47, 614, 50, 614, 48, 614, 100, 614,
120770 /* 710 */ 99, 614, 101, 576, 614, 102, 614, 109, 326, 89,
120771 /* 720 */ 90, 80, 600, 599, 601, 601, 87, 87, 88, 88,
120772 /* 730 */ 88, 88, 424, 86, 86, 86, 86, 85, 85, 84,
120773 /* 740 */ 84, 84, 83, 330, 306, 424, 311, 424, 585, 54,
120774 /* 750 */ 424, 516, 517, 590, 614, 112, 424, 584, 424, 572,
120775 /* 760 */ 424, 195, 424, 571, 424, 67, 424, 614, 94, 614,
120776 /* 770 */ 98, 424, 614, 97, 264, 606, 606, 195, 614, 46,
120777 /* 780 */ 614, 96, 614, 30, 614, 49, 614, 115, 614, 114,
120778 /* 790 */ 418, 229, 388, 614, 113, 306, 89, 90, 80, 600,
120779 /* 800 */ 599, 601, 601, 87, 87, 88, 88, 88, 88, 424,
120780 /* 810 */ 86, 86, 86, 86, 85, 85, 84, 84, 84, 83,
120781 /* 820 */ 330, 119, 424, 590, 110, 372, 606, 606, 195, 53,
120782 /* 830 */ 250, 614, 29, 195, 472, 438, 729, 190, 302, 498,
120783 /* 840 */ 14, 523, 641, 2, 614, 43, 306, 89, 90, 80,
120784 /* 850 */ 600, 599, 601, 601, 87, 87, 88, 88, 88, 88,
120785 /* 860 */ 424, 86, 86, 86, 86, 85, 85, 84, 84, 84,
120786 /* 870 */ 83, 330, 424, 613, 964, 964, 354, 606, 606, 420,
120787 /* 880 */ 312, 64, 614, 42, 391, 355, 283, 437, 301, 255,
120788 /* 890 */ 414, 410, 495, 492, 614, 28, 471, 306, 89, 90,
120789 /* 900 */ 80, 600, 599, 601, 601, 87, 87, 88, 88, 88,
120790 /* 910 */ 88, 424, 86, 86, 86, 86, 85, 85, 84, 84,
120791 /* 920 */ 84, 83, 330, 424, 110, 110, 110, 110, 606, 606,
120792 /* 930 */ 110, 254, 13, 614, 41, 532, 531, 283, 481, 531,
120793 /* 940 */ 457, 284, 119, 561, 356, 614, 40, 284, 306, 89,
120794 /* 950 */ 78, 80, 600, 599, 601, 601, 87, 87, 88, 88,
120795 /* 960 */ 88, 88, 424, 86, 86, 86, 86, 85, 85, 84,
120796 /* 970 */ 84, 84, 83, 330, 110, 424, 341, 220, 555, 606,
120797 /* 980 */ 606, 351, 555, 318, 614, 95, 413, 255, 83, 330,
120798 /* 990 */ 284, 284, 255, 640, 333, 356, 255, 614, 39, 306,
120799 /* 1000 */ 356, 90, 80, 600, 599, 601, 601, 87, 87, 88,
120800 /* 1010 */ 88, 88, 88, 424, 86, 86, 86, 86, 85, 85,
120801 /* 1020 */ 84, 84, 84, 83, 330, 424, 317, 316, 141, 465,
120802 /* 1030 */ 606, 606, 219, 619, 463, 614, 10, 417, 462, 255,
120803 /* 1040 */ 189, 510, 553, 351, 207, 363, 161, 614, 38, 315,
120804 /* 1050 */ 218, 255, 255, 80, 600, 599, 601, 601, 87, 87,
120805 /* 1060 */ 88, 88, 88, 88, 424, 86, 86, 86, 86, 85,
120806 /* 1070 */ 85, 84, 84, 84, 83, 330, 76, 419, 255, 3,
120807 /* 1080 */ 878, 461, 424, 247, 331, 331, 614, 37, 217, 76,
120808 /* 1090 */ 419, 390, 3, 216, 215, 422, 4, 331, 331, 424,
120809 /* 1100 */ 547, 12, 424, 545, 614, 36, 424, 541, 422, 424,
120810 /* 1110 */ 540, 424, 214, 424, 408, 424, 539, 403, 605, 605,
120811 /* 1120 */ 237, 614, 25, 119, 614, 24, 588, 408, 614, 45,
120812 /* 1130 */ 118, 614, 35, 614, 34, 614, 33, 614, 23, 588,
120813 /* 1140 */ 60, 223, 603, 602, 513, 378, 73, 74, 140, 139,
120814 /* 1150 */ 424, 110, 265, 75, 426, 425, 59, 424, 610, 73,
120815 /* 1160 */ 74, 549, 402, 404, 424, 373, 75, 426, 425, 604,
120816 /* 1170 */ 138, 610, 614, 11, 392, 76, 419, 181, 3, 614,
120817 /* 1180 */ 32, 271, 369, 331, 331, 493, 614, 31, 149, 608,
120818 /* 1190 */ 608, 608, 607, 15, 422, 365, 614, 8, 137, 489,
120819 /* 1200 */ 136, 190, 608, 608, 608, 607, 15, 485, 176, 135,
120820 /* 1210 */ 7, 252, 477, 408, 174, 133, 175, 474, 57, 56,
120821 /* 1220 */ 132, 130, 119, 76, 419, 588, 3, 468, 245, 464,
120822 /* 1230 */ 171, 331, 331, 125, 123, 456, 447, 122, 446, 104,
120823 /* 1240 */ 336, 231, 422, 166, 154, 73, 74, 332, 116, 431,
120824 /* 1250 */ 121, 309, 75, 426, 425, 222, 106, 610, 308, 637,
120825 /* 1260 */ 204, 408, 629, 627, 628, 6, 200, 428, 427, 290,
120826 /* 1270 */ 203, 622, 201, 588, 62, 63, 289, 66, 419, 399,
120827 /* 1280 */ 3, 401, 288, 92, 143, 331, 331, 287, 608, 608,
120828 /* 1290 */ 608, 607, 15, 73, 74, 227, 422, 325, 69, 416,
120829 /* 1300 */ 75, 426, 425, 612, 412, 610, 192, 61, 569, 209,
120830 /* 1310 */ 396, 226, 278, 225, 383, 408, 527, 558, 276, 533,
120831 /* 1320 */ 552, 528, 321, 523, 370, 508, 180, 588, 494, 179,
120832 /* 1330 */ 366, 117, 253, 269, 522, 503, 608, 608, 608, 607,
120833 /* 1340 */ 15, 551, 502, 58, 274, 524, 178, 73, 74, 304,
120834 /* 1350 */ 501, 368, 303, 206, 75, 426, 425, 491, 360, 610,
120835 /* 1360 */ 213, 177, 483, 131, 345, 298, 297, 296, 202, 294,
120836 /* 1370 */ 480, 490, 466, 134, 172, 129, 444, 346, 470, 128,
120837 /* 1380 */ 314, 459, 103, 127, 126, 148, 124, 167, 443, 235,
120838 /* 1390 */ 608, 608, 608, 607, 15, 442, 439, 623, 234, 299,
120839 /* 1400 */ 145, 583, 291, 377, 581, 160, 119, 156, 270, 636,
120840 /* 1410 */ 971, 169, 279, 626, 520, 625, 473, 624, 170, 621,
120841 /* 1420 */ 618, 119, 168, 55, 409, 423, 537, 609, 286, 285,
120842 /* 1430 */ 405, 570, 560, 556, 5, 52, 458, 554, 147, 267,
120843 /* 1440 */ 519, 504, 518, 406, 262, 239, 260, 512, 343, 511,
120844 /* 1450 */ 258, 353, 565, 256, 224, 251, 359, 277, 275, 476,
120845 /* 1460 */ 475, 246, 352, 244, 467, 455, 236, 233, 232, 307,
120846 /* 1470 */ 441, 281, 205, 163, 397, 280, 535, 505, 330, 617,
120847 /* 1480 */ 971, 971, 971, 971, 367, 971, 971, 971, 971, 971,
120848 /* 1490 */ 971, 971, 971, 971, 971, 971, 338,
120850 static const YYCODETYPE yy_lookahead[] = {
120851 /* 0 */ 19, 22, 22, 23, 1, 24, 26, 15, 27, 80,
120852 /* 10 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
120853 /* 20 */ 91, 92, 93, 94, 95, 108, 109, 110, 27, 28,
120854 /* 30 */ 23, 50, 51, 80, 81, 82, 83, 122, 85, 86,
120855 /* 40 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 22,
120856 /* 50 */ 70, 23, 71, 72, 73, 74, 75, 76, 77, 78,
120857 /* 60 */ 79, 80, 81, 82, 83, 122, 85, 86, 87, 88,
120858 /* 70 */ 89, 90, 91, 92, 93, 94, 95, 19, 97, 91,
120859 /* 80 */ 92, 93, 94, 95, 26, 85, 86, 87, 88, 89,
120860 /* 90 */ 90, 91, 92, 93, 94, 95, 27, 28, 97, 98,
120861 /* 100 */ 99, 122, 211, 102, 103, 104, 79, 19, 50, 51,
120862 /* 110 */ 19, 122, 59, 55, 113, 224, 225, 226, 89, 90,
120863 /* 120 */ 91, 92, 93, 94, 95, 23, 27, 28, 26, 71,
120864 /* 130 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
120865 /* 140 */ 82, 83, 51, 85, 86, 87, 88, 89, 90, 91,
120866 /* 150 */ 92, 93, 94, 95, 19, 132, 133, 58, 89, 90,
120867 /* 160 */ 21, 108, 109, 110, 27, 28, 97, 98, 33, 100,
120868 /* 170 */ 7, 8, 119, 120, 22, 19, 107, 42, 109, 27,
120869 /* 180 */ 28, 27, 28, 95, 28, 50, 51, 99, 100, 101,
120870 /* 190 */ 102, 103, 104, 105, 27, 28, 97, 98, 107, 152,
120871 /* 200 */ 112, 132, 133, 112, 65, 69, 71, 72, 73, 74,
120872 /* 210 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 11,
120873 /* 220 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
120874 /* 230 */ 95, 19, 101, 97, 97, 98, 24, 101, 122, 157,
120875 /* 240 */ 12, 99, 103, 112, 102, 103, 104, 152, 22, 97,
120876 /* 250 */ 98, 97, 98, 27, 28, 113, 27, 29, 91, 164,
120877 /* 260 */ 165, 124, 50, 51, 97, 98, 219, 59, 132, 133,
120878 /* 270 */ 134, 22, 23, 45, 66, 47, 212, 213, 124, 140,
120879 /* 280 */ 132, 133, 19, 71, 72, 73, 74, 75, 76, 77,
120880 /* 290 */ 78, 79, 80, 81, 82, 83, 152, 85, 86, 87,
120881 /* 300 */ 88, 89, 90, 91, 92, 93, 94, 95, 164, 165,
120882 /* 310 */ 27, 28, 230, 50, 51, 233, 108, 109, 110, 70,
120883 /* 320 */ 16, 59, 23, 97, 98, 26, 97, 22, 66, 185,
120884 /* 330 */ 12, 187, 27, 28, 71, 72, 73, 74, 75, 76,
120885 /* 340 */ 77, 78, 79, 80, 81, 82, 83, 29, 85, 86,
120886 /* 350 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 19,
120887 /* 360 */ 22, 148, 149, 45, 23, 47, 62, 154, 64, 156,
120888 /* 370 */ 108, 109, 110, 37, 69, 23, 163, 59, 26, 26,
120889 /* 380 */ 97, 98, 144, 145, 146, 147, 152, 200, 52, 23,
120890 /* 390 */ 50, 51, 26, 22, 89, 90, 60, 210, 7, 8,
120891 /* 400 */ 9, 138, 97, 22, 23, 26, 101, 26, 174, 175,
120892 /* 410 */ 197, 71, 72, 73, 74, 75, 76, 77, 78, 79,
120893 /* 420 */ 80, 81, 82, 83, 16, 85, 86, 87, 88, 89,
120894 /* 430 */ 90, 91, 92, 93, 94, 95, 19, 132, 133, 134,
120895 /* 440 */ 23, 152, 208, 209, 140, 152, 152, 111, 195, 196,
120896 /* 450 */ 98, 70, 163, 160, 152, 23, 22, 164, 165, 246,
120897 /* 460 */ 207, 27, 152, 174, 175, 171, 172, 50, 51, 137,
120898 /* 470 */ 62, 139, 64, 171, 172, 222, 124, 27, 138, 24,
120899 /* 480 */ 163, 89, 90, 130, 174, 175, 197, 163, 71, 72,
120900 /* 490 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
120901 /* 500 */ 83, 22, 85, 86, 87, 88, 89, 90, 91, 92,
120902 /* 510 */ 93, 94, 95, 19, 197, 181, 182, 23, 208, 209,
120903 /* 520 */ 152, 197, 26, 189, 132, 133, 232, 224, 225, 226,
120904 /* 530 */ 152, 97, 91, 26, 232, 116, 212, 213, 152, 222,
120905 /* 540 */ 121, 152, 174, 175, 50, 51, 243, 97, 22, 23,
120906 /* 550 */ 22, 234, 174, 175, 177, 23, 239, 116, 163, 177,
120907 /* 560 */ 174, 175, 121, 174, 175, 71, 72, 73, 74, 75,
120908 /* 570 */ 76, 77, 78, 79, 80, 81, 82, 83, 24, 85,
120909 /* 580 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
120910 /* 590 */ 19, 23, 197, 11, 23, 227, 70, 208, 220, 152,
120911 /* 600 */ 31, 224, 225, 226, 35, 98, 224, 225, 226, 108,
120912 /* 610 */ 109, 110, 115, 152, 117, 118, 27, 222, 49, 123,
120913 /* 620 */ 24, 50, 51, 27, 0, 1, 2, 224, 225, 226,
120914 /* 630 */ 166, 124, 168, 169, 239, 174, 175, 170, 171, 172,
120915 /* 640 */ 22, 194, 71, 72, 73, 74, 75, 76, 77, 78,
120916 /* 650 */ 79, 80, 81, 82, 83, 152, 85, 86, 87, 88,
120917 /* 660 */ 89, 90, 91, 92, 93, 94, 95, 19, 22, 208,
120918 /* 670 */ 24, 23, 195, 196, 170, 171, 172, 174, 175, 152,
120919 /* 680 */ 26, 152, 152, 152, 207, 152, 97, 152, 23, 152,
120920 /* 690 */ 51, 244, 152, 97, 152, 247, 248, 23, 50, 51,
120921 /* 700 */ 26, 174, 175, 174, 175, 174, 175, 174, 175, 174,
120922 /* 710 */ 175, 174, 175, 23, 174, 175, 174, 175, 188, 71,
120923 /* 720 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
120924 /* 730 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
120925 /* 740 */ 92, 93, 94, 95, 19, 152, 107, 152, 33, 24,
120926 /* 750 */ 152, 100, 101, 27, 174, 175, 152, 42, 152, 23,
120927 /* 760 */ 152, 26, 152, 23, 152, 26, 152, 174, 175, 174,
120928 /* 770 */ 175, 152, 174, 175, 23, 50, 51, 26, 174, 175,
120929 /* 780 */ 174, 175, 174, 175, 174, 175, 174, 175, 174, 175,
120930 /* 790 */ 163, 119, 120, 174, 175, 19, 71, 72, 73, 74,
120931 /* 800 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 152,
120932 /* 810 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
120933 /* 820 */ 95, 66, 152, 97, 197, 23, 50, 51, 26, 53,
120934 /* 830 */ 23, 174, 175, 26, 23, 23, 23, 26, 26, 26,
120935 /* 840 */ 36, 106, 146, 147, 174, 175, 19, 71, 72, 73,
120936 /* 850 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
120937 /* 860 */ 152, 85, 86, 87, 88, 89, 90, 91, 92, 93,
120938 /* 870 */ 94, 95, 152, 196, 119, 120, 19, 50, 51, 168,
120939 /* 880 */ 169, 26, 174, 175, 207, 28, 152, 249, 250, 152,
120940 /* 890 */ 163, 163, 163, 163, 174, 175, 163, 19, 71, 72,
120941 /* 900 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
120942 /* 910 */ 83, 152, 85, 86, 87, 88, 89, 90, 91, 92,
120943 /* 920 */ 93, 94, 95, 152, 197, 197, 197, 197, 50, 51,
120944 /* 930 */ 197, 194, 36, 174, 175, 191, 192, 152, 191, 192,
120945 /* 940 */ 163, 152, 66, 124, 152, 174, 175, 152, 19, 71,
120946 /* 950 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
120947 /* 960 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
120948 /* 970 */ 92, 93, 94, 95, 197, 152, 100, 188, 152, 50,
120949 /* 980 */ 51, 152, 152, 188, 174, 175, 252, 152, 94, 95,
120950 /* 990 */ 152, 152, 152, 1, 2, 152, 152, 174, 175, 19,
120951 /* 1000 */ 152, 72, 73, 74, 75, 76, 77, 78, 79, 80,
120952 /* 1010 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
120953 /* 1020 */ 91, 92, 93, 94, 95, 152, 188, 188, 22, 194,
120954 /* 1030 */ 50, 51, 240, 173, 194, 174, 175, 252, 194, 152,
120955 /* 1040 */ 36, 181, 28, 152, 23, 219, 122, 174, 175, 219,
120956 /* 1050 */ 221, 152, 152, 73, 74, 75, 76, 77, 78, 79,
120957 /* 1060 */ 80, 81, 82, 83, 152, 85, 86, 87, 88, 89,
120958 /* 1070 */ 90, 91, 92, 93, 94, 95, 19, 20, 152, 22,
120959 /* 1080 */ 23, 194, 152, 240, 27, 28, 174, 175, 240, 19,
120960 /* 1090 */ 20, 26, 22, 194, 194, 38, 22, 27, 28, 152,
120961 /* 1100 */ 23, 22, 152, 116, 174, 175, 152, 23, 38, 152,
120962 /* 1110 */ 23, 152, 221, 152, 57, 152, 23, 163, 50, 51,
120963 /* 1120 */ 194, 174, 175, 66, 174, 175, 69, 57, 174, 175,
120964 /* 1130 */ 40, 174, 175, 174, 175, 174, 175, 174, 175, 69,
120965 /* 1140 */ 22, 53, 74, 75, 30, 53, 89, 90, 22, 22,
120966 /* 1150 */ 152, 197, 23, 96, 97, 98, 22, 152, 101, 89,
120967 /* 1160 */ 90, 91, 208, 209, 152, 53, 96, 97, 98, 101,
120968 /* 1170 */ 22, 101, 174, 175, 152, 19, 20, 105, 22, 174,
120969 /* 1180 */ 175, 112, 19, 27, 28, 20, 174, 175, 24, 132,
120970 /* 1190 */ 133, 134, 135, 136, 38, 44, 174, 175, 107, 61,
120971 /* 1200 */ 54, 26, 132, 133, 134, 135, 136, 54, 107, 22,
120972 /* 1210 */ 5, 140, 1, 57, 36, 111, 122, 28, 79, 79,
120973 /* 1220 */ 131, 123, 66, 19, 20, 69, 22, 1, 16, 20,
120974 /* 1230 */ 125, 27, 28, 123, 111, 120, 23, 131, 23, 16,
120975 /* 1240 */ 68, 142, 38, 15, 22, 89, 90, 3, 167, 4,
120976 /* 1250 */ 248, 251, 96, 97, 98, 180, 180, 101, 251, 151,
120977 /* 1260 */ 6, 57, 151, 13, 151, 26, 25, 151, 161, 202,
120978 /* 1270 */ 153, 162, 153, 69, 130, 128, 203, 19, 20, 127,
120979 /* 1280 */ 22, 126, 204, 129, 22, 27, 28, 205, 132, 133,
120980 /* 1290 */ 134, 135, 136, 89, 90, 231, 38, 95, 137, 179,
120981 /* 1300 */ 96, 97, 98, 206, 179, 101, 122, 107, 159, 159,
120982 /* 1310 */ 125, 231, 216, 228, 107, 57, 184, 217, 216, 176,
120983 /* 1320 */ 217, 176, 48, 106, 18, 184, 158, 69, 159, 158,
120984 /* 1330 */ 46, 71, 237, 176, 176, 176, 132, 133, 134, 135,
120985 /* 1340 */ 136, 217, 176, 137, 216, 178, 158, 89, 90, 179,
120986 /* 1350 */ 176, 159, 179, 159, 96, 97, 98, 159, 159, 101,
120987 /* 1360 */ 5, 158, 202, 22, 18, 10, 11, 12, 13, 14,
120988 /* 1370 */ 190, 238, 17, 190, 158, 193, 41, 159, 202, 193,
120989 /* 1380 */ 159, 202, 245, 193, 193, 223, 190, 32, 159, 34,
120990 /* 1390 */ 132, 133, 134, 135, 136, 159, 39, 155, 43, 150,
120991 /* 1400 */ 223, 177, 201, 178, 177, 186, 66, 199, 177, 152,
120992 /* 1410 */ 253, 56, 215, 152, 182, 152, 202, 152, 63, 152,
120993 /* 1420 */ 152, 66, 67, 242, 229, 152, 174, 152, 152, 152,
120994 /* 1430 */ 152, 152, 152, 152, 199, 242, 202, 152, 198, 152,
120995 /* 1440 */ 152, 152, 183, 192, 152, 215, 152, 183, 215, 183,
120996 /* 1450 */ 152, 241, 214, 152, 211, 152, 152, 211, 211, 152,
120997 /* 1460 */ 152, 241, 152, 152, 152, 152, 152, 152, 152, 114,
120998 /* 1470 */ 152, 152, 235, 152, 152, 152, 174, 187, 95, 174,
120999 /* 1480 */ 253, 253, 253, 253, 236, 253, 253, 253, 253, 253,
121000 /* 1490 */ 253, 253, 253, 253, 253, 253, 141,
121002 #define YY_SHIFT_USE_DFLT (-86)
121003 #define YY_SHIFT_COUNT (429)
121004 #define YY_SHIFT_MIN (-85)
121005 #define YY_SHIFT_MAX (1383)
121006 static const short yy_shift_ofst[] = {
121007 /* 0 */ 992, 1057, 1355, 1156, 1204, 1204, 1, 262, -19, 135,
121008 /* 10 */ 135, 776, 1204, 1204, 1204, 1204, 69, 69, 53, 208,
121009 /* 20 */ 283, 755, 58, 725, 648, 571, 494, 417, 340, 263,
121010 /* 30 */ 212, 827, 827, 827, 827, 827, 827, 827, 827, 827,
121011 /* 40 */ 827, 827, 827, 827, 827, 827, 878, 827, 929, 980,
121012 /* 50 */ 980, 1070, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
121013 /* 60 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
121014 /* 70 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
121015 /* 80 */ 1258, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
121016 /* 90 */ 1204, 1204, 1204, 1204, -71, -47, -47, -47, -47, -47,
121017 /* 100 */ 0, 29, -12, 283, 283, 139, 91, 392, 392, 894,
121018 /* 110 */ 672, 726, 1383, -86, -86, -86, 88, 318, 318, 99,
121019 /* 120 */ 381, -20, 283, 283, 283, 283, 283, 283, 283, 283,
121020 /* 130 */ 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
121021 /* 140 */ 283, 283, 283, 283, 624, 876, 726, 672, 1340, 1340,
121022 /* 150 */ 1340, 1340, 1340, 1340, -86, -86, -86, 305, 136, 136,
121023 /* 160 */ 142, 167, 226, 154, 137, 152, 283, 283, 283, 283,
121024 /* 170 */ 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
121025 /* 180 */ 283, 283, 283, 336, 336, 336, 283, 283, 352, 283,
121026 /* 190 */ 283, 283, 283, 283, 228, 283, 283, 283, 283, 283,
121027 /* 200 */ 283, 283, 283, 283, 283, 501, 569, 596, 596, 596,
121028 /* 210 */ 507, 497, 441, 391, 353, 156, 156, 857, 353, 857,
121029 /* 220 */ 735, 813, 639, 715, 156, 332, 715, 715, 496, 419,
121030 /* 230 */ 646, 1357, 1184, 1184, 1335, 1335, 1184, 1341, 1260, 1144,
121031 /* 240 */ 1346, 1346, 1346, 1346, 1184, 1306, 1144, 1341, 1260, 1260,
121032 /* 250 */ 1144, 1184, 1306, 1206, 1284, 1184, 1184, 1306, 1184, 1306,
121033 /* 260 */ 1184, 1306, 1262, 1207, 1207, 1207, 1274, 1262, 1207, 1217,
121034 /* 270 */ 1207, 1274, 1207, 1207, 1185, 1200, 1185, 1200, 1185, 1200,
121035 /* 280 */ 1184, 1184, 1161, 1262, 1202, 1202, 1262, 1154, 1155, 1147,
121036 /* 290 */ 1152, 1144, 1241, 1239, 1250, 1250, 1254, 1254, 1254, 1254,
121037 /* 300 */ -86, -86, -86, -86, -86, -86, 1068, 304, 526, 249,
121038 /* 310 */ 408, -83, 434, 812, 27, 811, 807, 802, 751, 589,
121039 /* 320 */ 651, 163, 131, 674, 366, 450, 299, 148, 23, 102,
121040 /* 330 */ 229, -21, 1245, 1244, 1222, 1099, 1228, 1172, 1223, 1215,
121041 /* 340 */ 1213, 1115, 1106, 1123, 1110, 1209, 1105, 1212, 1226, 1098,
121042 /* 350 */ 1089, 1140, 1139, 1104, 1189, 1178, 1094, 1211, 1205, 1187,
121043 /* 360 */ 1101, 1071, 1153, 1175, 1146, 1138, 1151, 1091, 1164, 1165,
121044 /* 370 */ 1163, 1069, 1072, 1148, 1112, 1134, 1127, 1129, 1126, 1092,
121045 /* 380 */ 1114, 1118, 1088, 1090, 1093, 1087, 1084, 987, 1079, 1077,
121046 /* 390 */ 1074, 1065, 924, 1021, 1014, 1004, 1006, 819, 739, 896,
121047 /* 400 */ 855, 804, 739, 740, 736, 690, 654, 665, 618, 582,
121048 /* 410 */ 568, 528, 554, 379, 532, 479, 455, 379, 432, 371,
121049 /* 420 */ 341, 28, 338, 116, -11, -57, -85, 7, -8, 3,
121051 #define YY_REDUCE_USE_DFLT (-110)
121052 #define YY_REDUCE_COUNT (305)
121053 #define YY_REDUCE_MIN (-109)
121054 #define YY_REDUCE_MAX (1323)
121055 static const short yy_reduce_ofst[] = {
121056 /* 0 */ 238, 954, 213, 289, 310, 234, 144, 317, -109, 382,
121057 /* 10 */ 377, 303, 461, 389, 378, 368, 302, 294, 253, 395,
121058 /* 20 */ 293, 324, 403, 403, 403, 403, 403, 403, 403, 403,
121059 /* 30 */ 403, 403, 403, 403, 403, 403, 403, 403, 403, 403,
121060 /* 40 */ 403, 403, 403, 403, 403, 403, 403, 403, 403, 403,
121061 /* 50 */ 403, 1022, 1012, 1005, 998, 963, 961, 959, 957, 950,
121062 /* 60 */ 947, 930, 912, 873, 861, 823, 810, 771, 759, 720,
121063 /* 70 */ 708, 670, 657, 619, 614, 612, 610, 608, 606, 604,
121064 /* 80 */ 598, 595, 593, 580, 542, 540, 537, 535, 533, 531,
121065 /* 90 */ 529, 527, 503, 386, 403, 403, 403, 403, 403, 403,
121066 /* 100 */ 403, 403, 403, 95, 447, 82, 334, 504, 467, 403,
121067 /* 110 */ 477, 464, 403, 403, 403, 403, 860, 747, 744, 785,
121068 /* 120 */ 638, 638, 926, 891, 900, 899, 887, 844, 840, 835,
121069 /* 130 */ 848, 830, 843, 829, 792, 839, 826, 737, 838, 795,
121070 /* 140 */ 789, 47, 734, 530, 696, 777, 711, 677, 733, 730,
121071 /* 150 */ 729, 728, 727, 627, 448, 64, 187, 1305, 1302, 1252,
121072 /* 160 */ 1290, 1273, 1323, 1322, 1321, 1319, 1318, 1316, 1315, 1314,
121073 /* 170 */ 1313, 1312, 1311, 1310, 1308, 1307, 1304, 1303, 1301, 1298,
121074 /* 180 */ 1294, 1292, 1289, 1266, 1264, 1259, 1288, 1287, 1238, 1285,
121075 /* 190 */ 1281, 1280, 1279, 1278, 1251, 1277, 1276, 1275, 1273, 1268,
121076 /* 200 */ 1267, 1265, 1263, 1261, 1257, 1248, 1237, 1247, 1246, 1243,
121077 /* 210 */ 1238, 1240, 1235, 1249, 1234, 1233, 1230, 1220, 1214, 1210,
121078 /* 220 */ 1225, 1219, 1232, 1231, 1197, 1195, 1227, 1224, 1201, 1208,
121079 /* 230 */ 1242, 1137, 1236, 1229, 1193, 1181, 1221, 1177, 1196, 1179,
121080 /* 240 */ 1191, 1190, 1186, 1182, 1218, 1216, 1176, 1162, 1183, 1180,
121081 /* 250 */ 1160, 1199, 1203, 1133, 1095, 1198, 1194, 1188, 1192, 1171,
121082 /* 260 */ 1169, 1168, 1173, 1174, 1166, 1159, 1141, 1170, 1158, 1167,
121083 /* 270 */ 1157, 1132, 1145, 1143, 1124, 1128, 1103, 1102, 1100, 1096,
121084 /* 280 */ 1150, 1149, 1085, 1125, 1080, 1064, 1120, 1097, 1082, 1078,
121085 /* 290 */ 1073, 1067, 1109, 1107, 1119, 1117, 1116, 1113, 1111, 1108,
121086 /* 300 */ 1007, 1000, 1002, 1076, 1075, 1081,
121088 static const YYACTIONTYPE yy_default[] = {
121089 /* 0 */ 647, 964, 964, 964, 878, 878, 969, 964, 774, 802,
121090 /* 10 */ 802, 938, 969, 969, 969, 876, 969, 969, 969, 964,
121091 /* 20 */ 969, 778, 808, 969, 969, 969, 969, 969, 969, 969,
121092 /* 30 */ 969, 937, 939, 816, 815, 918, 789, 813, 806, 810,
121093 /* 40 */ 879, 872, 873, 871, 875, 880, 969, 809, 841, 856,
121094 /* 50 */ 840, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121095 /* 60 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121096 /* 70 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121097 /* 80 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121098 /* 90 */ 969, 969, 969, 969, 850, 855, 862, 854, 851, 843,
121099 /* 100 */ 842, 844, 845, 969, 969, 673, 739, 969, 969, 846,
121100 /* 110 */ 969, 685, 847, 859, 858, 857, 680, 969, 969, 969,
121101 /* 120 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121102 /* 130 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121103 /* 140 */ 969, 969, 969, 969, 647, 964, 969, 969, 964, 964,
121104 /* 150 */ 964, 964, 964, 964, 956, 778, 768, 969, 969, 969,
121105 /* 160 */ 969, 969, 969, 969, 969, 969, 969, 944, 942, 969,
121106 /* 170 */ 891, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121107 /* 180 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121108 /* 190 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121109 /* 200 */ 969, 969, 969, 969, 653, 969, 911, 774, 774, 774,
121110 /* 210 */ 776, 754, 766, 655, 812, 791, 791, 923, 812, 923,
121111 /* 220 */ 710, 733, 707, 802, 791, 874, 802, 802, 775, 766,
121112 /* 230 */ 969, 949, 782, 782, 941, 941, 782, 821, 743, 812,
121113 /* 240 */ 750, 750, 750, 750, 782, 670, 812, 821, 743, 743,
121114 /* 250 */ 812, 782, 670, 917, 915, 782, 782, 670, 782, 670,
121115 /* 260 */ 782, 670, 884, 741, 741, 741, 725, 884, 741, 710,
121116 /* 270 */ 741, 725, 741, 741, 795, 790, 795, 790, 795, 790,
121117 /* 280 */ 782, 782, 969, 884, 888, 888, 884, 807, 796, 805,
121118 /* 290 */ 803, 812, 676, 728, 663, 663, 652, 652, 652, 652,
121119 /* 300 */ 961, 961, 956, 712, 712, 695, 969, 969, 969, 969,
121120 /* 310 */ 969, 969, 687, 969, 893, 969, 969, 969, 969, 969,
121121 /* 320 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121122 /* 330 */ 969, 828, 969, 648, 951, 969, 969, 948, 969, 969,
121123 /* 340 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121124 /* 350 */ 969, 969, 969, 969, 969, 969, 921, 969, 969, 969,
121125 /* 360 */ 969, 969, 969, 914, 913, 969, 969, 969, 969, 969,
121126 /* 370 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121127 /* 380 */ 969, 969, 969, 969, 969, 969, 969, 757, 969, 969,
121128 /* 390 */ 969, 761, 969, 969, 969, 969, 969, 969, 804, 969,
121129 /* 400 */ 797, 969, 877, 969, 969, 969, 969, 969, 969, 969,
121130 /* 410 */ 969, 969, 969, 966, 969, 969, 969, 965, 969, 969,
121131 /* 420 */ 969, 969, 969, 830, 969, 829, 833, 969, 661, 969,
121132 /* 430 */ 644, 649, 960, 963, 962, 959, 958, 957, 952, 950,
121133 /* 440 */ 947, 946, 945, 943, 940, 936, 897, 895, 902, 901,
121134 /* 450 */ 900, 899, 898, 896, 894, 892, 818, 817, 814, 811,
121135 /* 460 */ 753, 935, 890, 752, 749, 748, 669, 953, 920, 929,
121136 /* 470 */ 928, 927, 822, 926, 925, 924, 922, 919, 906, 820,
121137 /* 480 */ 819, 744, 882, 881, 672, 910, 909, 908, 912, 916,
121138 /* 490 */ 907, 784, 751, 671, 668, 675, 679, 731, 732, 740,
121139 /* 500 */ 738, 737, 736, 735, 734, 730, 681, 686, 724, 709,
121140 /* 510 */ 708, 717, 716, 722, 721, 720, 719, 718, 715, 714,
121141 /* 520 */ 713, 706, 705, 711, 704, 727, 726, 723, 703, 747,
121142 /* 530 */ 746, 745, 742, 702, 701, 700, 833, 699, 698, 838,
121143 /* 540 */ 837, 866, 826, 755, 759, 758, 762, 763, 771, 770,
121144 /* 550 */ 769, 780, 781, 793, 792, 824, 823, 794, 779, 773,
121145 /* 560 */ 772, 788, 787, 786, 785, 777, 767, 799, 798, 868,
121146 /* 570 */ 783, 867, 865, 934, 933, 932, 931, 930, 870, 967,
121147 /* 580 */ 968, 887, 889, 886, 801, 800, 885, 869, 839, 836,
121148 /* 590 */ 690, 691, 905, 904, 903, 693, 692, 689, 688, 863,
121149 /* 600 */ 860, 852, 864, 861, 853, 849, 848, 834, 832, 831,
121150 /* 610 */ 827, 835, 760, 756, 825, 765, 764, 697, 696, 694,
121151 /* 620 */ 678, 677, 674, 667, 665, 664, 666, 662, 660, 659,
121152 /* 630 */ 658, 657, 656, 684, 683, 682, 654, 651, 650, 646,
121153 /* 640 */ 645, 643,
121156 /* The next table maps tokens into fallback tokens. If a construct
121157 ** like the following:
121159 ** %fallback ID X Y Z.
121161 ** appears in the grammar, then ID becomes a fallback token for X, Y,
121162 ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
121163 ** but it does not parse, the type of the token is changed to ID and
121164 ** the parse is retried before an error is thrown.
121166 #ifdef YYFALLBACK
121167 static const YYCODETYPE yyFallback[] = {
121168 0, /* $ => nothing */
121169 0, /* SEMI => nothing */
121170 27, /* EXPLAIN => ID */
121171 27, /* QUERY => ID */
121172 27, /* PLAN => ID */
121173 27, /* BEGIN => ID */
121174 0, /* TRANSACTION => nothing */
121175 27, /* DEFERRED => ID */
121176 27, /* IMMEDIATE => ID */
121177 27, /* EXCLUSIVE => ID */
121178 0, /* COMMIT => nothing */
121179 27, /* END => ID */
121180 27, /* ROLLBACK => ID */
121181 27, /* SAVEPOINT => ID */
121182 27, /* RELEASE => ID */
121183 0, /* TO => nothing */
121184 0, /* TABLE => nothing */
121185 0, /* CREATE => nothing */
121186 27, /* IF => ID */
121187 0, /* NOT => nothing */
121188 0, /* EXISTS => nothing */
121189 27, /* TEMP => ID */
121190 0, /* LP => nothing */
121191 0, /* RP => nothing */
121192 0, /* AS => nothing */
121193 27, /* WITHOUT => ID */
121194 0, /* COMMA => nothing */
121195 0, /* ID => nothing */
121196 0, /* INDEXED => nothing */
121197 27, /* ABORT => ID */
121198 27, /* ACTION => ID */
121199 27, /* AFTER => ID */
121200 27, /* ANALYZE => ID */
121201 27, /* ASC => ID */
121202 27, /* ATTACH => ID */
121203 27, /* BEFORE => ID */
121204 27, /* BY => ID */
121205 27, /* CASCADE => ID */
121206 27, /* CAST => ID */
121207 27, /* COLUMNKW => ID */
121208 27, /* CONFLICT => ID */
121209 27, /* DATABASE => ID */
121210 27, /* DESC => ID */
121211 27, /* DETACH => ID */
121212 27, /* EACH => ID */
121213 27, /* FAIL => ID */
121214 27, /* FOR => ID */
121215 27, /* IGNORE => ID */
121216 27, /* INITIALLY => ID */
121217 27, /* INSTEAD => ID */
121218 27, /* LIKE_KW => ID */
121219 27, /* MATCH => ID */
121220 27, /* NO => ID */
121221 27, /* KEY => ID */
121222 27, /* OF => ID */
121223 27, /* OFFSET => ID */
121224 27, /* PRAGMA => ID */
121225 27, /* RAISE => ID */
121226 27, /* RECURSIVE => ID */
121227 27, /* REPLACE => ID */
121228 27, /* RESTRICT => ID */
121229 27, /* ROW => ID */
121230 27, /* TRIGGER => ID */
121231 27, /* VACUUM => ID */
121232 27, /* VIEW => ID */
121233 27, /* VIRTUAL => ID */
121234 27, /* WITH => ID */
121235 27, /* REINDEX => ID */
121236 27, /* RENAME => ID */
121237 27, /* CTIME_KW => ID */
121239 #endif /* YYFALLBACK */
121241 /* The following structure represents a single element of the
121242 ** parser's stack. Information stored includes:
121244 ** + The state number for the parser at this level of the stack.
121246 ** + The value of the token stored at this level of the stack.
121247 ** (In other words, the "major" token.)
121249 ** + The semantic value stored at this level of the stack. This is
121250 ** the information used by the action routines in the grammar.
121251 ** It is sometimes called the "minor" token.
121253 struct yyStackEntry {
121254 YYACTIONTYPE stateno; /* The state-number */
121255 YYCODETYPE major; /* The major token value. This is the code
121256 ** number for the token at this stack level */
121257 YYMINORTYPE minor; /* The user-supplied minor token value. This
121258 ** is the value of the token */
121260 typedef struct yyStackEntry yyStackEntry;
121262 /* The state of the parser is completely contained in an instance of
121263 ** the following structure */
121264 struct yyParser {
121265 int yyidx; /* Index of top element in stack */
121266 #ifdef YYTRACKMAXSTACKDEPTH
121267 int yyidxMax; /* Maximum value of yyidx */
121268 #endif
121269 int yyerrcnt; /* Shifts left before out of the error */
121270 sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
121271 #if YYSTACKDEPTH<=0
121272 int yystksz; /* Current side of the stack */
121273 yyStackEntry *yystack; /* The parser's stack */
121274 #else
121275 yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
121276 #endif
121278 typedef struct yyParser yyParser;
121280 #ifndef NDEBUG
121281 /* #include <stdio.h> */
121282 static FILE *yyTraceFILE = 0;
121283 static char *yyTracePrompt = 0;
121284 #endif /* NDEBUG */
121286 #ifndef NDEBUG
121288 ** Turn parser tracing on by giving a stream to which to write the trace
121289 ** and a prompt to preface each trace message. Tracing is turned off
121290 ** by making either argument NULL
121292 ** Inputs:
121293 ** <ul>
121294 ** <li> A FILE* to which trace output should be written.
121295 ** If NULL, then tracing is turned off.
121296 ** <li> A prefix string written at the beginning of every
121297 ** line of trace output. If NULL, then tracing is
121298 ** turned off.
121299 ** </ul>
121301 ** Outputs:
121302 ** None.
121304 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
121305 yyTraceFILE = TraceFILE;
121306 yyTracePrompt = zTracePrompt;
121307 if( yyTraceFILE==0 ) yyTracePrompt = 0;
121308 else if( yyTracePrompt==0 ) yyTraceFILE = 0;
121310 #endif /* NDEBUG */
121312 #ifndef NDEBUG
121313 /* For tracing shifts, the names of all terminals and nonterminals
121314 ** are required. The following table supplies these names */
121315 static const char *const yyTokenName[] = {
121316 "$", "SEMI", "EXPLAIN", "QUERY",
121317 "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
121318 "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
121319 "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
121320 "TABLE", "CREATE", "IF", "NOT",
121321 "EXISTS", "TEMP", "LP", "RP",
121322 "AS", "WITHOUT", "COMMA", "ID",
121323 "INDEXED", "ABORT", "ACTION", "AFTER",
121324 "ANALYZE", "ASC", "ATTACH", "BEFORE",
121325 "BY", "CASCADE", "CAST", "COLUMNKW",
121326 "CONFLICT", "DATABASE", "DESC", "DETACH",
121327 "EACH", "FAIL", "FOR", "IGNORE",
121328 "INITIALLY", "INSTEAD", "LIKE_KW", "MATCH",
121329 "NO", "KEY", "OF", "OFFSET",
121330 "PRAGMA", "RAISE", "RECURSIVE", "REPLACE",
121331 "RESTRICT", "ROW", "TRIGGER", "VACUUM",
121332 "VIEW", "VIRTUAL", "WITH", "REINDEX",
121333 "RENAME", "CTIME_KW", "ANY", "OR",
121334 "AND", "IS", "BETWEEN", "IN",
121335 "ISNULL", "NOTNULL", "NE", "EQ",
121336 "GT", "LE", "LT", "GE",
121337 "ESCAPE", "BITAND", "BITOR", "LSHIFT",
121338 "RSHIFT", "PLUS", "MINUS", "STAR",
121339 "SLASH", "REM", "CONCAT", "COLLATE",
121340 "BITNOT", "STRING", "JOIN_KW", "CONSTRAINT",
121341 "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
121342 "CHECK", "REFERENCES", "AUTOINCR", "ON",
121343 "INSERT", "DELETE", "UPDATE", "SET",
121344 "DEFERRABLE", "FOREIGN", "DROP", "UNION",
121345 "ALL", "EXCEPT", "INTERSECT", "SELECT",
121346 "VALUES", "DISTINCT", "DOT", "FROM",
121347 "JOIN", "USING", "ORDER", "GROUP",
121348 "HAVING", "LIMIT", "WHERE", "INTO",
121349 "INTEGER", "FLOAT", "BLOB", "VARIABLE",
121350 "CASE", "WHEN", "THEN", "ELSE",
121351 "INDEX", "ALTER", "ADD", "error",
121352 "input", "cmdlist", "ecmd", "explain",
121353 "cmdx", "cmd", "transtype", "trans_opt",
121354 "nm", "savepoint_opt", "create_table", "create_table_args",
121355 "createkw", "temp", "ifnotexists", "dbnm",
121356 "columnlist", "conslist_opt", "table_options", "select",
121357 "column", "columnid", "type", "carglist",
121358 "typetoken", "typename", "signed", "plus_num",
121359 "minus_num", "ccons", "term", "expr",
121360 "onconf", "sortorder", "autoinc", "idxlist_opt",
121361 "refargs", "defer_subclause", "refarg", "refact",
121362 "init_deferred_pred_opt", "conslist", "tconscomma", "tcons",
121363 "idxlist", "defer_subclause_opt", "orconf", "resolvetype",
121364 "raisetype", "ifexists", "fullname", "selectnowith",
121365 "oneselect", "with", "multiselect_op", "distinct",
121366 "selcollist", "from", "where_opt", "groupby_opt",
121367 "having_opt", "orderby_opt", "limit_opt", "values",
121368 "nexprlist", "exprlist", "sclp", "as",
121369 "seltablist", "stl_prefix", "joinop", "indexed_opt",
121370 "on_opt", "using_opt", "joinop2", "idlist",
121371 "sortlist", "setlist", "insert_cmd", "inscollist_opt",
121372 "likeop", "between_op", "in_op", "case_operand",
121373 "case_exprlist", "case_else", "uniqueflag", "collate",
121374 "nmnum", "trigger_decl", "trigger_cmd_list", "trigger_time",
121375 "trigger_event", "foreach_clause", "when_clause", "trigger_cmd",
121376 "trnm", "tridxby", "database_kw_opt", "key_opt",
121377 "add_column_fullname", "kwcolumn_opt", "create_vtab", "vtabarglist",
121378 "vtabarg", "vtabargtoken", "lp", "anylist",
121379 "wqlist",
121381 #endif /* NDEBUG */
121383 #ifndef NDEBUG
121384 /* For tracing reduce actions, the names of all rules are required.
121386 static const char *const yyRuleName[] = {
121387 /* 0 */ "input ::= cmdlist",
121388 /* 1 */ "cmdlist ::= cmdlist ecmd",
121389 /* 2 */ "cmdlist ::= ecmd",
121390 /* 3 */ "ecmd ::= SEMI",
121391 /* 4 */ "ecmd ::= explain cmdx SEMI",
121392 /* 5 */ "explain ::=",
121393 /* 6 */ "explain ::= EXPLAIN",
121394 /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
121395 /* 8 */ "cmdx ::= cmd",
121396 /* 9 */ "cmd ::= BEGIN transtype trans_opt",
121397 /* 10 */ "trans_opt ::=",
121398 /* 11 */ "trans_opt ::= TRANSACTION",
121399 /* 12 */ "trans_opt ::= TRANSACTION nm",
121400 /* 13 */ "transtype ::=",
121401 /* 14 */ "transtype ::= DEFERRED",
121402 /* 15 */ "transtype ::= IMMEDIATE",
121403 /* 16 */ "transtype ::= EXCLUSIVE",
121404 /* 17 */ "cmd ::= COMMIT trans_opt",
121405 /* 18 */ "cmd ::= END trans_opt",
121406 /* 19 */ "cmd ::= ROLLBACK trans_opt",
121407 /* 20 */ "savepoint_opt ::= SAVEPOINT",
121408 /* 21 */ "savepoint_opt ::=",
121409 /* 22 */ "cmd ::= SAVEPOINT nm",
121410 /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
121411 /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
121412 /* 25 */ "cmd ::= create_table create_table_args",
121413 /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
121414 /* 27 */ "createkw ::= CREATE",
121415 /* 28 */ "ifnotexists ::=",
121416 /* 29 */ "ifnotexists ::= IF NOT EXISTS",
121417 /* 30 */ "temp ::= TEMP",
121418 /* 31 */ "temp ::=",
121419 /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
121420 /* 33 */ "create_table_args ::= AS select",
121421 /* 34 */ "table_options ::=",
121422 /* 35 */ "table_options ::= WITHOUT nm",
121423 /* 36 */ "columnlist ::= columnlist COMMA column",
121424 /* 37 */ "columnlist ::= column",
121425 /* 38 */ "column ::= columnid type carglist",
121426 /* 39 */ "columnid ::= nm",
121427 /* 40 */ "nm ::= ID|INDEXED",
121428 /* 41 */ "nm ::= STRING",
121429 /* 42 */ "nm ::= JOIN_KW",
121430 /* 43 */ "type ::=",
121431 /* 44 */ "type ::= typetoken",
121432 /* 45 */ "typetoken ::= typename",
121433 /* 46 */ "typetoken ::= typename LP signed RP",
121434 /* 47 */ "typetoken ::= typename LP signed COMMA signed RP",
121435 /* 48 */ "typename ::= ID|STRING",
121436 /* 49 */ "typename ::= typename ID|STRING",
121437 /* 50 */ "signed ::= plus_num",
121438 /* 51 */ "signed ::= minus_num",
121439 /* 52 */ "carglist ::= carglist ccons",
121440 /* 53 */ "carglist ::=",
121441 /* 54 */ "ccons ::= CONSTRAINT nm",
121442 /* 55 */ "ccons ::= DEFAULT term",
121443 /* 56 */ "ccons ::= DEFAULT LP expr RP",
121444 /* 57 */ "ccons ::= DEFAULT PLUS term",
121445 /* 58 */ "ccons ::= DEFAULT MINUS term",
121446 /* 59 */ "ccons ::= DEFAULT ID|INDEXED",
121447 /* 60 */ "ccons ::= NULL onconf",
121448 /* 61 */ "ccons ::= NOT NULL onconf",
121449 /* 62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
121450 /* 63 */ "ccons ::= UNIQUE onconf",
121451 /* 64 */ "ccons ::= CHECK LP expr RP",
121452 /* 65 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
121453 /* 66 */ "ccons ::= defer_subclause",
121454 /* 67 */ "ccons ::= COLLATE ID|STRING",
121455 /* 68 */ "autoinc ::=",
121456 /* 69 */ "autoinc ::= AUTOINCR",
121457 /* 70 */ "refargs ::=",
121458 /* 71 */ "refargs ::= refargs refarg",
121459 /* 72 */ "refarg ::= MATCH nm",
121460 /* 73 */ "refarg ::= ON INSERT refact",
121461 /* 74 */ "refarg ::= ON DELETE refact",
121462 /* 75 */ "refarg ::= ON UPDATE refact",
121463 /* 76 */ "refact ::= SET NULL",
121464 /* 77 */ "refact ::= SET DEFAULT",
121465 /* 78 */ "refact ::= CASCADE",
121466 /* 79 */ "refact ::= RESTRICT",
121467 /* 80 */ "refact ::= NO ACTION",
121468 /* 81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
121469 /* 82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
121470 /* 83 */ "init_deferred_pred_opt ::=",
121471 /* 84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
121472 /* 85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
121473 /* 86 */ "conslist_opt ::=",
121474 /* 87 */ "conslist_opt ::= COMMA conslist",
121475 /* 88 */ "conslist ::= conslist tconscomma tcons",
121476 /* 89 */ "conslist ::= tcons",
121477 /* 90 */ "tconscomma ::= COMMA",
121478 /* 91 */ "tconscomma ::=",
121479 /* 92 */ "tcons ::= CONSTRAINT nm",
121480 /* 93 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
121481 /* 94 */ "tcons ::= UNIQUE LP idxlist RP onconf",
121482 /* 95 */ "tcons ::= CHECK LP expr RP onconf",
121483 /* 96 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
121484 /* 97 */ "defer_subclause_opt ::=",
121485 /* 98 */ "defer_subclause_opt ::= defer_subclause",
121486 /* 99 */ "onconf ::=",
121487 /* 100 */ "onconf ::= ON CONFLICT resolvetype",
121488 /* 101 */ "orconf ::=",
121489 /* 102 */ "orconf ::= OR resolvetype",
121490 /* 103 */ "resolvetype ::= raisetype",
121491 /* 104 */ "resolvetype ::= IGNORE",
121492 /* 105 */ "resolvetype ::= REPLACE",
121493 /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
121494 /* 107 */ "ifexists ::= IF EXISTS",
121495 /* 108 */ "ifexists ::=",
121496 /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
121497 /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
121498 /* 111 */ "cmd ::= select",
121499 /* 112 */ "select ::= with selectnowith",
121500 /* 113 */ "selectnowith ::= oneselect",
121501 /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
121502 /* 115 */ "multiselect_op ::= UNION",
121503 /* 116 */ "multiselect_op ::= UNION ALL",
121504 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
121505 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
121506 /* 119 */ "oneselect ::= values",
121507 /* 120 */ "values ::= VALUES LP nexprlist RP",
121508 /* 121 */ "values ::= values COMMA LP exprlist RP",
121509 /* 122 */ "distinct ::= DISTINCT",
121510 /* 123 */ "distinct ::= ALL",
121511 /* 124 */ "distinct ::=",
121512 /* 125 */ "sclp ::= selcollist COMMA",
121513 /* 126 */ "sclp ::=",
121514 /* 127 */ "selcollist ::= sclp expr as",
121515 /* 128 */ "selcollist ::= sclp STAR",
121516 /* 129 */ "selcollist ::= sclp nm DOT STAR",
121517 /* 130 */ "as ::= AS nm",
121518 /* 131 */ "as ::= ID|STRING",
121519 /* 132 */ "as ::=",
121520 /* 133 */ "from ::=",
121521 /* 134 */ "from ::= FROM seltablist",
121522 /* 135 */ "stl_prefix ::= seltablist joinop",
121523 /* 136 */ "stl_prefix ::=",
121524 /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
121525 /* 138 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
121526 /* 139 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
121527 /* 140 */ "dbnm ::=",
121528 /* 141 */ "dbnm ::= DOT nm",
121529 /* 142 */ "fullname ::= nm dbnm",
121530 /* 143 */ "joinop ::= COMMA|JOIN",
121531 /* 144 */ "joinop ::= JOIN_KW JOIN",
121532 /* 145 */ "joinop ::= JOIN_KW nm JOIN",
121533 /* 146 */ "joinop ::= JOIN_KW nm nm JOIN",
121534 /* 147 */ "on_opt ::= ON expr",
121535 /* 148 */ "on_opt ::=",
121536 /* 149 */ "indexed_opt ::=",
121537 /* 150 */ "indexed_opt ::= INDEXED BY nm",
121538 /* 151 */ "indexed_opt ::= NOT INDEXED",
121539 /* 152 */ "using_opt ::= USING LP idlist RP",
121540 /* 153 */ "using_opt ::=",
121541 /* 154 */ "orderby_opt ::=",
121542 /* 155 */ "orderby_opt ::= ORDER BY sortlist",
121543 /* 156 */ "sortlist ::= sortlist COMMA expr sortorder",
121544 /* 157 */ "sortlist ::= expr sortorder",
121545 /* 158 */ "sortorder ::= ASC",
121546 /* 159 */ "sortorder ::= DESC",
121547 /* 160 */ "sortorder ::=",
121548 /* 161 */ "groupby_opt ::=",
121549 /* 162 */ "groupby_opt ::= GROUP BY nexprlist",
121550 /* 163 */ "having_opt ::=",
121551 /* 164 */ "having_opt ::= HAVING expr",
121552 /* 165 */ "limit_opt ::=",
121553 /* 166 */ "limit_opt ::= LIMIT expr",
121554 /* 167 */ "limit_opt ::= LIMIT expr OFFSET expr",
121555 /* 168 */ "limit_opt ::= LIMIT expr COMMA expr",
121556 /* 169 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
121557 /* 170 */ "where_opt ::=",
121558 /* 171 */ "where_opt ::= WHERE expr",
121559 /* 172 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
121560 /* 173 */ "setlist ::= setlist COMMA nm EQ expr",
121561 /* 174 */ "setlist ::= nm EQ expr",
121562 /* 175 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt select",
121563 /* 176 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
121564 /* 177 */ "insert_cmd ::= INSERT orconf",
121565 /* 178 */ "insert_cmd ::= REPLACE",
121566 /* 179 */ "inscollist_opt ::=",
121567 /* 180 */ "inscollist_opt ::= LP idlist RP",
121568 /* 181 */ "idlist ::= idlist COMMA nm",
121569 /* 182 */ "idlist ::= nm",
121570 /* 183 */ "expr ::= term",
121571 /* 184 */ "expr ::= LP expr RP",
121572 /* 185 */ "term ::= NULL",
121573 /* 186 */ "expr ::= ID|INDEXED",
121574 /* 187 */ "expr ::= JOIN_KW",
121575 /* 188 */ "expr ::= nm DOT nm",
121576 /* 189 */ "expr ::= nm DOT nm DOT nm",
121577 /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
121578 /* 191 */ "term ::= STRING",
121579 /* 192 */ "expr ::= VARIABLE",
121580 /* 193 */ "expr ::= expr COLLATE ID|STRING",
121581 /* 194 */ "expr ::= CAST LP expr AS typetoken RP",
121582 /* 195 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
121583 /* 196 */ "expr ::= ID|INDEXED LP STAR RP",
121584 /* 197 */ "term ::= CTIME_KW",
121585 /* 198 */ "expr ::= expr AND expr",
121586 /* 199 */ "expr ::= expr OR expr",
121587 /* 200 */ "expr ::= expr LT|GT|GE|LE expr",
121588 /* 201 */ "expr ::= expr EQ|NE expr",
121589 /* 202 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
121590 /* 203 */ "expr ::= expr PLUS|MINUS expr",
121591 /* 204 */ "expr ::= expr STAR|SLASH|REM expr",
121592 /* 205 */ "expr ::= expr CONCAT expr",
121593 /* 206 */ "likeop ::= LIKE_KW|MATCH",
121594 /* 207 */ "likeop ::= NOT LIKE_KW|MATCH",
121595 /* 208 */ "expr ::= expr likeop expr",
121596 /* 209 */ "expr ::= expr likeop expr ESCAPE expr",
121597 /* 210 */ "expr ::= expr ISNULL|NOTNULL",
121598 /* 211 */ "expr ::= expr NOT NULL",
121599 /* 212 */ "expr ::= expr IS expr",
121600 /* 213 */ "expr ::= expr IS NOT expr",
121601 /* 214 */ "expr ::= NOT expr",
121602 /* 215 */ "expr ::= BITNOT expr",
121603 /* 216 */ "expr ::= MINUS expr",
121604 /* 217 */ "expr ::= PLUS expr",
121605 /* 218 */ "between_op ::= BETWEEN",
121606 /* 219 */ "between_op ::= NOT BETWEEN",
121607 /* 220 */ "expr ::= expr between_op expr AND expr",
121608 /* 221 */ "in_op ::= IN",
121609 /* 222 */ "in_op ::= NOT IN",
121610 /* 223 */ "expr ::= expr in_op LP exprlist RP",
121611 /* 224 */ "expr ::= LP select RP",
121612 /* 225 */ "expr ::= expr in_op LP select RP",
121613 /* 226 */ "expr ::= expr in_op nm dbnm",
121614 /* 227 */ "expr ::= EXISTS LP select RP",
121615 /* 228 */ "expr ::= CASE case_operand case_exprlist case_else END",
121616 /* 229 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
121617 /* 230 */ "case_exprlist ::= WHEN expr THEN expr",
121618 /* 231 */ "case_else ::= ELSE expr",
121619 /* 232 */ "case_else ::=",
121620 /* 233 */ "case_operand ::= expr",
121621 /* 234 */ "case_operand ::=",
121622 /* 235 */ "exprlist ::= nexprlist",
121623 /* 236 */ "exprlist ::=",
121624 /* 237 */ "nexprlist ::= nexprlist COMMA expr",
121625 /* 238 */ "nexprlist ::= expr",
121626 /* 239 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
121627 /* 240 */ "uniqueflag ::= UNIQUE",
121628 /* 241 */ "uniqueflag ::=",
121629 /* 242 */ "idxlist_opt ::=",
121630 /* 243 */ "idxlist_opt ::= LP idxlist RP",
121631 /* 244 */ "idxlist ::= idxlist COMMA nm collate sortorder",
121632 /* 245 */ "idxlist ::= nm collate sortorder",
121633 /* 246 */ "collate ::=",
121634 /* 247 */ "collate ::= COLLATE ID|STRING",
121635 /* 248 */ "cmd ::= DROP INDEX ifexists fullname",
121636 /* 249 */ "cmd ::= VACUUM",
121637 /* 250 */ "cmd ::= VACUUM nm",
121638 /* 251 */ "cmd ::= PRAGMA nm dbnm",
121639 /* 252 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
121640 /* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
121641 /* 254 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
121642 /* 255 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
121643 /* 256 */ "nmnum ::= plus_num",
121644 /* 257 */ "nmnum ::= nm",
121645 /* 258 */ "nmnum ::= ON",
121646 /* 259 */ "nmnum ::= DELETE",
121647 /* 260 */ "nmnum ::= DEFAULT",
121648 /* 261 */ "plus_num ::= PLUS INTEGER|FLOAT",
121649 /* 262 */ "plus_num ::= INTEGER|FLOAT",
121650 /* 263 */ "minus_num ::= MINUS INTEGER|FLOAT",
121651 /* 264 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
121652 /* 265 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
121653 /* 266 */ "trigger_time ::= BEFORE",
121654 /* 267 */ "trigger_time ::= AFTER",
121655 /* 268 */ "trigger_time ::= INSTEAD OF",
121656 /* 269 */ "trigger_time ::=",
121657 /* 270 */ "trigger_event ::= DELETE|INSERT",
121658 /* 271 */ "trigger_event ::= UPDATE",
121659 /* 272 */ "trigger_event ::= UPDATE OF idlist",
121660 /* 273 */ "foreach_clause ::=",
121661 /* 274 */ "foreach_clause ::= FOR EACH ROW",
121662 /* 275 */ "when_clause ::=",
121663 /* 276 */ "when_clause ::= WHEN expr",
121664 /* 277 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
121665 /* 278 */ "trigger_cmd_list ::= trigger_cmd SEMI",
121666 /* 279 */ "trnm ::= nm",
121667 /* 280 */ "trnm ::= nm DOT nm",
121668 /* 281 */ "tridxby ::=",
121669 /* 282 */ "tridxby ::= INDEXED BY nm",
121670 /* 283 */ "tridxby ::= NOT INDEXED",
121671 /* 284 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
121672 /* 285 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
121673 /* 286 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
121674 /* 287 */ "trigger_cmd ::= select",
121675 /* 288 */ "expr ::= RAISE LP IGNORE RP",
121676 /* 289 */ "expr ::= RAISE LP raisetype COMMA nm RP",
121677 /* 290 */ "raisetype ::= ROLLBACK",
121678 /* 291 */ "raisetype ::= ABORT",
121679 /* 292 */ "raisetype ::= FAIL",
121680 /* 293 */ "cmd ::= DROP TRIGGER ifexists fullname",
121681 /* 294 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
121682 /* 295 */ "cmd ::= DETACH database_kw_opt expr",
121683 /* 296 */ "key_opt ::=",
121684 /* 297 */ "key_opt ::= KEY expr",
121685 /* 298 */ "database_kw_opt ::= DATABASE",
121686 /* 299 */ "database_kw_opt ::=",
121687 /* 300 */ "cmd ::= REINDEX",
121688 /* 301 */ "cmd ::= REINDEX nm dbnm",
121689 /* 302 */ "cmd ::= ANALYZE",
121690 /* 303 */ "cmd ::= ANALYZE nm dbnm",
121691 /* 304 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
121692 /* 305 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
121693 /* 306 */ "add_column_fullname ::= fullname",
121694 /* 307 */ "kwcolumn_opt ::=",
121695 /* 308 */ "kwcolumn_opt ::= COLUMNKW",
121696 /* 309 */ "cmd ::= create_vtab",
121697 /* 310 */ "cmd ::= create_vtab LP vtabarglist RP",
121698 /* 311 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
121699 /* 312 */ "vtabarglist ::= vtabarg",
121700 /* 313 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
121701 /* 314 */ "vtabarg ::=",
121702 /* 315 */ "vtabarg ::= vtabarg vtabargtoken",
121703 /* 316 */ "vtabargtoken ::= ANY",
121704 /* 317 */ "vtabargtoken ::= lp anylist RP",
121705 /* 318 */ "lp ::= LP",
121706 /* 319 */ "anylist ::=",
121707 /* 320 */ "anylist ::= anylist LP anylist RP",
121708 /* 321 */ "anylist ::= anylist ANY",
121709 /* 322 */ "with ::=",
121710 /* 323 */ "with ::= WITH wqlist",
121711 /* 324 */ "with ::= WITH RECURSIVE wqlist",
121712 /* 325 */ "wqlist ::= nm idxlist_opt AS LP select RP",
121713 /* 326 */ "wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP",
121715 #endif /* NDEBUG */
121718 #if YYSTACKDEPTH<=0
121720 ** Try to increase the size of the parser stack.
121722 static void yyGrowStack(yyParser *p){
121723 int newSize;
121724 yyStackEntry *pNew;
121726 newSize = p->yystksz*2 + 100;
121727 pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
121728 if( pNew ){
121729 p->yystack = pNew;
121730 p->yystksz = newSize;
121731 #ifndef NDEBUG
121732 if( yyTraceFILE ){
121733 fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
121734 yyTracePrompt, p->yystksz);
121736 #endif
121739 #endif
121742 ** This function allocates a new parser.
121743 ** The only argument is a pointer to a function which works like
121744 ** malloc.
121746 ** Inputs:
121747 ** A pointer to the function used to allocate memory.
121749 ** Outputs:
121750 ** A pointer to a parser. This pointer is used in subsequent calls
121751 ** to sqlite3Parser and sqlite3ParserFree.
121753 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(u64)){
121754 yyParser *pParser;
121755 pParser = (yyParser*)(*mallocProc)( (u64)sizeof(yyParser) );
121756 if( pParser ){
121757 pParser->yyidx = -1;
121758 #ifdef YYTRACKMAXSTACKDEPTH
121759 pParser->yyidxMax = 0;
121760 #endif
121761 #if YYSTACKDEPTH<=0
121762 pParser->yystack = NULL;
121763 pParser->yystksz = 0;
121764 yyGrowStack(pParser);
121765 #endif
121767 return pParser;
121770 /* The following function deletes the value associated with a
121771 ** symbol. The symbol can be either a terminal or nonterminal.
121772 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
121773 ** the value.
121775 static void yy_destructor(
121776 yyParser *yypParser, /* The parser */
121777 YYCODETYPE yymajor, /* Type code for object to destroy */
121778 YYMINORTYPE *yypminor /* The object to be destroyed */
121780 sqlite3ParserARG_FETCH;
121781 switch( yymajor ){
121782 /* Here is inserted the actions which take place when a
121783 ** terminal or non-terminal is destroyed. This can happen
121784 ** when the symbol is popped from the stack during a
121785 ** reduce or during error processing or when a parser is
121786 ** being destroyed before it is finished parsing.
121788 ** Note: during a reduce, the only symbols destroyed are those
121789 ** which appear on the RHS of the rule, but which are not used
121790 ** inside the C code.
121792 case 163: /* select */
121793 case 195: /* selectnowith */
121794 case 196: /* oneselect */
121795 case 207: /* values */
121797 sqlite3SelectDelete(pParse->db, (yypminor->yy3));
121799 break;
121800 case 174: /* term */
121801 case 175: /* expr */
121803 sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
121805 break;
121806 case 179: /* idxlist_opt */
121807 case 188: /* idxlist */
121808 case 200: /* selcollist */
121809 case 203: /* groupby_opt */
121810 case 205: /* orderby_opt */
121811 case 208: /* nexprlist */
121812 case 209: /* exprlist */
121813 case 210: /* sclp */
121814 case 220: /* sortlist */
121815 case 221: /* setlist */
121816 case 228: /* case_exprlist */
121818 sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
121820 break;
121821 case 194: /* fullname */
121822 case 201: /* from */
121823 case 212: /* seltablist */
121824 case 213: /* stl_prefix */
121826 sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
121828 break;
121829 case 197: /* with */
121830 case 252: /* wqlist */
121832 sqlite3WithDelete(pParse->db, (yypminor->yy59));
121834 break;
121835 case 202: /* where_opt */
121836 case 204: /* having_opt */
121837 case 216: /* on_opt */
121838 case 227: /* case_operand */
121839 case 229: /* case_else */
121840 case 238: /* when_clause */
121841 case 243: /* key_opt */
121843 sqlite3ExprDelete(pParse->db, (yypminor->yy132));
121845 break;
121846 case 217: /* using_opt */
121847 case 219: /* idlist */
121848 case 223: /* inscollist_opt */
121850 sqlite3IdListDelete(pParse->db, (yypminor->yy408));
121852 break;
121853 case 234: /* trigger_cmd_list */
121854 case 239: /* trigger_cmd */
121856 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
121858 break;
121859 case 236: /* trigger_event */
121861 sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
121863 break;
121864 default: break; /* If no destructor action specified: do nothing */
121869 ** Pop the parser's stack once.
121871 ** If there is a destructor routine associated with the token which
121872 ** is popped from the stack, then call it.
121874 ** Return the major token number for the symbol popped.
121876 static int yy_pop_parser_stack(yyParser *pParser){
121877 YYCODETYPE yymajor;
121878 yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
121880 /* There is no mechanism by which the parser stack can be popped below
121881 ** empty in SQLite. */
121882 if( NEVER(pParser->yyidx<0) ) return 0;
121883 #ifndef NDEBUG
121884 if( yyTraceFILE && pParser->yyidx>=0 ){
121885 fprintf(yyTraceFILE,"%sPopping %s\n",
121886 yyTracePrompt,
121887 yyTokenName[yytos->major]);
121889 #endif
121890 yymajor = yytos->major;
121891 yy_destructor(pParser, yymajor, &yytos->minor);
121892 pParser->yyidx--;
121893 return yymajor;
121897 ** Deallocate and destroy a parser. Destructors are all called for
121898 ** all stack elements before shutting the parser down.
121900 ** Inputs:
121901 ** <ul>
121902 ** <li> A pointer to the parser. This should be a pointer
121903 ** obtained from sqlite3ParserAlloc.
121904 ** <li> A pointer to a function used to reclaim memory obtained
121905 ** from malloc.
121906 ** </ul>
121908 SQLITE_PRIVATE void sqlite3ParserFree(
121909 void *p, /* The parser to be deleted */
121910 void (*freeProc)(void*) /* Function used to reclaim memory */
121912 yyParser *pParser = (yyParser*)p;
121913 /* In SQLite, we never try to destroy a parser that was not successfully
121914 ** created in the first place. */
121915 if( NEVER(pParser==0) ) return;
121916 while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
121917 #if YYSTACKDEPTH<=0
121918 free(pParser->yystack);
121919 #endif
121920 (*freeProc)((void*)pParser);
121924 ** Return the peak depth of the stack for a parser.
121926 #ifdef YYTRACKMAXSTACKDEPTH
121927 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
121928 yyParser *pParser = (yyParser*)p;
121929 return pParser->yyidxMax;
121931 #endif
121934 ** Find the appropriate action for a parser given the terminal
121935 ** look-ahead token iLookAhead.
121937 ** If the look-ahead token is YYNOCODE, then check to see if the action is
121938 ** independent of the look-ahead. If it is, return the action, otherwise
121939 ** return YY_NO_ACTION.
121941 static int yy_find_shift_action(
121942 yyParser *pParser, /* The parser */
121943 YYCODETYPE iLookAhead /* The look-ahead token */
121945 int i;
121946 int stateno = pParser->yystack[pParser->yyidx].stateno;
121948 if( stateno>YY_SHIFT_COUNT
121949 || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
121950 return yy_default[stateno];
121952 assert( iLookAhead!=YYNOCODE );
121953 i += iLookAhead;
121954 if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
121955 if( iLookAhead>0 ){
121956 #ifdef YYFALLBACK
121957 YYCODETYPE iFallback; /* Fallback token */
121958 if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
121959 && (iFallback = yyFallback[iLookAhead])!=0 ){
121960 #ifndef NDEBUG
121961 if( yyTraceFILE ){
121962 fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
121963 yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
121965 #endif
121966 return yy_find_shift_action(pParser, iFallback);
121968 #endif
121969 #ifdef YYWILDCARD
121971 int j = i - iLookAhead + YYWILDCARD;
121973 #if YY_SHIFT_MIN+YYWILDCARD<0
121974 j>=0 &&
121975 #endif
121976 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
121977 j<YY_ACTTAB_COUNT &&
121978 #endif
121979 yy_lookahead[j]==YYWILDCARD
121981 #ifndef NDEBUG
121982 if( yyTraceFILE ){
121983 fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
121984 yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
121986 #endif /* NDEBUG */
121987 return yy_action[j];
121990 #endif /* YYWILDCARD */
121992 return yy_default[stateno];
121993 }else{
121994 return yy_action[i];
121999 ** Find the appropriate action for a parser given the non-terminal
122000 ** look-ahead token iLookAhead.
122002 ** If the look-ahead token is YYNOCODE, then check to see if the action is
122003 ** independent of the look-ahead. If it is, return the action, otherwise
122004 ** return YY_NO_ACTION.
122006 static int yy_find_reduce_action(
122007 int stateno, /* Current state number */
122008 YYCODETYPE iLookAhead /* The look-ahead token */
122010 int i;
122011 #ifdef YYERRORSYMBOL
122012 if( stateno>YY_REDUCE_COUNT ){
122013 return yy_default[stateno];
122015 #else
122016 assert( stateno<=YY_REDUCE_COUNT );
122017 #endif
122018 i = yy_reduce_ofst[stateno];
122019 assert( i!=YY_REDUCE_USE_DFLT );
122020 assert( iLookAhead!=YYNOCODE );
122021 i += iLookAhead;
122022 #ifdef YYERRORSYMBOL
122023 if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
122024 return yy_default[stateno];
122026 #else
122027 assert( i>=0 && i<YY_ACTTAB_COUNT );
122028 assert( yy_lookahead[i]==iLookAhead );
122029 #endif
122030 return yy_action[i];
122034 ** The following routine is called if the stack overflows.
122036 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
122037 sqlite3ParserARG_FETCH;
122038 yypParser->yyidx--;
122039 #ifndef NDEBUG
122040 if( yyTraceFILE ){
122041 fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
122043 #endif
122044 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
122045 /* Here code is inserted which will execute if the parser
122046 ** stack every overflows */
122048 UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
122049 sqlite3ErrorMsg(pParse, "parser stack overflow");
122050 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
122054 ** Perform a shift action.
122056 static void yy_shift(
122057 yyParser *yypParser, /* The parser to be shifted */
122058 int yyNewState, /* The new state to shift in */
122059 int yyMajor, /* The major token to shift in */
122060 YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
122062 yyStackEntry *yytos;
122063 yypParser->yyidx++;
122064 #ifdef YYTRACKMAXSTACKDEPTH
122065 if( yypParser->yyidx>yypParser->yyidxMax ){
122066 yypParser->yyidxMax = yypParser->yyidx;
122068 #endif
122069 #if YYSTACKDEPTH>0
122070 if( yypParser->yyidx>=YYSTACKDEPTH ){
122071 yyStackOverflow(yypParser, yypMinor);
122072 return;
122074 #else
122075 if( yypParser->yyidx>=yypParser->yystksz ){
122076 yyGrowStack(yypParser);
122077 if( yypParser->yyidx>=yypParser->yystksz ){
122078 yyStackOverflow(yypParser, yypMinor);
122079 return;
122082 #endif
122083 yytos = &yypParser->yystack[yypParser->yyidx];
122084 yytos->stateno = (YYACTIONTYPE)yyNewState;
122085 yytos->major = (YYCODETYPE)yyMajor;
122086 yytos->minor = *yypMinor;
122087 #ifndef NDEBUG
122088 if( yyTraceFILE && yypParser->yyidx>0 ){
122089 int i;
122090 fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
122091 fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
122092 for(i=1; i<=yypParser->yyidx; i++)
122093 fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
122094 fprintf(yyTraceFILE,"\n");
122096 #endif
122099 /* The following table contains information about every rule that
122100 ** is used during the reduce.
122102 static const struct {
122103 YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
122104 unsigned char nrhs; /* Number of right-hand side symbols in the rule */
122105 } yyRuleInfo[] = {
122106 { 144, 1 },
122107 { 145, 2 },
122108 { 145, 1 },
122109 { 146, 1 },
122110 { 146, 3 },
122111 { 147, 0 },
122112 { 147, 1 },
122113 { 147, 3 },
122114 { 148, 1 },
122115 { 149, 3 },
122116 { 151, 0 },
122117 { 151, 1 },
122118 { 151, 2 },
122119 { 150, 0 },
122120 { 150, 1 },
122121 { 150, 1 },
122122 { 150, 1 },
122123 { 149, 2 },
122124 { 149, 2 },
122125 { 149, 2 },
122126 { 153, 1 },
122127 { 153, 0 },
122128 { 149, 2 },
122129 { 149, 3 },
122130 { 149, 5 },
122131 { 149, 2 },
122132 { 154, 6 },
122133 { 156, 1 },
122134 { 158, 0 },
122135 { 158, 3 },
122136 { 157, 1 },
122137 { 157, 0 },
122138 { 155, 5 },
122139 { 155, 2 },
122140 { 162, 0 },
122141 { 162, 2 },
122142 { 160, 3 },
122143 { 160, 1 },
122144 { 164, 3 },
122145 { 165, 1 },
122146 { 152, 1 },
122147 { 152, 1 },
122148 { 152, 1 },
122149 { 166, 0 },
122150 { 166, 1 },
122151 { 168, 1 },
122152 { 168, 4 },
122153 { 168, 6 },
122154 { 169, 1 },
122155 { 169, 2 },
122156 { 170, 1 },
122157 { 170, 1 },
122158 { 167, 2 },
122159 { 167, 0 },
122160 { 173, 2 },
122161 { 173, 2 },
122162 { 173, 4 },
122163 { 173, 3 },
122164 { 173, 3 },
122165 { 173, 2 },
122166 { 173, 2 },
122167 { 173, 3 },
122168 { 173, 5 },
122169 { 173, 2 },
122170 { 173, 4 },
122171 { 173, 4 },
122172 { 173, 1 },
122173 { 173, 2 },
122174 { 178, 0 },
122175 { 178, 1 },
122176 { 180, 0 },
122177 { 180, 2 },
122178 { 182, 2 },
122179 { 182, 3 },
122180 { 182, 3 },
122181 { 182, 3 },
122182 { 183, 2 },
122183 { 183, 2 },
122184 { 183, 1 },
122185 { 183, 1 },
122186 { 183, 2 },
122187 { 181, 3 },
122188 { 181, 2 },
122189 { 184, 0 },
122190 { 184, 2 },
122191 { 184, 2 },
122192 { 161, 0 },
122193 { 161, 2 },
122194 { 185, 3 },
122195 { 185, 1 },
122196 { 186, 1 },
122197 { 186, 0 },
122198 { 187, 2 },
122199 { 187, 7 },
122200 { 187, 5 },
122201 { 187, 5 },
122202 { 187, 10 },
122203 { 189, 0 },
122204 { 189, 1 },
122205 { 176, 0 },
122206 { 176, 3 },
122207 { 190, 0 },
122208 { 190, 2 },
122209 { 191, 1 },
122210 { 191, 1 },
122211 { 191, 1 },
122212 { 149, 4 },
122213 { 193, 2 },
122214 { 193, 0 },
122215 { 149, 8 },
122216 { 149, 4 },
122217 { 149, 1 },
122218 { 163, 2 },
122219 { 195, 1 },
122220 { 195, 3 },
122221 { 198, 1 },
122222 { 198, 2 },
122223 { 198, 1 },
122224 { 196, 9 },
122225 { 196, 1 },
122226 { 207, 4 },
122227 { 207, 5 },
122228 { 199, 1 },
122229 { 199, 1 },
122230 { 199, 0 },
122231 { 210, 2 },
122232 { 210, 0 },
122233 { 200, 3 },
122234 { 200, 2 },
122235 { 200, 4 },
122236 { 211, 2 },
122237 { 211, 1 },
122238 { 211, 0 },
122239 { 201, 0 },
122240 { 201, 2 },
122241 { 213, 2 },
122242 { 213, 0 },
122243 { 212, 7 },
122244 { 212, 7 },
122245 { 212, 7 },
122246 { 159, 0 },
122247 { 159, 2 },
122248 { 194, 2 },
122249 { 214, 1 },
122250 { 214, 2 },
122251 { 214, 3 },
122252 { 214, 4 },
122253 { 216, 2 },
122254 { 216, 0 },
122255 { 215, 0 },
122256 { 215, 3 },
122257 { 215, 2 },
122258 { 217, 4 },
122259 { 217, 0 },
122260 { 205, 0 },
122261 { 205, 3 },
122262 { 220, 4 },
122263 { 220, 2 },
122264 { 177, 1 },
122265 { 177, 1 },
122266 { 177, 0 },
122267 { 203, 0 },
122268 { 203, 3 },
122269 { 204, 0 },
122270 { 204, 2 },
122271 { 206, 0 },
122272 { 206, 2 },
122273 { 206, 4 },
122274 { 206, 4 },
122275 { 149, 6 },
122276 { 202, 0 },
122277 { 202, 2 },
122278 { 149, 8 },
122279 { 221, 5 },
122280 { 221, 3 },
122281 { 149, 6 },
122282 { 149, 7 },
122283 { 222, 2 },
122284 { 222, 1 },
122285 { 223, 0 },
122286 { 223, 3 },
122287 { 219, 3 },
122288 { 219, 1 },
122289 { 175, 1 },
122290 { 175, 3 },
122291 { 174, 1 },
122292 { 175, 1 },
122293 { 175, 1 },
122294 { 175, 3 },
122295 { 175, 5 },
122296 { 174, 1 },
122297 { 174, 1 },
122298 { 175, 1 },
122299 { 175, 3 },
122300 { 175, 6 },
122301 { 175, 5 },
122302 { 175, 4 },
122303 { 174, 1 },
122304 { 175, 3 },
122305 { 175, 3 },
122306 { 175, 3 },
122307 { 175, 3 },
122308 { 175, 3 },
122309 { 175, 3 },
122310 { 175, 3 },
122311 { 175, 3 },
122312 { 224, 1 },
122313 { 224, 2 },
122314 { 175, 3 },
122315 { 175, 5 },
122316 { 175, 2 },
122317 { 175, 3 },
122318 { 175, 3 },
122319 { 175, 4 },
122320 { 175, 2 },
122321 { 175, 2 },
122322 { 175, 2 },
122323 { 175, 2 },
122324 { 225, 1 },
122325 { 225, 2 },
122326 { 175, 5 },
122327 { 226, 1 },
122328 { 226, 2 },
122329 { 175, 5 },
122330 { 175, 3 },
122331 { 175, 5 },
122332 { 175, 4 },
122333 { 175, 4 },
122334 { 175, 5 },
122335 { 228, 5 },
122336 { 228, 4 },
122337 { 229, 2 },
122338 { 229, 0 },
122339 { 227, 1 },
122340 { 227, 0 },
122341 { 209, 1 },
122342 { 209, 0 },
122343 { 208, 3 },
122344 { 208, 1 },
122345 { 149, 12 },
122346 { 230, 1 },
122347 { 230, 0 },
122348 { 179, 0 },
122349 { 179, 3 },
122350 { 188, 5 },
122351 { 188, 3 },
122352 { 231, 0 },
122353 { 231, 2 },
122354 { 149, 4 },
122355 { 149, 1 },
122356 { 149, 2 },
122357 { 149, 3 },
122358 { 149, 5 },
122359 { 149, 6 },
122360 { 149, 5 },
122361 { 149, 6 },
122362 { 232, 1 },
122363 { 232, 1 },
122364 { 232, 1 },
122365 { 232, 1 },
122366 { 232, 1 },
122367 { 171, 2 },
122368 { 171, 1 },
122369 { 172, 2 },
122370 { 149, 5 },
122371 { 233, 11 },
122372 { 235, 1 },
122373 { 235, 1 },
122374 { 235, 2 },
122375 { 235, 0 },
122376 { 236, 1 },
122377 { 236, 1 },
122378 { 236, 3 },
122379 { 237, 0 },
122380 { 237, 3 },
122381 { 238, 0 },
122382 { 238, 2 },
122383 { 234, 3 },
122384 { 234, 2 },
122385 { 240, 1 },
122386 { 240, 3 },
122387 { 241, 0 },
122388 { 241, 3 },
122389 { 241, 2 },
122390 { 239, 7 },
122391 { 239, 5 },
122392 { 239, 5 },
122393 { 239, 1 },
122394 { 175, 4 },
122395 { 175, 6 },
122396 { 192, 1 },
122397 { 192, 1 },
122398 { 192, 1 },
122399 { 149, 4 },
122400 { 149, 6 },
122401 { 149, 3 },
122402 { 243, 0 },
122403 { 243, 2 },
122404 { 242, 1 },
122405 { 242, 0 },
122406 { 149, 1 },
122407 { 149, 3 },
122408 { 149, 1 },
122409 { 149, 3 },
122410 { 149, 6 },
122411 { 149, 6 },
122412 { 244, 1 },
122413 { 245, 0 },
122414 { 245, 1 },
122415 { 149, 1 },
122416 { 149, 4 },
122417 { 246, 8 },
122418 { 247, 1 },
122419 { 247, 3 },
122420 { 248, 0 },
122421 { 248, 2 },
122422 { 249, 1 },
122423 { 249, 3 },
122424 { 250, 1 },
122425 { 251, 0 },
122426 { 251, 4 },
122427 { 251, 2 },
122428 { 197, 0 },
122429 { 197, 2 },
122430 { 197, 3 },
122431 { 252, 6 },
122432 { 252, 8 },
122435 static void yy_accept(yyParser*); /* Forward Declaration */
122438 ** Perform a reduce action and the shift that must immediately
122439 ** follow the reduce.
122441 static void yy_reduce(
122442 yyParser *yypParser, /* The parser */
122443 int yyruleno /* Number of the rule by which to reduce */
122445 int yygoto; /* The next state */
122446 int yyact; /* The next action */
122447 YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
122448 yyStackEntry *yymsp; /* The top of the parser's stack */
122449 int yysize; /* Amount to pop the stack */
122450 sqlite3ParserARG_FETCH;
122451 yymsp = &yypParser->yystack[yypParser->yyidx];
122452 #ifndef NDEBUG
122453 if( yyTraceFILE && yyruleno>=0
122454 && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
122455 fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
122456 yyRuleName[yyruleno]);
122458 #endif /* NDEBUG */
122460 /* Silence complaints from purify about yygotominor being uninitialized
122461 ** in some cases when it is copied into the stack after the following
122462 ** switch. yygotominor is uninitialized when a rule reduces that does
122463 ** not set the value of its left-hand side nonterminal. Leaving the
122464 ** value of the nonterminal uninitialized is utterly harmless as long
122465 ** as the value is never used. So really the only thing this code
122466 ** accomplishes is to quieten purify.
122468 ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
122469 ** without this code, their parser segfaults. I'm not sure what there
122470 ** parser is doing to make this happen. This is the second bug report
122471 ** from wireshark this week. Clearly they are stressing Lemon in ways
122472 ** that it has not been previously stressed... (SQLite ticket #2172)
122474 /*memset(&yygotominor, 0, sizeof(yygotominor));*/
122475 yygotominor = yyzerominor;
122478 switch( yyruleno ){
122479 /* Beginning here are the reduction cases. A typical example
122480 ** follows:
122481 ** case 0:
122482 ** #line <lineno> <grammarfile>
122483 ** { ... } // User supplied code
122484 ** #line <lineno> <thisfile>
122485 ** break;
122487 case 5: /* explain ::= */
122488 { sqlite3BeginParse(pParse, 0); }
122489 break;
122490 case 6: /* explain ::= EXPLAIN */
122491 { sqlite3BeginParse(pParse, 1); }
122492 break;
122493 case 7: /* explain ::= EXPLAIN QUERY PLAN */
122494 { sqlite3BeginParse(pParse, 2); }
122495 break;
122496 case 8: /* cmdx ::= cmd */
122497 { sqlite3FinishCoding(pParse); }
122498 break;
122499 case 9: /* cmd ::= BEGIN transtype trans_opt */
122500 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
122501 break;
122502 case 13: /* transtype ::= */
122503 {yygotominor.yy328 = TK_DEFERRED;}
122504 break;
122505 case 14: /* transtype ::= DEFERRED */
122506 case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
122507 case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
122508 case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
122509 case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
122510 {yygotominor.yy328 = yymsp[0].major;}
122511 break;
122512 case 17: /* cmd ::= COMMIT trans_opt */
122513 case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
122514 {sqlite3CommitTransaction(pParse);}
122515 break;
122516 case 19: /* cmd ::= ROLLBACK trans_opt */
122517 {sqlite3RollbackTransaction(pParse);}
122518 break;
122519 case 22: /* cmd ::= SAVEPOINT nm */
122521 sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
122523 break;
122524 case 23: /* cmd ::= RELEASE savepoint_opt nm */
122526 sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
122528 break;
122529 case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
122531 sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
122533 break;
122534 case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
122536 sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
122538 break;
122539 case 27: /* createkw ::= CREATE */
122541 pParse->db->lookaside.bEnabled = 0;
122542 yygotominor.yy0 = yymsp[0].minor.yy0;
122544 break;
122545 case 28: /* ifnotexists ::= */
122546 case 31: /* temp ::= */ yytestcase(yyruleno==31);
122547 case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
122548 case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
122549 case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
122550 case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
122551 case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
122552 case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
122553 case 218: /* between_op ::= BETWEEN */ yytestcase(yyruleno==218);
122554 case 221: /* in_op ::= IN */ yytestcase(yyruleno==221);
122555 {yygotominor.yy328 = 0;}
122556 break;
122557 case 29: /* ifnotexists ::= IF NOT EXISTS */
122558 case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
122559 case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
122560 case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
122561 case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
122562 case 219: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==219);
122563 case 222: /* in_op ::= NOT IN */ yytestcase(yyruleno==222);
122564 {yygotominor.yy328 = 1;}
122565 break;
122566 case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
122568 sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy186,0);
122570 break;
122571 case 33: /* create_table_args ::= AS select */
122573 sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy3);
122574 sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
122576 break;
122577 case 34: /* table_options ::= */
122578 {yygotominor.yy186 = 0;}
122579 break;
122580 case 35: /* table_options ::= WITHOUT nm */
122582 if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
122583 yygotominor.yy186 = TF_WithoutRowid;
122584 }else{
122585 yygotominor.yy186 = 0;
122586 sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
122589 break;
122590 case 38: /* column ::= columnid type carglist */
122592 yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
122593 yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
122595 break;
122596 case 39: /* columnid ::= nm */
122598 sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
122599 yygotominor.yy0 = yymsp[0].minor.yy0;
122600 pParse->constraintName.n = 0;
122602 break;
122603 case 40: /* nm ::= ID|INDEXED */
122604 case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
122605 case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
122606 case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
122607 case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
122608 case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
122609 case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
122610 case 141: /* dbnm ::= DOT nm */ yytestcase(yyruleno==141);
122611 case 150: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==150);
122612 case 247: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==247);
122613 case 256: /* nmnum ::= plus_num */ yytestcase(yyruleno==256);
122614 case 257: /* nmnum ::= nm */ yytestcase(yyruleno==257);
122615 case 258: /* nmnum ::= ON */ yytestcase(yyruleno==258);
122616 case 259: /* nmnum ::= DELETE */ yytestcase(yyruleno==259);
122617 case 260: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==260);
122618 case 261: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==261);
122619 case 262: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==262);
122620 case 263: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==263);
122621 case 279: /* trnm ::= nm */ yytestcase(yyruleno==279);
122622 {yygotominor.yy0 = yymsp[0].minor.yy0;}
122623 break;
122624 case 44: /* type ::= typetoken */
122625 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
122626 break;
122627 case 46: /* typetoken ::= typename LP signed RP */
122629 yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
122630 yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
122632 break;
122633 case 47: /* typetoken ::= typename LP signed COMMA signed RP */
122635 yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
122636 yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
122638 break;
122639 case 49: /* typename ::= typename ID|STRING */
122640 {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);}
122641 break;
122642 case 54: /* ccons ::= CONSTRAINT nm */
122643 case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
122644 {pParse->constraintName = yymsp[0].minor.yy0;}
122645 break;
122646 case 55: /* ccons ::= DEFAULT term */
122647 case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
122648 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
122649 break;
122650 case 56: /* ccons ::= DEFAULT LP expr RP */
122651 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
122652 break;
122653 case 58: /* ccons ::= DEFAULT MINUS term */
122655 ExprSpan v;
122656 v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
122657 v.zStart = yymsp[-1].minor.yy0.z;
122658 v.zEnd = yymsp[0].minor.yy346.zEnd;
122659 sqlite3AddDefaultValue(pParse,&v);
122661 break;
122662 case 59: /* ccons ::= DEFAULT ID|INDEXED */
122664 ExprSpan v;
122665 spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
122666 sqlite3AddDefaultValue(pParse,&v);
122668 break;
122669 case 61: /* ccons ::= NOT NULL onconf */
122670 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
122671 break;
122672 case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
122673 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
122674 break;
122675 case 63: /* ccons ::= UNIQUE onconf */
122676 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
122677 break;
122678 case 64: /* ccons ::= CHECK LP expr RP */
122679 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
122680 break;
122681 case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
122682 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
122683 break;
122684 case 66: /* ccons ::= defer_subclause */
122685 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
122686 break;
122687 case 67: /* ccons ::= COLLATE ID|STRING */
122688 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
122689 break;
122690 case 70: /* refargs ::= */
122691 { yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
122692 break;
122693 case 71: /* refargs ::= refargs refarg */
122694 { yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
122695 break;
122696 case 72: /* refarg ::= MATCH nm */
122697 case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
122698 { yygotominor.yy429.value = 0; yygotominor.yy429.mask = 0x000000; }
122699 break;
122700 case 74: /* refarg ::= ON DELETE refact */
122701 { yygotominor.yy429.value = yymsp[0].minor.yy328; yygotominor.yy429.mask = 0x0000ff; }
122702 break;
122703 case 75: /* refarg ::= ON UPDATE refact */
122704 { yygotominor.yy429.value = yymsp[0].minor.yy328<<8; yygotominor.yy429.mask = 0x00ff00; }
122705 break;
122706 case 76: /* refact ::= SET NULL */
122707 { yygotominor.yy328 = OE_SetNull; /* EV: R-33326-45252 */}
122708 break;
122709 case 77: /* refact ::= SET DEFAULT */
122710 { yygotominor.yy328 = OE_SetDflt; /* EV: R-33326-45252 */}
122711 break;
122712 case 78: /* refact ::= CASCADE */
122713 { yygotominor.yy328 = OE_Cascade; /* EV: R-33326-45252 */}
122714 break;
122715 case 79: /* refact ::= RESTRICT */
122716 { yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
122717 break;
122718 case 80: /* refact ::= NO ACTION */
122719 { yygotominor.yy328 = OE_None; /* EV: R-33326-45252 */}
122720 break;
122721 case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
122722 case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
122723 case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
122724 case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
122725 {yygotominor.yy328 = yymsp[0].minor.yy328;}
122726 break;
122727 case 86: /* conslist_opt ::= */
122728 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
122729 break;
122730 case 87: /* conslist_opt ::= COMMA conslist */
122731 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
122732 break;
122733 case 90: /* tconscomma ::= COMMA */
122734 {pParse->constraintName.n = 0;}
122735 break;
122736 case 93: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
122737 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
122738 break;
122739 case 94: /* tcons ::= UNIQUE LP idxlist RP onconf */
122740 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
122741 break;
122742 case 95: /* tcons ::= CHECK LP expr RP onconf */
122743 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
122744 break;
122745 case 96: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
122747 sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
122748 sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
122750 break;
122751 case 99: /* onconf ::= */
122752 {yygotominor.yy328 = OE_Default;}
122753 break;
122754 case 101: /* orconf ::= */
122755 {yygotominor.yy186 = OE_Default;}
122756 break;
122757 case 102: /* orconf ::= OR resolvetype */
122758 {yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
122759 break;
122760 case 104: /* resolvetype ::= IGNORE */
122761 {yygotominor.yy328 = OE_Ignore;}
122762 break;
122763 case 105: /* resolvetype ::= REPLACE */
122764 {yygotominor.yy328 = OE_Replace;}
122765 break;
122766 case 106: /* cmd ::= DROP TABLE ifexists fullname */
122768 sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
122770 break;
122771 case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
122773 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);
122775 break;
122776 case 110: /* cmd ::= DROP VIEW ifexists fullname */
122778 sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
122780 break;
122781 case 111: /* cmd ::= select */
122783 SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
122784 sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
122785 sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
122787 break;
122788 case 112: /* select ::= with selectnowith */
122790 Select *p = yymsp[0].minor.yy3, *pNext, *pLoop;
122791 if( p ){
122792 int cnt = 0, mxSelect;
122793 p->pWith = yymsp[-1].minor.yy59;
122794 if( p->pPrior ){
122795 pNext = 0;
122796 for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
122797 pLoop->pNext = pNext;
122798 pLoop->selFlags |= SF_Compound;
122800 mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
122801 if( mxSelect && cnt>mxSelect ){
122802 sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
122805 }else{
122806 sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
122808 yygotominor.yy3 = p;
122810 break;
122811 case 113: /* selectnowith ::= oneselect */
122812 case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
122813 {yygotominor.yy3 = yymsp[0].minor.yy3;}
122814 break;
122815 case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
122817 Select *pRhs = yymsp[0].minor.yy3;
122818 if( pRhs && pRhs->pPrior ){
122819 SrcList *pFrom;
122820 Token x;
122821 x.n = 0;
122822 pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
122823 pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
122825 if( pRhs ){
122826 pRhs->op = (u8)yymsp[-1].minor.yy328;
122827 pRhs->pPrior = yymsp[-2].minor.yy3;
122828 if( yymsp[-1].minor.yy328!=TK_ALL ) pParse->hasCompound = 1;
122829 }else{
122830 sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
122832 yygotominor.yy3 = pRhs;
122834 break;
122835 case 116: /* multiselect_op ::= UNION ALL */
122836 {yygotominor.yy328 = TK_ALL;}
122837 break;
122838 case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
122840 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);
122841 #if SELECTTRACE_ENABLED
122842 /* Populate the Select.zSelName[] string that is used to help with
122843 ** query planner debugging, to differentiate between multiple Select
122844 ** objects in a complex query.
122846 ** If the SELECT keyword is immediately followed by a C-style comment
122847 ** then extract the first few alphanumeric characters from within that
122848 ** comment to be the zSelName value. Otherwise, the label is #N where
122849 ** is an integer that is incremented with each SELECT statement seen.
122851 if( yygotominor.yy3!=0 ){
122852 const char *z = yymsp[-8].minor.yy0.z+6;
122853 int i;
122854 sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "#%d",
122855 ++pParse->nSelect);
122856 while( z[0]==' ' ) z++;
122857 if( z[0]=='/' && z[1]=='*' ){
122858 z += 2;
122859 while( z[0]==' ' ) z++;
122860 for(i=0; sqlite3Isalnum(z[i]); i++){}
122861 sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "%.*s", i, z);
122864 #endif /* SELECTRACE_ENABLED */
122866 break;
122867 case 120: /* values ::= VALUES LP nexprlist RP */
122869 yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
122871 break;
122872 case 121: /* values ::= values COMMA LP exprlist RP */
122874 Select *pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
122875 if( pRight ){
122876 pRight->op = TK_ALL;
122877 pRight->pPrior = yymsp[-4].minor.yy3;
122878 yygotominor.yy3 = pRight;
122879 }else{
122880 yygotominor.yy3 = yymsp[-4].minor.yy3;
122883 break;
122884 case 122: /* distinct ::= DISTINCT */
122885 {yygotominor.yy381 = SF_Distinct;}
122886 break;
122887 case 123: /* distinct ::= ALL */
122888 case 124: /* distinct ::= */ yytestcase(yyruleno==124);
122889 {yygotominor.yy381 = 0;}
122890 break;
122891 case 125: /* sclp ::= selcollist COMMA */
122892 case 243: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==243);
122893 {yygotominor.yy14 = yymsp[-1].minor.yy14;}
122894 break;
122895 case 126: /* sclp ::= */
122896 case 154: /* orderby_opt ::= */ yytestcase(yyruleno==154);
122897 case 161: /* groupby_opt ::= */ yytestcase(yyruleno==161);
122898 case 236: /* exprlist ::= */ yytestcase(yyruleno==236);
122899 case 242: /* idxlist_opt ::= */ yytestcase(yyruleno==242);
122900 {yygotominor.yy14 = 0;}
122901 break;
122902 case 127: /* selcollist ::= sclp expr as */
122904 yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
122905 if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
122906 sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
122908 break;
122909 case 128: /* selcollist ::= sclp STAR */
122911 Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
122912 yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
122914 break;
122915 case 129: /* selcollist ::= sclp nm DOT STAR */
122917 Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
122918 Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
122919 Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
122920 yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
122922 break;
122923 case 132: /* as ::= */
122924 {yygotominor.yy0.n = 0;}
122925 break;
122926 case 133: /* from ::= */
122927 {yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
122928 break;
122929 case 134: /* from ::= FROM seltablist */
122931 yygotominor.yy65 = yymsp[0].minor.yy65;
122932 sqlite3SrcListShiftJoinType(yygotominor.yy65);
122934 break;
122935 case 135: /* stl_prefix ::= seltablist joinop */
122937 yygotominor.yy65 = yymsp[-1].minor.yy65;
122938 if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
122940 break;
122941 case 136: /* stl_prefix ::= */
122942 {yygotominor.yy65 = 0;}
122943 break;
122944 case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
122946 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);
122947 sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
122949 break;
122950 case 138: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
122952 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);
122954 break;
122955 case 139: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
122957 if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
122958 yygotominor.yy65 = yymsp[-4].minor.yy65;
122959 }else if( yymsp[-4].minor.yy65->nSrc==1 ){
122960 yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
122961 if( yygotominor.yy65 ){
122962 struct SrcList_item *pNew = &yygotominor.yy65->a[yygotominor.yy65->nSrc-1];
122963 struct SrcList_item *pOld = yymsp[-4].minor.yy65->a;
122964 pNew->zName = pOld->zName;
122965 pNew->zDatabase = pOld->zDatabase;
122966 pNew->pSelect = pOld->pSelect;
122967 pOld->zName = pOld->zDatabase = 0;
122968 pOld->pSelect = 0;
122970 sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy65);
122971 }else{
122972 Select *pSubquery;
122973 sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
122974 pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,SF_NestedFrom,0,0);
122975 yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
122978 break;
122979 case 140: /* dbnm ::= */
122980 case 149: /* indexed_opt ::= */ yytestcase(yyruleno==149);
122981 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
122982 break;
122983 case 142: /* fullname ::= nm dbnm */
122984 {yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
122985 break;
122986 case 143: /* joinop ::= COMMA|JOIN */
122987 { yygotominor.yy328 = JT_INNER; }
122988 break;
122989 case 144: /* joinop ::= JOIN_KW JOIN */
122990 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
122991 break;
122992 case 145: /* joinop ::= JOIN_KW nm JOIN */
122993 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
122994 break;
122995 case 146: /* joinop ::= JOIN_KW nm nm JOIN */
122996 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
122997 break;
122998 case 147: /* on_opt ::= ON expr */
122999 case 164: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==164);
123000 case 171: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==171);
123001 case 231: /* case_else ::= ELSE expr */ yytestcase(yyruleno==231);
123002 case 233: /* case_operand ::= expr */ yytestcase(yyruleno==233);
123003 {yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
123004 break;
123005 case 148: /* on_opt ::= */
123006 case 163: /* having_opt ::= */ yytestcase(yyruleno==163);
123007 case 170: /* where_opt ::= */ yytestcase(yyruleno==170);
123008 case 232: /* case_else ::= */ yytestcase(yyruleno==232);
123009 case 234: /* case_operand ::= */ yytestcase(yyruleno==234);
123010 {yygotominor.yy132 = 0;}
123011 break;
123012 case 151: /* indexed_opt ::= NOT INDEXED */
123013 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
123014 break;
123015 case 152: /* using_opt ::= USING LP idlist RP */
123016 case 180: /* inscollist_opt ::= LP idlist RP */ yytestcase(yyruleno==180);
123017 {yygotominor.yy408 = yymsp[-1].minor.yy408;}
123018 break;
123019 case 153: /* using_opt ::= */
123020 case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
123021 {yygotominor.yy408 = 0;}
123022 break;
123023 case 155: /* orderby_opt ::= ORDER BY sortlist */
123024 case 162: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==162);
123025 case 235: /* exprlist ::= nexprlist */ yytestcase(yyruleno==235);
123026 {yygotominor.yy14 = yymsp[0].minor.yy14;}
123027 break;
123028 case 156: /* sortlist ::= sortlist COMMA expr sortorder */
123030 yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy346.pExpr);
123031 if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
123033 break;
123034 case 157: /* sortlist ::= expr sortorder */
123036 yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy346.pExpr);
123037 if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
123039 break;
123040 case 158: /* sortorder ::= ASC */
123041 case 160: /* sortorder ::= */ yytestcase(yyruleno==160);
123042 {yygotominor.yy328 = SQLITE_SO_ASC;}
123043 break;
123044 case 159: /* sortorder ::= DESC */
123045 {yygotominor.yy328 = SQLITE_SO_DESC;}
123046 break;
123047 case 165: /* limit_opt ::= */
123048 {yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
123049 break;
123050 case 166: /* limit_opt ::= LIMIT expr */
123051 {yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
123052 break;
123053 case 167: /* limit_opt ::= LIMIT expr OFFSET expr */
123054 {yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
123055 break;
123056 case 168: /* limit_opt ::= LIMIT expr COMMA expr */
123057 {yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
123058 break;
123059 case 169: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
123061 sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
123062 sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
123063 sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
123065 break;
123066 case 172: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
123068 sqlite3WithPush(pParse, yymsp[-7].minor.yy59, 1);
123069 sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
123070 sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
123071 sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
123073 break;
123074 case 173: /* setlist ::= setlist COMMA nm EQ expr */
123076 yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
123077 sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
123079 break;
123080 case 174: /* setlist ::= nm EQ expr */
123082 yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
123083 sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
123085 break;
123086 case 175: /* cmd ::= with insert_cmd INTO fullname inscollist_opt select */
123088 sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
123089 sqlite3Insert(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);
123091 break;
123092 case 176: /* cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
123094 sqlite3WithPush(pParse, yymsp[-6].minor.yy59, 1);
123095 sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);
123097 break;
123098 case 177: /* insert_cmd ::= INSERT orconf */
123099 {yygotominor.yy186 = yymsp[0].minor.yy186;}
123100 break;
123101 case 178: /* insert_cmd ::= REPLACE */
123102 {yygotominor.yy186 = OE_Replace;}
123103 break;
123104 case 181: /* idlist ::= idlist COMMA nm */
123105 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
123106 break;
123107 case 182: /* idlist ::= nm */
123108 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
123109 break;
123110 case 183: /* expr ::= term */
123111 {yygotominor.yy346 = yymsp[0].minor.yy346;}
123112 break;
123113 case 184: /* expr ::= LP expr RP */
123114 {yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
123115 break;
123116 case 185: /* term ::= NULL */
123117 case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
123118 case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
123119 {spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
123120 break;
123121 case 186: /* expr ::= ID|INDEXED */
123122 case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
123123 {spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
123124 break;
123125 case 188: /* expr ::= nm DOT nm */
123127 Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
123128 Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
123129 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
123130 spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
123132 break;
123133 case 189: /* expr ::= nm DOT nm DOT nm */
123135 Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
123136 Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
123137 Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
123138 Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
123139 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
123140 spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
123142 break;
123143 case 192: /* expr ::= VARIABLE */
123145 if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
123146 /* When doing a nested parse, one can include terms in an expression
123147 ** that look like this: #1 #2 ... These terms refer to registers
123148 ** in the virtual machine. #N is the N-th register. */
123149 if( pParse->nested==0 ){
123150 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
123151 yygotominor.yy346.pExpr = 0;
123152 }else{
123153 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
123154 if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
123156 }else{
123157 spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
123158 sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
123160 spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
123162 break;
123163 case 193: /* expr ::= expr COLLATE ID|STRING */
123165 yygotominor.yy346.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0, 1);
123166 yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
123167 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123169 break;
123170 case 194: /* expr ::= CAST LP expr AS typetoken RP */
123172 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
123173 spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
123175 break;
123176 case 195: /* expr ::= ID|INDEXED LP distinct exprlist RP */
123178 if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
123179 sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
123181 yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
123182 spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
123183 if( yymsp[-2].minor.yy381 && yygotominor.yy346.pExpr ){
123184 yygotominor.yy346.pExpr->flags |= EP_Distinct;
123187 break;
123188 case 196: /* expr ::= ID|INDEXED LP STAR RP */
123190 yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
123191 spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
123193 break;
123194 case 197: /* term ::= CTIME_KW */
123196 yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
123197 spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
123199 break;
123200 case 198: /* expr ::= expr AND expr */
123201 case 199: /* expr ::= expr OR expr */ yytestcase(yyruleno==199);
123202 case 200: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==200);
123203 case 201: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==201);
123204 case 202: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==202);
123205 case 203: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==203);
123206 case 204: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==204);
123207 case 205: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==205);
123208 {spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
123209 break;
123210 case 206: /* likeop ::= LIKE_KW|MATCH */
123211 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 0;}
123212 break;
123213 case 207: /* likeop ::= NOT LIKE_KW|MATCH */
123214 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 1;}
123215 break;
123216 case 208: /* expr ::= expr likeop expr */
123218 ExprList *pList;
123219 pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy346.pExpr);
123220 pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy346.pExpr);
123221 yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy96.eOperator);
123222 if( yymsp[-1].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
123223 yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
123224 yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
123225 if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
123227 break;
123228 case 209: /* expr ::= expr likeop expr ESCAPE expr */
123230 ExprList *pList;
123231 pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
123232 pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy346.pExpr);
123233 pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
123234 yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy96.eOperator);
123235 if( yymsp[-3].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
123236 yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
123237 yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
123238 if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
123240 break;
123241 case 210: /* expr ::= expr ISNULL|NOTNULL */
123242 {spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
123243 break;
123244 case 211: /* expr ::= expr NOT NULL */
123245 {spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
123246 break;
123247 case 212: /* expr ::= expr IS expr */
123249 spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
123250 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
123252 break;
123253 case 213: /* expr ::= expr IS NOT expr */
123255 spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
123256 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
123258 break;
123259 case 214: /* expr ::= NOT expr */
123260 case 215: /* expr ::= BITNOT expr */ yytestcase(yyruleno==215);
123261 {spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
123262 break;
123263 case 216: /* expr ::= MINUS expr */
123264 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
123265 break;
123266 case 217: /* expr ::= PLUS expr */
123267 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
123268 break;
123269 case 220: /* expr ::= expr between_op expr AND expr */
123271 ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
123272 pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
123273 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
123274 if( yygotominor.yy346.pExpr ){
123275 yygotominor.yy346.pExpr->x.pList = pList;
123276 }else{
123277 sqlite3ExprListDelete(pParse->db, pList);
123279 if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
123280 yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
123281 yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
123283 break;
123284 case 223: /* expr ::= expr in_op LP exprlist RP */
123286 if( yymsp[-1].minor.yy14==0 ){
123287 /* Expressions of the form
123289 ** expr1 IN ()
123290 ** expr1 NOT IN ()
123292 ** simplify to constants 0 (false) and 1 (true), respectively,
123293 ** regardless of the value of expr1.
123295 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy328]);
123296 sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy346.pExpr);
123297 }else if( yymsp[-1].minor.yy14->nExpr==1 ){
123298 /* Expressions of the form:
123300 ** expr1 IN (?1)
123301 ** expr1 NOT IN (?2)
123303 ** with exactly one value on the RHS can be simplified to something
123304 ** like this:
123306 ** expr1 == ?1
123307 ** expr1 <> ?2
123309 ** But, the RHS of the == or <> is marked with the EP_Generic flag
123310 ** so that it may not contribute to the computation of comparison
123311 ** affinity or the collating sequence to use for comparison. Otherwise,
123312 ** the semantics would be subtly different from IN or NOT IN.
123314 Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
123315 yymsp[-1].minor.yy14->a[0].pExpr = 0;
123316 sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
123317 /* pRHS cannot be NULL because a malloc error would have been detected
123318 ** before now and control would have never reached this point */
123319 if( ALWAYS(pRHS) ){
123320 pRHS->flags &= ~EP_Collate;
123321 pRHS->flags |= EP_Generic;
123323 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy328 ? TK_NE : TK_EQ, yymsp[-4].minor.yy346.pExpr, pRHS, 0);
123324 }else{
123325 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
123326 if( yygotominor.yy346.pExpr ){
123327 yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
123328 sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
123329 }else{
123330 sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
123332 if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
123334 yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
123335 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123337 break;
123338 case 224: /* expr ::= LP select RP */
123340 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
123341 if( yygotominor.yy346.pExpr ){
123342 yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
123343 ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
123344 sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
123345 }else{
123346 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
123348 yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
123349 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123351 break;
123352 case 225: /* expr ::= expr in_op LP select RP */
123354 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
123355 if( yygotominor.yy346.pExpr ){
123356 yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
123357 ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
123358 sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
123359 }else{
123360 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
123362 if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
123363 yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
123364 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123366 break;
123367 case 226: /* expr ::= expr in_op nm dbnm */
123369 SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
123370 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
123371 if( yygotominor.yy346.pExpr ){
123372 yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
123373 ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
123374 sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
123375 }else{
123376 sqlite3SrcListDelete(pParse->db, pSrc);
123378 if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
123379 yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
123380 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];
123382 break;
123383 case 227: /* expr ::= EXISTS LP select RP */
123385 Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
123386 if( p ){
123387 p->x.pSelect = yymsp[-1].minor.yy3;
123388 ExprSetProperty(p, EP_xIsSelect);
123389 sqlite3ExprSetHeight(pParse, p);
123390 }else{
123391 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
123393 yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
123394 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123396 break;
123397 case 228: /* expr ::= CASE case_operand case_exprlist case_else END */
123399 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, 0, 0);
123400 if( yygotominor.yy346.pExpr ){
123401 yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy132 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy132) : yymsp[-2].minor.yy14;
123402 sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
123403 }else{
123404 sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
123405 sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy132);
123407 yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
123408 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123410 break;
123411 case 229: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
123413 yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
123414 yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
123416 break;
123417 case 230: /* case_exprlist ::= WHEN expr THEN expr */
123419 yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
123420 yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
123422 break;
123423 case 237: /* nexprlist ::= nexprlist COMMA expr */
123424 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
123425 break;
123426 case 238: /* nexprlist ::= expr */
123427 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
123428 break;
123429 case 239: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
123431 sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
123432 sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy328,
123433 &yymsp[-11].minor.yy0, yymsp[0].minor.yy132, SQLITE_SO_ASC, yymsp[-8].minor.yy328);
123435 break;
123436 case 240: /* uniqueflag ::= UNIQUE */
123437 case 291: /* raisetype ::= ABORT */ yytestcase(yyruleno==291);
123438 {yygotominor.yy328 = OE_Abort;}
123439 break;
123440 case 241: /* uniqueflag ::= */
123441 {yygotominor.yy328 = OE_None;}
123442 break;
123443 case 244: /* idxlist ::= idxlist COMMA nm collate sortorder */
123445 Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0, 1);
123446 yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
123447 sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
123448 sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
123449 if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
123451 break;
123452 case 245: /* idxlist ::= nm collate sortorder */
123454 Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0, 1);
123455 yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
123456 sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
123457 sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
123458 if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
123460 break;
123461 case 246: /* collate ::= */
123462 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
123463 break;
123464 case 248: /* cmd ::= DROP INDEX ifexists fullname */
123465 {sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
123466 break;
123467 case 249: /* cmd ::= VACUUM */
123468 case 250: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==250);
123469 {sqlite3Vacuum(pParse);}
123470 break;
123471 case 251: /* cmd ::= PRAGMA nm dbnm */
123472 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
123473 break;
123474 case 252: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
123475 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
123476 break;
123477 case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
123478 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
123479 break;
123480 case 254: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
123481 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
123482 break;
123483 case 255: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
123484 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
123485 break;
123486 case 264: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
123488 Token all;
123489 all.z = yymsp[-3].minor.yy0.z;
123490 all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
123491 sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
123493 break;
123494 case 265: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
123496 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);
123497 yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
123499 break;
123500 case 266: /* trigger_time ::= BEFORE */
123501 case 269: /* trigger_time ::= */ yytestcase(yyruleno==269);
123502 { yygotominor.yy328 = TK_BEFORE; }
123503 break;
123504 case 267: /* trigger_time ::= AFTER */
123505 { yygotominor.yy328 = TK_AFTER; }
123506 break;
123507 case 268: /* trigger_time ::= INSTEAD OF */
123508 { yygotominor.yy328 = TK_INSTEAD;}
123509 break;
123510 case 270: /* trigger_event ::= DELETE|INSERT */
123511 case 271: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==271);
123512 {yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
123513 break;
123514 case 272: /* trigger_event ::= UPDATE OF idlist */
123515 {yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
123516 break;
123517 case 275: /* when_clause ::= */
123518 case 296: /* key_opt ::= */ yytestcase(yyruleno==296);
123519 { yygotominor.yy132 = 0; }
123520 break;
123521 case 276: /* when_clause ::= WHEN expr */
123522 case 297: /* key_opt ::= KEY expr */ yytestcase(yyruleno==297);
123523 { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
123524 break;
123525 case 277: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
123527 assert( yymsp[-2].minor.yy473!=0 );
123528 yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
123529 yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
123530 yygotominor.yy473 = yymsp[-2].minor.yy473;
123532 break;
123533 case 278: /* trigger_cmd_list ::= trigger_cmd SEMI */
123535 assert( yymsp[-1].minor.yy473!=0 );
123536 yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
123537 yygotominor.yy473 = yymsp[-1].minor.yy473;
123539 break;
123540 case 280: /* trnm ::= nm DOT nm */
123542 yygotominor.yy0 = yymsp[0].minor.yy0;
123543 sqlite3ErrorMsg(pParse,
123544 "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
123545 "statements within triggers");
123547 break;
123548 case 282: /* tridxby ::= INDEXED BY nm */
123550 sqlite3ErrorMsg(pParse,
123551 "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
123552 "within triggers");
123554 break;
123555 case 283: /* tridxby ::= NOT INDEXED */
123557 sqlite3ErrorMsg(pParse,
123558 "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
123559 "within triggers");
123561 break;
123562 case 284: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
123563 { yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
123564 break;
123565 case 285: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
123566 {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
123567 break;
123568 case 286: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
123569 {yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
123570 break;
123571 case 287: /* trigger_cmd ::= select */
123572 {yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
123573 break;
123574 case 288: /* expr ::= RAISE LP IGNORE RP */
123576 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
123577 if( yygotominor.yy346.pExpr ){
123578 yygotominor.yy346.pExpr->affinity = OE_Ignore;
123580 yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
123581 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123583 break;
123584 case 289: /* expr ::= RAISE LP raisetype COMMA nm RP */
123586 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
123587 if( yygotominor.yy346.pExpr ) {
123588 yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
123590 yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
123591 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123593 break;
123594 case 290: /* raisetype ::= ROLLBACK */
123595 {yygotominor.yy328 = OE_Rollback;}
123596 break;
123597 case 292: /* raisetype ::= FAIL */
123598 {yygotominor.yy328 = OE_Fail;}
123599 break;
123600 case 293: /* cmd ::= DROP TRIGGER ifexists fullname */
123602 sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
123604 break;
123605 case 294: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
123607 sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
123609 break;
123610 case 295: /* cmd ::= DETACH database_kw_opt expr */
123612 sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
123614 break;
123615 case 300: /* cmd ::= REINDEX */
123616 {sqlite3Reindex(pParse, 0, 0);}
123617 break;
123618 case 301: /* cmd ::= REINDEX nm dbnm */
123619 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
123620 break;
123621 case 302: /* cmd ::= ANALYZE */
123622 {sqlite3Analyze(pParse, 0, 0);}
123623 break;
123624 case 303: /* cmd ::= ANALYZE nm dbnm */
123625 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
123626 break;
123627 case 304: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
123629 sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
123631 break;
123632 case 305: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
123634 sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
123636 break;
123637 case 306: /* add_column_fullname ::= fullname */
123639 pParse->db->lookaside.bEnabled = 0;
123640 sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
123642 break;
123643 case 309: /* cmd ::= create_vtab */
123644 {sqlite3VtabFinishParse(pParse,0);}
123645 break;
123646 case 310: /* cmd ::= create_vtab LP vtabarglist RP */
123647 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
123648 break;
123649 case 311: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
123651 sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy328);
123653 break;
123654 case 314: /* vtabarg ::= */
123655 {sqlite3VtabArgInit(pParse);}
123656 break;
123657 case 316: /* vtabargtoken ::= ANY */
123658 case 317: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==317);
123659 case 318: /* lp ::= LP */ yytestcase(yyruleno==318);
123660 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
123661 break;
123662 case 322: /* with ::= */
123663 {yygotominor.yy59 = 0;}
123664 break;
123665 case 323: /* with ::= WITH wqlist */
123666 case 324: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==324);
123667 { yygotominor.yy59 = yymsp[0].minor.yy59; }
123668 break;
123669 case 325: /* wqlist ::= nm idxlist_opt AS LP select RP */
123671 yygotominor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
123673 break;
123674 case 326: /* wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP */
123676 yygotominor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
123678 break;
123679 default:
123680 /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
123681 /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
123682 /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
123683 /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
123684 /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
123685 /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
123686 /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
123687 /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
123688 /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
123689 /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
123690 /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
123691 /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
123692 /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
123693 /* (43) type ::= */ yytestcase(yyruleno==43);
123694 /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
123695 /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
123696 /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
123697 /* (53) carglist ::= */ yytestcase(yyruleno==53);
123698 /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
123699 /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
123700 /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
123701 /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
123702 /* (273) foreach_clause ::= */ yytestcase(yyruleno==273);
123703 /* (274) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==274);
123704 /* (281) tridxby ::= */ yytestcase(yyruleno==281);
123705 /* (298) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==298);
123706 /* (299) database_kw_opt ::= */ yytestcase(yyruleno==299);
123707 /* (307) kwcolumn_opt ::= */ yytestcase(yyruleno==307);
123708 /* (308) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==308);
123709 /* (312) vtabarglist ::= vtabarg */ yytestcase(yyruleno==312);
123710 /* (313) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==313);
123711 /* (315) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==315);
123712 /* (319) anylist ::= */ yytestcase(yyruleno==319);
123713 /* (320) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==320);
123714 /* (321) anylist ::= anylist ANY */ yytestcase(yyruleno==321);
123715 break;
123717 assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
123718 yygoto = yyRuleInfo[yyruleno].lhs;
123719 yysize = yyRuleInfo[yyruleno].nrhs;
123720 yypParser->yyidx -= yysize;
123721 yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
123722 if( yyact < YYNSTATE ){
123723 #ifdef NDEBUG
123724 /* If we are not debugging and the reduce action popped at least
123725 ** one element off the stack, then we can push the new element back
123726 ** onto the stack here, and skip the stack overflow test in yy_shift().
123727 ** That gives a significant speed improvement. */
123728 if( yysize ){
123729 yypParser->yyidx++;
123730 yymsp -= yysize-1;
123731 yymsp->stateno = (YYACTIONTYPE)yyact;
123732 yymsp->major = (YYCODETYPE)yygoto;
123733 yymsp->minor = yygotominor;
123734 }else
123735 #endif
123737 yy_shift(yypParser,yyact,yygoto,&yygotominor);
123739 }else{
123740 assert( yyact == YYNSTATE + YYNRULE + 1 );
123741 yy_accept(yypParser);
123746 ** The following code executes when the parse fails
123748 #ifndef YYNOERRORRECOVERY
123749 static void yy_parse_failed(
123750 yyParser *yypParser /* The parser */
123752 sqlite3ParserARG_FETCH;
123753 #ifndef NDEBUG
123754 if( yyTraceFILE ){
123755 fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
123757 #endif
123758 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
123759 /* Here code is inserted which will be executed whenever the
123760 ** parser fails */
123761 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
123763 #endif /* YYNOERRORRECOVERY */
123766 ** The following code executes when a syntax error first occurs.
123768 static void yy_syntax_error(
123769 yyParser *yypParser, /* The parser */
123770 int yymajor, /* The major type of the error token */
123771 YYMINORTYPE yyminor /* The minor type of the error token */
123773 sqlite3ParserARG_FETCH;
123774 #define TOKEN (yyminor.yy0)
123776 UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
123777 assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
123778 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
123779 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
123783 ** The following is executed when the parser accepts
123785 static void yy_accept(
123786 yyParser *yypParser /* The parser */
123788 sqlite3ParserARG_FETCH;
123789 #ifndef NDEBUG
123790 if( yyTraceFILE ){
123791 fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
123793 #endif
123794 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
123795 /* Here code is inserted which will be executed whenever the
123796 ** parser accepts */
123797 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
123800 /* The main parser program.
123801 ** The first argument is a pointer to a structure obtained from
123802 ** "sqlite3ParserAlloc" which describes the current state of the parser.
123803 ** The second argument is the major token number. The third is
123804 ** the minor token. The fourth optional argument is whatever the
123805 ** user wants (and specified in the grammar) and is available for
123806 ** use by the action routines.
123808 ** Inputs:
123809 ** <ul>
123810 ** <li> A pointer to the parser (an opaque structure.)
123811 ** <li> The major token number.
123812 ** <li> The minor token number.
123813 ** <li> An option argument of a grammar-specified type.
123814 ** </ul>
123816 ** Outputs:
123817 ** None.
123819 SQLITE_PRIVATE void sqlite3Parser(
123820 void *yyp, /* The parser */
123821 int yymajor, /* The major token code number */
123822 sqlite3ParserTOKENTYPE yyminor /* The value for the token */
123823 sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
123825 YYMINORTYPE yyminorunion;
123826 int yyact; /* The parser action. */
123827 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
123828 int yyendofinput; /* True if we are at the end of input */
123829 #endif
123830 #ifdef YYERRORSYMBOL
123831 int yyerrorhit = 0; /* True if yymajor has invoked an error */
123832 #endif
123833 yyParser *yypParser; /* The parser */
123835 /* (re)initialize the parser, if necessary */
123836 yypParser = (yyParser*)yyp;
123837 if( yypParser->yyidx<0 ){
123838 #if YYSTACKDEPTH<=0
123839 if( yypParser->yystksz <=0 ){
123840 /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
123841 yyminorunion = yyzerominor;
123842 yyStackOverflow(yypParser, &yyminorunion);
123843 return;
123845 #endif
123846 yypParser->yyidx = 0;
123847 yypParser->yyerrcnt = -1;
123848 yypParser->yystack[0].stateno = 0;
123849 yypParser->yystack[0].major = 0;
123851 yyminorunion.yy0 = yyminor;
123852 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
123853 yyendofinput = (yymajor==0);
123854 #endif
123855 sqlite3ParserARG_STORE;
123857 #ifndef NDEBUG
123858 if( yyTraceFILE ){
123859 fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
123861 #endif
123864 yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
123865 if( yyact<YYNSTATE ){
123866 yy_shift(yypParser,yyact,yymajor,&yyminorunion);
123867 yypParser->yyerrcnt--;
123868 yymajor = YYNOCODE;
123869 }else if( yyact < YYNSTATE + YYNRULE ){
123870 yy_reduce(yypParser,yyact-YYNSTATE);
123871 }else{
123872 assert( yyact == YY_ERROR_ACTION );
123873 #ifdef YYERRORSYMBOL
123874 int yymx;
123875 #endif
123876 #ifndef NDEBUG
123877 if( yyTraceFILE ){
123878 fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
123880 #endif
123881 #ifdef YYERRORSYMBOL
123882 /* A syntax error has occurred.
123883 ** The response to an error depends upon whether or not the
123884 ** grammar defines an error token "ERROR".
123886 ** This is what we do if the grammar does define ERROR:
123888 ** * Call the %syntax_error function.
123890 ** * Begin popping the stack until we enter a state where
123891 ** it is legal to shift the error symbol, then shift
123892 ** the error symbol.
123894 ** * Set the error count to three.
123896 ** * Begin accepting and shifting new tokens. No new error
123897 ** processing will occur until three tokens have been
123898 ** shifted successfully.
123901 if( yypParser->yyerrcnt<0 ){
123902 yy_syntax_error(yypParser,yymajor,yyminorunion);
123904 yymx = yypParser->yystack[yypParser->yyidx].major;
123905 if( yymx==YYERRORSYMBOL || yyerrorhit ){
123906 #ifndef NDEBUG
123907 if( yyTraceFILE ){
123908 fprintf(yyTraceFILE,"%sDiscard input token %s\n",
123909 yyTracePrompt,yyTokenName[yymajor]);
123911 #endif
123912 yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
123913 yymajor = YYNOCODE;
123914 }else{
123915 while(
123916 yypParser->yyidx >= 0 &&
123917 yymx != YYERRORSYMBOL &&
123918 (yyact = yy_find_reduce_action(
123919 yypParser->yystack[yypParser->yyidx].stateno,
123920 YYERRORSYMBOL)) >= YYNSTATE
123922 yy_pop_parser_stack(yypParser);
123924 if( yypParser->yyidx < 0 || yymajor==0 ){
123925 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
123926 yy_parse_failed(yypParser);
123927 yymajor = YYNOCODE;
123928 }else if( yymx!=YYERRORSYMBOL ){
123929 YYMINORTYPE u2;
123930 u2.YYERRSYMDT = 0;
123931 yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
123934 yypParser->yyerrcnt = 3;
123935 yyerrorhit = 1;
123936 #elif defined(YYNOERRORRECOVERY)
123937 /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
123938 ** do any kind of error recovery. Instead, simply invoke the syntax
123939 ** error routine and continue going as if nothing had happened.
123941 ** Applications can set this macro (for example inside %include) if
123942 ** they intend to abandon the parse upon the first syntax error seen.
123944 yy_syntax_error(yypParser,yymajor,yyminorunion);
123945 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
123946 yymajor = YYNOCODE;
123948 #else /* YYERRORSYMBOL is not defined */
123949 /* This is what we do if the grammar does not define ERROR:
123951 ** * Report an error message, and throw away the input token.
123953 ** * If the input token is $, then fail the parse.
123955 ** As before, subsequent error messages are suppressed until
123956 ** three input tokens have been successfully shifted.
123958 if( yypParser->yyerrcnt<=0 ){
123959 yy_syntax_error(yypParser,yymajor,yyminorunion);
123961 yypParser->yyerrcnt = 3;
123962 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
123963 if( yyendofinput ){
123964 yy_parse_failed(yypParser);
123966 yymajor = YYNOCODE;
123967 #endif
123969 }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
123970 return;
123973 /************** End of parse.c ***********************************************/
123974 /************** Begin file tokenize.c ****************************************/
123976 ** 2001 September 15
123978 ** The author disclaims copyright to this source code. In place of
123979 ** a legal notice, here is a blessing:
123981 ** May you do good and not evil.
123982 ** May you find forgiveness for yourself and forgive others.
123983 ** May you share freely, never taking more than you give.
123985 *************************************************************************
123986 ** An tokenizer for SQL
123988 ** This file contains C code that splits an SQL input string up into
123989 ** individual tokens and sends those tokens one-by-one over to the
123990 ** parser for analysis.
123992 /* #include <stdlib.h> */
123995 ** The charMap() macro maps alphabetic characters into their
123996 ** lower-case ASCII equivalent. On ASCII machines, this is just
123997 ** an upper-to-lower case map. On EBCDIC machines we also need
123998 ** to adjust the encoding. Only alphabetic characters and underscores
123999 ** need to be translated.
124001 #ifdef SQLITE_ASCII
124002 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
124003 #endif
124004 #ifdef SQLITE_EBCDIC
124005 # define charMap(X) ebcdicToAscii[(unsigned char)X]
124006 const unsigned char ebcdicToAscii[] = {
124007 /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
124008 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
124009 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
124010 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
124011 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
124012 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
124013 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
124014 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
124015 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
124016 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
124017 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
124018 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
124019 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
124020 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
124021 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
124022 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
124023 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
124025 #endif
124028 ** The sqlite3KeywordCode function looks up an identifier to determine if
124029 ** it is a keyword. If it is a keyword, the token code of that keyword is
124030 ** returned. If the input is not a keyword, TK_ID is returned.
124032 ** The implementation of this routine was generated by a program,
124033 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
124034 ** The output of the mkkeywordhash.c program is written into a file
124035 ** named keywordhash.h and then included into this source file by
124036 ** the #include below.
124038 /************** Include keywordhash.h in the middle of tokenize.c ************/
124039 /************** Begin file keywordhash.h *************************************/
124040 /***** This file contains automatically generated code ******
124042 ** The code in this file has been automatically generated by
124044 ** sqlite/tool/mkkeywordhash.c
124046 ** The code in this file implements a function that determines whether
124047 ** or not a given identifier is really an SQL keyword. The same thing
124048 ** might be implemented more directly using a hand-written hash table.
124049 ** But by using this automatically generated code, the size of the code
124050 ** is substantially reduced. This is important for embedded applications
124051 ** on platforms with limited memory.
124053 /* Hash score: 182 */
124054 static int keywordCode(const char *z, int n){
124055 /* zText[] encodes 834 bytes of keywords in 554 bytes */
124056 /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
124057 /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
124058 /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
124059 /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
124060 /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
124061 /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
124062 /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
124063 /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
124064 /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
124065 /* VACUUMVIEWINITIALLY */
124066 static const char zText[553] = {
124067 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
124068 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
124069 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
124070 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
124071 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
124072 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
124073 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
124074 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
124075 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
124076 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
124077 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
124078 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
124079 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
124080 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
124081 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
124082 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
124083 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
124084 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
124085 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
124086 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
124087 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
124088 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
124089 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
124090 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
124091 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
124092 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
124093 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
124094 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
124095 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
124096 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
124097 'V','I','E','W','I','N','I','T','I','A','L','L','Y',
124099 static const unsigned char aHash[127] = {
124100 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
124101 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
124102 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
124103 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
124104 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
124105 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
124106 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
124107 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
124108 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
124109 29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
124111 static const unsigned char aNext[124] = {
124112 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
124113 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
124114 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
124115 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
124116 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
124117 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
124118 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
124119 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
124120 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
124121 73, 83, 0, 35, 68, 0, 0,
124123 static const unsigned char aLen[124] = {
124124 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
124125 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
124126 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
124127 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
124128 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
124129 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
124130 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
124131 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
124132 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
124133 3, 5, 5, 6, 4, 9, 3,
124135 static const unsigned short int aOffset[124] = {
124136 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
124137 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
124138 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
124139 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
124140 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
124141 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
124142 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
124143 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
124144 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
124145 521, 524, 529, 534, 540, 544, 549,
124147 static const unsigned char aCode[124] = {
124148 TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
124149 TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
124150 TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
124151 TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
124152 TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
124153 TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
124154 TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
124155 TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
124156 TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
124157 TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
124158 TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
124159 TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN,
124160 TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
124161 TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE,
124162 TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN,
124163 TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
124164 TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN,
124165 TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND,
124166 TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
124167 TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
124168 TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS,
124169 TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW,
124170 TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT,
124171 TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
124172 TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
124174 int h, i;
124175 if( n<2 ) return TK_ID;
124176 h = ((charMap(z[0])*4) ^
124177 (charMap(z[n-1])*3) ^
124178 n) % 127;
124179 for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
124180 if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
124181 testcase( i==0 ); /* REINDEX */
124182 testcase( i==1 ); /* INDEXED */
124183 testcase( i==2 ); /* INDEX */
124184 testcase( i==3 ); /* DESC */
124185 testcase( i==4 ); /* ESCAPE */
124186 testcase( i==5 ); /* EACH */
124187 testcase( i==6 ); /* CHECK */
124188 testcase( i==7 ); /* KEY */
124189 testcase( i==8 ); /* BEFORE */
124190 testcase( i==9 ); /* FOREIGN */
124191 testcase( i==10 ); /* FOR */
124192 testcase( i==11 ); /* IGNORE */
124193 testcase( i==12 ); /* REGEXP */
124194 testcase( i==13 ); /* EXPLAIN */
124195 testcase( i==14 ); /* INSTEAD */
124196 testcase( i==15 ); /* ADD */
124197 testcase( i==16 ); /* DATABASE */
124198 testcase( i==17 ); /* AS */
124199 testcase( i==18 ); /* SELECT */
124200 testcase( i==19 ); /* TABLE */
124201 testcase( i==20 ); /* LEFT */
124202 testcase( i==21 ); /* THEN */
124203 testcase( i==22 ); /* END */
124204 testcase( i==23 ); /* DEFERRABLE */
124205 testcase( i==24 ); /* ELSE */
124206 testcase( i==25 ); /* EXCEPT */
124207 testcase( i==26 ); /* TRANSACTION */
124208 testcase( i==27 ); /* ACTION */
124209 testcase( i==28 ); /* ON */
124210 testcase( i==29 ); /* NATURAL */
124211 testcase( i==30 ); /* ALTER */
124212 testcase( i==31 ); /* RAISE */
124213 testcase( i==32 ); /* EXCLUSIVE */
124214 testcase( i==33 ); /* EXISTS */
124215 testcase( i==34 ); /* SAVEPOINT */
124216 testcase( i==35 ); /* INTERSECT */
124217 testcase( i==36 ); /* TRIGGER */
124218 testcase( i==37 ); /* REFERENCES */
124219 testcase( i==38 ); /* CONSTRAINT */
124220 testcase( i==39 ); /* INTO */
124221 testcase( i==40 ); /* OFFSET */
124222 testcase( i==41 ); /* OF */
124223 testcase( i==42 ); /* SET */
124224 testcase( i==43 ); /* TEMPORARY */
124225 testcase( i==44 ); /* TEMP */
124226 testcase( i==45 ); /* OR */
124227 testcase( i==46 ); /* UNIQUE */
124228 testcase( i==47 ); /* QUERY */
124229 testcase( i==48 ); /* WITHOUT */
124230 testcase( i==49 ); /* WITH */
124231 testcase( i==50 ); /* OUTER */
124232 testcase( i==51 ); /* RELEASE */
124233 testcase( i==52 ); /* ATTACH */
124234 testcase( i==53 ); /* HAVING */
124235 testcase( i==54 ); /* GROUP */
124236 testcase( i==55 ); /* UPDATE */
124237 testcase( i==56 ); /* BEGIN */
124238 testcase( i==57 ); /* INNER */
124239 testcase( i==58 ); /* RECURSIVE */
124240 testcase( i==59 ); /* BETWEEN */
124241 testcase( i==60 ); /* NOTNULL */
124242 testcase( i==61 ); /* NOT */
124243 testcase( i==62 ); /* NO */
124244 testcase( i==63 ); /* NULL */
124245 testcase( i==64 ); /* LIKE */
124246 testcase( i==65 ); /* CASCADE */
124247 testcase( i==66 ); /* ASC */
124248 testcase( i==67 ); /* DELETE */
124249 testcase( i==68 ); /* CASE */
124250 testcase( i==69 ); /* COLLATE */
124251 testcase( i==70 ); /* CREATE */
124252 testcase( i==71 ); /* CURRENT_DATE */
124253 testcase( i==72 ); /* DETACH */
124254 testcase( i==73 ); /* IMMEDIATE */
124255 testcase( i==74 ); /* JOIN */
124256 testcase( i==75 ); /* INSERT */
124257 testcase( i==76 ); /* MATCH */
124258 testcase( i==77 ); /* PLAN */
124259 testcase( i==78 ); /* ANALYZE */
124260 testcase( i==79 ); /* PRAGMA */
124261 testcase( i==80 ); /* ABORT */
124262 testcase( i==81 ); /* VALUES */
124263 testcase( i==82 ); /* VIRTUAL */
124264 testcase( i==83 ); /* LIMIT */
124265 testcase( i==84 ); /* WHEN */
124266 testcase( i==85 ); /* WHERE */
124267 testcase( i==86 ); /* RENAME */
124268 testcase( i==87 ); /* AFTER */
124269 testcase( i==88 ); /* REPLACE */
124270 testcase( i==89 ); /* AND */
124271 testcase( i==90 ); /* DEFAULT */
124272 testcase( i==91 ); /* AUTOINCREMENT */
124273 testcase( i==92 ); /* TO */
124274 testcase( i==93 ); /* IN */
124275 testcase( i==94 ); /* CAST */
124276 testcase( i==95 ); /* COLUMN */
124277 testcase( i==96 ); /* COMMIT */
124278 testcase( i==97 ); /* CONFLICT */
124279 testcase( i==98 ); /* CROSS */
124280 testcase( i==99 ); /* CURRENT_TIMESTAMP */
124281 testcase( i==100 ); /* CURRENT_TIME */
124282 testcase( i==101 ); /* PRIMARY */
124283 testcase( i==102 ); /* DEFERRED */
124284 testcase( i==103 ); /* DISTINCT */
124285 testcase( i==104 ); /* IS */
124286 testcase( i==105 ); /* DROP */
124287 testcase( i==106 ); /* FAIL */
124288 testcase( i==107 ); /* FROM */
124289 testcase( i==108 ); /* FULL */
124290 testcase( i==109 ); /* GLOB */
124291 testcase( i==110 ); /* BY */
124292 testcase( i==111 ); /* IF */
124293 testcase( i==112 ); /* ISNULL */
124294 testcase( i==113 ); /* ORDER */
124295 testcase( i==114 ); /* RESTRICT */
124296 testcase( i==115 ); /* RIGHT */
124297 testcase( i==116 ); /* ROLLBACK */
124298 testcase( i==117 ); /* ROW */
124299 testcase( i==118 ); /* UNION */
124300 testcase( i==119 ); /* USING */
124301 testcase( i==120 ); /* VACUUM */
124302 testcase( i==121 ); /* VIEW */
124303 testcase( i==122 ); /* INITIALLY */
124304 testcase( i==123 ); /* ALL */
124305 return aCode[i];
124308 return TK_ID;
124310 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
124311 return keywordCode((char*)z, n);
124313 #define SQLITE_N_KEYWORD 124
124315 /************** End of keywordhash.h *****************************************/
124316 /************** Continuing where we left off in tokenize.c *******************/
124320 ** If X is a character that can be used in an identifier then
124321 ** IdChar(X) will be true. Otherwise it is false.
124323 ** For ASCII, any character with the high-order bit set is
124324 ** allowed in an identifier. For 7-bit characters,
124325 ** sqlite3IsIdChar[X] must be 1.
124327 ** For EBCDIC, the rules are more complex but have the same
124328 ** end result.
124330 ** Ticket #1066. the SQL standard does not allow '$' in the
124331 ** middle of identifiers. But many SQL implementations do.
124332 ** SQLite will allow '$' in identifiers for compatibility.
124333 ** But the feature is undocumented.
124335 #ifdef SQLITE_ASCII
124336 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
124337 #endif
124338 #ifdef SQLITE_EBCDIC
124339 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
124340 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
124341 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
124342 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
124343 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
124344 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
124345 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
124346 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
124347 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
124348 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
124349 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
124350 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
124351 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
124352 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
124354 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
124355 #endif
124356 SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
124360 ** Return the length of the token that begins at z[0].
124361 ** Store the token type in *tokenType before returning.
124363 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
124364 int i, c;
124365 switch( *z ){
124366 case ' ': case '\t': case '\n': case '\f': case '\r': {
124367 testcase( z[0]==' ' );
124368 testcase( z[0]=='\t' );
124369 testcase( z[0]=='\n' );
124370 testcase( z[0]=='\f' );
124371 testcase( z[0]=='\r' );
124372 for(i=1; sqlite3Isspace(z[i]); i++){}
124373 *tokenType = TK_SPACE;
124374 return i;
124376 case '-': {
124377 if( z[1]=='-' ){
124378 for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
124379 *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
124380 return i;
124382 *tokenType = TK_MINUS;
124383 return 1;
124385 case '(': {
124386 *tokenType = TK_LP;
124387 return 1;
124389 case ')': {
124390 *tokenType = TK_RP;
124391 return 1;
124393 case ';': {
124394 *tokenType = TK_SEMI;
124395 return 1;
124397 case '+': {
124398 *tokenType = TK_PLUS;
124399 return 1;
124401 case '*': {
124402 *tokenType = TK_STAR;
124403 return 1;
124405 case '/': {
124406 if( z[1]!='*' || z[2]==0 ){
124407 *tokenType = TK_SLASH;
124408 return 1;
124410 for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
124411 if( c ) i++;
124412 *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
124413 return i;
124415 case '%': {
124416 *tokenType = TK_REM;
124417 return 1;
124419 case '=': {
124420 *tokenType = TK_EQ;
124421 return 1 + (z[1]=='=');
124423 case '<': {
124424 if( (c=z[1])=='=' ){
124425 *tokenType = TK_LE;
124426 return 2;
124427 }else if( c=='>' ){
124428 *tokenType = TK_NE;
124429 return 2;
124430 }else if( c=='<' ){
124431 *tokenType = TK_LSHIFT;
124432 return 2;
124433 }else{
124434 *tokenType = TK_LT;
124435 return 1;
124438 case '>': {
124439 if( (c=z[1])=='=' ){
124440 *tokenType = TK_GE;
124441 return 2;
124442 }else if( c=='>' ){
124443 *tokenType = TK_RSHIFT;
124444 return 2;
124445 }else{
124446 *tokenType = TK_GT;
124447 return 1;
124450 case '!': {
124451 if( z[1]!='=' ){
124452 *tokenType = TK_ILLEGAL;
124453 return 2;
124454 }else{
124455 *tokenType = TK_NE;
124456 return 2;
124459 case '|': {
124460 if( z[1]!='|' ){
124461 *tokenType = TK_BITOR;
124462 return 1;
124463 }else{
124464 *tokenType = TK_CONCAT;
124465 return 2;
124468 case ',': {
124469 *tokenType = TK_COMMA;
124470 return 1;
124472 case '&': {
124473 *tokenType = TK_BITAND;
124474 return 1;
124476 case '~': {
124477 *tokenType = TK_BITNOT;
124478 return 1;
124480 case '`':
124481 case '\'':
124482 case '"': {
124483 int delim = z[0];
124484 testcase( delim=='`' );
124485 testcase( delim=='\'' );
124486 testcase( delim=='"' );
124487 for(i=1; (c=z[i])!=0; i++){
124488 if( c==delim ){
124489 if( z[i+1]==delim ){
124491 }else{
124492 break;
124496 if( c=='\'' ){
124497 *tokenType = TK_STRING;
124498 return i+1;
124499 }else if( c!=0 ){
124500 *tokenType = TK_ID;
124501 return i+1;
124502 }else{
124503 *tokenType = TK_ILLEGAL;
124504 return i;
124507 case '.': {
124508 #ifndef SQLITE_OMIT_FLOATING_POINT
124509 if( !sqlite3Isdigit(z[1]) )
124510 #endif
124512 *tokenType = TK_DOT;
124513 return 1;
124515 /* If the next character is a digit, this is a floating point
124516 ** number that begins with ".". Fall thru into the next case */
124518 case '0': case '1': case '2': case '3': case '4':
124519 case '5': case '6': case '7': case '8': case '9': {
124520 testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
124521 testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
124522 testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
124523 testcase( z[0]=='9' );
124524 *tokenType = TK_INTEGER;
124525 #ifndef SQLITE_OMIT_HEX_INTEGER
124526 if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
124527 for(i=3; sqlite3Isxdigit(z[i]); i++){}
124528 return i;
124530 #endif
124531 for(i=0; sqlite3Isdigit(z[i]); i++){}
124532 #ifndef SQLITE_OMIT_FLOATING_POINT
124533 if( z[i]=='.' ){
124535 while( sqlite3Isdigit(z[i]) ){ i++; }
124536 *tokenType = TK_FLOAT;
124538 if( (z[i]=='e' || z[i]=='E') &&
124539 ( sqlite3Isdigit(z[i+1])
124540 || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
124543 i += 2;
124544 while( sqlite3Isdigit(z[i]) ){ i++; }
124545 *tokenType = TK_FLOAT;
124547 #endif
124548 while( IdChar(z[i]) ){
124549 *tokenType = TK_ILLEGAL;
124552 return i;
124554 case '[': {
124555 for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
124556 *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
124557 return i;
124559 case '?': {
124560 *tokenType = TK_VARIABLE;
124561 for(i=1; sqlite3Isdigit(z[i]); i++){}
124562 return i;
124564 #ifndef SQLITE_OMIT_TCL_VARIABLE
124565 case '$':
124566 #endif
124567 case '@': /* For compatibility with MS SQL Server */
124568 case '#':
124569 case ':': {
124570 int n = 0;
124571 testcase( z[0]=='$' ); testcase( z[0]=='@' );
124572 testcase( z[0]==':' ); testcase( z[0]=='#' );
124573 *tokenType = TK_VARIABLE;
124574 for(i=1; (c=z[i])!=0; i++){
124575 if( IdChar(c) ){
124577 #ifndef SQLITE_OMIT_TCL_VARIABLE
124578 }else if( c=='(' && n>0 ){
124581 }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
124582 if( c==')' ){
124584 }else{
124585 *tokenType = TK_ILLEGAL;
124587 break;
124588 }else if( c==':' && z[i+1]==':' ){
124590 #endif
124591 }else{
124592 break;
124595 if( n==0 ) *tokenType = TK_ILLEGAL;
124596 return i;
124598 #ifndef SQLITE_OMIT_BLOB_LITERAL
124599 case 'x': case 'X': {
124600 testcase( z[0]=='x' ); testcase( z[0]=='X' );
124601 if( z[1]=='\'' ){
124602 *tokenType = TK_BLOB;
124603 for(i=2; sqlite3Isxdigit(z[i]); i++){}
124604 if( z[i]!='\'' || i%2 ){
124605 *tokenType = TK_ILLEGAL;
124606 while( z[i] && z[i]!='\'' ){ i++; }
124608 if( z[i] ) i++;
124609 return i;
124611 /* Otherwise fall through to the next case */
124613 #endif
124614 default: {
124615 if( !IdChar(*z) ){
124616 break;
124618 for(i=1; IdChar(z[i]); i++){}
124619 *tokenType = keywordCode((char*)z, i);
124620 return i;
124623 *tokenType = TK_ILLEGAL;
124624 return 1;
124628 ** Run the parser on the given SQL string. The parser structure is
124629 ** passed in. An SQLITE_ status code is returned. If an error occurs
124630 ** then an and attempt is made to write an error message into
124631 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
124632 ** error message.
124634 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
124635 int nErr = 0; /* Number of errors encountered */
124636 int i; /* Loop counter */
124637 void *pEngine; /* The LEMON-generated LALR(1) parser */
124638 int tokenType; /* type of the next token */
124639 int lastTokenParsed = -1; /* type of the previous token */
124640 u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
124641 sqlite3 *db = pParse->db; /* The database connection */
124642 int mxSqlLen; /* Max length of an SQL string */
124645 mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
124646 if( db->nVdbeActive==0 ){
124647 db->u1.isInterrupted = 0;
124649 pParse->rc = SQLITE_OK;
124650 pParse->zTail = zSql;
124651 i = 0;
124652 assert( pzErrMsg!=0 );
124653 pEngine = sqlite3ParserAlloc(sqlite3Malloc);
124654 if( pEngine==0 ){
124655 db->mallocFailed = 1;
124656 return SQLITE_NOMEM;
124658 assert( pParse->pNewTable==0 );
124659 assert( pParse->pNewTrigger==0 );
124660 assert( pParse->nVar==0 );
124661 assert( pParse->nzVar==0 );
124662 assert( pParse->azVar==0 );
124663 enableLookaside = db->lookaside.bEnabled;
124664 if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
124665 while( !db->mallocFailed && zSql[i]!=0 ){
124666 assert( i>=0 );
124667 pParse->sLastToken.z = &zSql[i];
124668 pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
124669 i += pParse->sLastToken.n;
124670 if( i>mxSqlLen ){
124671 pParse->rc = SQLITE_TOOBIG;
124672 break;
124674 switch( tokenType ){
124675 case TK_SPACE: {
124676 if( db->u1.isInterrupted ){
124677 sqlite3ErrorMsg(pParse, "interrupt");
124678 pParse->rc = SQLITE_INTERRUPT;
124679 goto abort_parse;
124681 break;
124683 case TK_ILLEGAL: {
124684 sqlite3DbFree(db, *pzErrMsg);
124685 *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
124686 &pParse->sLastToken);
124687 nErr++;
124688 goto abort_parse;
124690 case TK_SEMI: {
124691 pParse->zTail = &zSql[i];
124692 /* Fall thru into the default case */
124694 default: {
124695 sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
124696 lastTokenParsed = tokenType;
124697 if( pParse->rc!=SQLITE_OK ){
124698 goto abort_parse;
124700 break;
124704 abort_parse:
124705 if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
124706 if( lastTokenParsed!=TK_SEMI ){
124707 sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
124708 pParse->zTail = &zSql[i];
124710 sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
124712 #ifdef YYTRACKMAXSTACKDEPTH
124713 sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
124714 sqlite3ParserStackPeak(pEngine)
124716 #endif /* YYDEBUG */
124717 sqlite3ParserFree(pEngine, sqlite3_free);
124718 db->lookaside.bEnabled = enableLookaside;
124719 if( db->mallocFailed ){
124720 pParse->rc = SQLITE_NOMEM;
124722 if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
124723 sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
124725 assert( pzErrMsg!=0 );
124726 if( pParse->zErrMsg ){
124727 *pzErrMsg = pParse->zErrMsg;
124728 sqlite3_log(pParse->rc, "%s", *pzErrMsg);
124729 pParse->zErrMsg = 0;
124730 nErr++;
124732 if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
124733 sqlite3VdbeDelete(pParse->pVdbe);
124734 pParse->pVdbe = 0;
124736 #ifndef SQLITE_OMIT_SHARED_CACHE
124737 if( pParse->nested==0 ){
124738 sqlite3DbFree(db, pParse->aTableLock);
124739 pParse->aTableLock = 0;
124740 pParse->nTableLock = 0;
124742 #endif
124743 #ifndef SQLITE_OMIT_VIRTUALTABLE
124744 sqlite3_free(pParse->apVtabLock);
124745 #endif
124747 if( !IN_DECLARE_VTAB ){
124748 /* If the pParse->declareVtab flag is set, do not delete any table
124749 ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
124750 ** will take responsibility for freeing the Table structure.
124752 sqlite3DeleteTable(db, pParse->pNewTable);
124755 if( pParse->bFreeWith ) sqlite3WithDelete(db, pParse->pWith);
124756 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
124757 for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
124758 sqlite3DbFree(db, pParse->azVar);
124759 while( pParse->pAinc ){
124760 AutoincInfo *p = pParse->pAinc;
124761 pParse->pAinc = p->pNext;
124762 sqlite3DbFree(db, p);
124764 while( pParse->pZombieTab ){
124765 Table *p = pParse->pZombieTab;
124766 pParse->pZombieTab = p->pNextZombie;
124767 sqlite3DeleteTable(db, p);
124769 if( nErr>0 && pParse->rc==SQLITE_OK ){
124770 pParse->rc = SQLITE_ERROR;
124772 return nErr;
124775 /************** End of tokenize.c ********************************************/
124776 /************** Begin file complete.c ****************************************/
124778 ** 2001 September 15
124780 ** The author disclaims copyright to this source code. In place of
124781 ** a legal notice, here is a blessing:
124783 ** May you do good and not evil.
124784 ** May you find forgiveness for yourself and forgive others.
124785 ** May you share freely, never taking more than you give.
124787 *************************************************************************
124788 ** An tokenizer for SQL
124790 ** This file contains C code that implements the sqlite3_complete() API.
124791 ** This code used to be part of the tokenizer.c source file. But by
124792 ** separating it out, the code will be automatically omitted from
124793 ** static links that do not use it.
124795 #ifndef SQLITE_OMIT_COMPLETE
124798 ** This is defined in tokenize.c. We just have to import the definition.
124800 #ifndef SQLITE_AMALGAMATION
124801 #ifdef SQLITE_ASCII
124802 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
124803 #endif
124804 #ifdef SQLITE_EBCDIC
124805 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
124806 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
124807 #endif
124808 #endif /* SQLITE_AMALGAMATION */
124812 ** Token types used by the sqlite3_complete() routine. See the header
124813 ** comments on that procedure for additional information.
124815 #define tkSEMI 0
124816 #define tkWS 1
124817 #define tkOTHER 2
124818 #ifndef SQLITE_OMIT_TRIGGER
124819 #define tkEXPLAIN 3
124820 #define tkCREATE 4
124821 #define tkTEMP 5
124822 #define tkTRIGGER 6
124823 #define tkEND 7
124824 #endif
124827 ** Return TRUE if the given SQL string ends in a semicolon.
124829 ** Special handling is require for CREATE TRIGGER statements.
124830 ** Whenever the CREATE TRIGGER keywords are seen, the statement
124831 ** must end with ";END;".
124833 ** This implementation uses a state machine with 8 states:
124835 ** (0) INVALID We have not yet seen a non-whitespace character.
124837 ** (1) START At the beginning or end of an SQL statement. This routine
124838 ** returns 1 if it ends in the START state and 0 if it ends
124839 ** in any other state.
124841 ** (2) NORMAL We are in the middle of statement which ends with a single
124842 ** semicolon.
124844 ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
124845 ** a statement.
124847 ** (4) CREATE The keyword CREATE has been seen at the beginning of a
124848 ** statement, possibly preceded by EXPLAIN and/or followed by
124849 ** TEMP or TEMPORARY
124851 ** (5) TRIGGER We are in the middle of a trigger definition that must be
124852 ** ended by a semicolon, the keyword END, and another semicolon.
124854 ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
124855 ** the end of a trigger definition.
124857 ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
124858 ** of a trigger definition.
124860 ** Transitions between states above are determined by tokens extracted
124861 ** from the input. The following tokens are significant:
124863 ** (0) tkSEMI A semicolon.
124864 ** (1) tkWS Whitespace.
124865 ** (2) tkOTHER Any other SQL token.
124866 ** (3) tkEXPLAIN The "explain" keyword.
124867 ** (4) tkCREATE The "create" keyword.
124868 ** (5) tkTEMP The "temp" or "temporary" keyword.
124869 ** (6) tkTRIGGER The "trigger" keyword.
124870 ** (7) tkEND The "end" keyword.
124872 ** Whitespace never causes a state transition and is always ignored.
124873 ** This means that a SQL string of all whitespace is invalid.
124875 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
124876 ** to recognize the end of a trigger can be omitted. All we have to do
124877 ** is look for a semicolon that is not part of an string or comment.
124879 SQLITE_API int sqlite3_complete(const char *zSql){
124880 u8 state = 0; /* Current state, using numbers defined in header comment */
124881 u8 token; /* Value of the next token */
124883 #ifndef SQLITE_OMIT_TRIGGER
124884 /* A complex statement machine used to detect the end of a CREATE TRIGGER
124885 ** statement. This is the normal case.
124887 static const u8 trans[8][8] = {
124888 /* Token: */
124889 /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
124890 /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
124891 /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
124892 /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
124893 /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
124894 /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
124895 /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
124896 /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
124897 /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
124899 #else
124900 /* If triggers are not supported by this compile then the statement machine
124901 ** used to detect the end of a statement is much simpler
124903 static const u8 trans[3][3] = {
124904 /* Token: */
124905 /* State: ** SEMI WS OTHER */
124906 /* 0 INVALID: */ { 1, 0, 2, },
124907 /* 1 START: */ { 1, 1, 2, },
124908 /* 2 NORMAL: */ { 1, 2, 2, },
124910 #endif /* SQLITE_OMIT_TRIGGER */
124912 while( *zSql ){
124913 switch( *zSql ){
124914 case ';': { /* A semicolon */
124915 token = tkSEMI;
124916 break;
124918 case ' ':
124919 case '\r':
124920 case '\t':
124921 case '\n':
124922 case '\f': { /* White space is ignored */
124923 token = tkWS;
124924 break;
124926 case '/': { /* C-style comments */
124927 if( zSql[1]!='*' ){
124928 token = tkOTHER;
124929 break;
124931 zSql += 2;
124932 while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
124933 if( zSql[0]==0 ) return 0;
124934 zSql++;
124935 token = tkWS;
124936 break;
124938 case '-': { /* SQL-style comments from "--" to end of line */
124939 if( zSql[1]!='-' ){
124940 token = tkOTHER;
124941 break;
124943 while( *zSql && *zSql!='\n' ){ zSql++; }
124944 if( *zSql==0 ) return state==1;
124945 token = tkWS;
124946 break;
124948 case '[': { /* Microsoft-style identifiers in [...] */
124949 zSql++;
124950 while( *zSql && *zSql!=']' ){ zSql++; }
124951 if( *zSql==0 ) return 0;
124952 token = tkOTHER;
124953 break;
124955 case '`': /* Grave-accent quoted symbols used by MySQL */
124956 case '"': /* single- and double-quoted strings */
124957 case '\'': {
124958 int c = *zSql;
124959 zSql++;
124960 while( *zSql && *zSql!=c ){ zSql++; }
124961 if( *zSql==0 ) return 0;
124962 token = tkOTHER;
124963 break;
124965 default: {
124966 #ifdef SQLITE_EBCDIC
124967 unsigned char c;
124968 #endif
124969 if( IdChar((u8)*zSql) ){
124970 /* Keywords and unquoted identifiers */
124971 int nId;
124972 for(nId=1; IdChar(zSql[nId]); nId++){}
124973 #ifdef SQLITE_OMIT_TRIGGER
124974 token = tkOTHER;
124975 #else
124976 switch( *zSql ){
124977 case 'c': case 'C': {
124978 if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
124979 token = tkCREATE;
124980 }else{
124981 token = tkOTHER;
124983 break;
124985 case 't': case 'T': {
124986 if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
124987 token = tkTRIGGER;
124988 }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
124989 token = tkTEMP;
124990 }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
124991 token = tkTEMP;
124992 }else{
124993 token = tkOTHER;
124995 break;
124997 case 'e': case 'E': {
124998 if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
124999 token = tkEND;
125000 }else
125001 #ifndef SQLITE_OMIT_EXPLAIN
125002 if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
125003 token = tkEXPLAIN;
125004 }else
125005 #endif
125007 token = tkOTHER;
125009 break;
125011 default: {
125012 token = tkOTHER;
125013 break;
125016 #endif /* SQLITE_OMIT_TRIGGER */
125017 zSql += nId-1;
125018 }else{
125019 /* Operators and special symbols */
125020 token = tkOTHER;
125022 break;
125025 state = trans[state][token];
125026 zSql++;
125028 return state==1;
125031 #ifndef SQLITE_OMIT_UTF16
125033 ** This routine is the same as the sqlite3_complete() routine described
125034 ** above, except that the parameter is required to be UTF-16 encoded, not
125035 ** UTF-8.
125037 SQLITE_API int sqlite3_complete16(const void *zSql){
125038 sqlite3_value *pVal;
125039 char const *zSql8;
125040 int rc = SQLITE_NOMEM;
125042 #ifndef SQLITE_OMIT_AUTOINIT
125043 rc = sqlite3_initialize();
125044 if( rc ) return rc;
125045 #endif
125046 pVal = sqlite3ValueNew(0);
125047 sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
125048 zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
125049 if( zSql8 ){
125050 rc = sqlite3_complete(zSql8);
125051 }else{
125052 rc = SQLITE_NOMEM;
125054 sqlite3ValueFree(pVal);
125055 return sqlite3ApiExit(0, rc);
125057 #endif /* SQLITE_OMIT_UTF16 */
125058 #endif /* SQLITE_OMIT_COMPLETE */
125060 /************** End of complete.c ********************************************/
125061 /************** Begin file main.c ********************************************/
125063 ** 2001 September 15
125065 ** The author disclaims copyright to this source code. In place of
125066 ** a legal notice, here is a blessing:
125068 ** May you do good and not evil.
125069 ** May you find forgiveness for yourself and forgive others.
125070 ** May you share freely, never taking more than you give.
125072 *************************************************************************
125073 ** Main file for the SQLite library. The routines in this file
125074 ** implement the programmer interface to the library. Routines in
125075 ** other files are for internal use by SQLite and should not be
125076 ** accessed by users of the library.
125079 #ifdef SQLITE_ENABLE_FTS3
125080 /************** Include fts3.h in the middle of main.c ***********************/
125081 /************** Begin file fts3.h ********************************************/
125083 ** 2006 Oct 10
125085 ** The author disclaims copyright to this source code. In place of
125086 ** a legal notice, here is a blessing:
125088 ** May you do good and not evil.
125089 ** May you find forgiveness for yourself and forgive others.
125090 ** May you share freely, never taking more than you give.
125092 ******************************************************************************
125094 ** This header file is used by programs that want to link against the
125095 ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
125098 #if 0
125099 extern "C" {
125100 #endif /* __cplusplus */
125102 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
125104 #if 0
125105 } /* extern "C" */
125106 #endif /* __cplusplus */
125108 /************** End of fts3.h ************************************************/
125109 /************** Continuing where we left off in main.c ***********************/
125110 #endif
125111 #ifdef SQLITE_ENABLE_RTREE
125112 /************** Include rtree.h in the middle of main.c **********************/
125113 /************** Begin file rtree.h *******************************************/
125115 ** 2008 May 26
125117 ** The author disclaims copyright to this source code. In place of
125118 ** a legal notice, here is a blessing:
125120 ** May you do good and not evil.
125121 ** May you find forgiveness for yourself and forgive others.
125122 ** May you share freely, never taking more than you give.
125124 ******************************************************************************
125126 ** This header file is used by programs that want to link against the
125127 ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
125130 #if 0
125131 extern "C" {
125132 #endif /* __cplusplus */
125134 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
125136 #if 0
125137 } /* extern "C" */
125138 #endif /* __cplusplus */
125140 /************** End of rtree.h ***********************************************/
125141 /************** Continuing where we left off in main.c ***********************/
125142 #endif
125143 #ifdef SQLITE_ENABLE_ICU
125144 /************** Include sqliteicu.h in the middle of main.c ******************/
125145 /************** Begin file sqliteicu.h ***************************************/
125147 ** 2008 May 26
125149 ** The author disclaims copyright to this source code. In place of
125150 ** a legal notice, here is a blessing:
125152 ** May you do good and not evil.
125153 ** May you find forgiveness for yourself and forgive others.
125154 ** May you share freely, never taking more than you give.
125156 ******************************************************************************
125158 ** This header file is used by programs that want to link against the
125159 ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
125162 #if 0
125163 extern "C" {
125164 #endif /* __cplusplus */
125166 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
125168 #if 0
125169 } /* extern "C" */
125170 #endif /* __cplusplus */
125173 /************** End of sqliteicu.h *******************************************/
125174 /************** Continuing where we left off in main.c ***********************/
125175 #endif
125177 #ifndef SQLITE_AMALGAMATION
125178 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
125179 ** contains the text of SQLITE_VERSION macro.
125181 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
125182 #endif
125184 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
125185 ** a pointer to the to the sqlite3_version[] string constant.
125187 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
125189 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
125190 ** pointer to a string constant whose value is the same as the
125191 ** SQLITE_SOURCE_ID C preprocessor macro.
125193 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
125195 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
125196 ** returns an integer equal to SQLITE_VERSION_NUMBER.
125198 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
125200 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
125201 ** zero if and only if SQLite was compiled with mutexing code omitted due to
125202 ** the SQLITE_THREADSAFE compile-time option being set to 0.
125204 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
125206 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
125208 ** If the following function pointer is not NULL and if
125209 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
125210 ** I/O active are written using this function. These messages
125211 ** are intended for debugging activity only.
125213 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
125214 #endif
125217 ** If the following global variable points to a string which is the
125218 ** name of a directory, then that directory will be used to store
125219 ** temporary files.
125221 ** See also the "PRAGMA temp_store_directory" SQL command.
125223 SQLITE_API char *sqlite3_temp_directory = 0;
125226 ** If the following global variable points to a string which is the
125227 ** name of a directory, then that directory will be used to store
125228 ** all database files specified with a relative pathname.
125230 ** See also the "PRAGMA data_store_directory" SQL command.
125232 SQLITE_API char *sqlite3_data_directory = 0;
125235 ** Initialize SQLite.
125237 ** This routine must be called to initialize the memory allocation,
125238 ** VFS, and mutex subsystems prior to doing any serious work with
125239 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
125240 ** this routine will be called automatically by key routines such as
125241 ** sqlite3_open().
125243 ** This routine is a no-op except on its very first call for the process,
125244 ** or for the first call after a call to sqlite3_shutdown.
125246 ** The first thread to call this routine runs the initialization to
125247 ** completion. If subsequent threads call this routine before the first
125248 ** thread has finished the initialization process, then the subsequent
125249 ** threads must block until the first thread finishes with the initialization.
125251 ** The first thread might call this routine recursively. Recursive
125252 ** calls to this routine should not block, of course. Otherwise the
125253 ** initialization process would never complete.
125255 ** Let X be the first thread to enter this routine. Let Y be some other
125256 ** thread. Then while the initial invocation of this routine by X is
125257 ** incomplete, it is required that:
125259 ** * Calls to this routine from Y must block until the outer-most
125260 ** call by X completes.
125262 ** * Recursive calls to this routine from thread X return immediately
125263 ** without blocking.
125265 SQLITE_API int sqlite3_initialize(void){
125266 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
125267 int rc; /* Result code */
125268 #ifdef SQLITE_EXTRA_INIT
125269 int bRunExtraInit = 0; /* Extra initialization needed */
125270 #endif
125272 #ifdef SQLITE_OMIT_WSD
125273 rc = sqlite3_wsd_init(4096, 24);
125274 if( rc!=SQLITE_OK ){
125275 return rc;
125277 #endif
125279 /* If SQLite is already completely initialized, then this call
125280 ** to sqlite3_initialize() should be a no-op. But the initialization
125281 ** must be complete. So isInit must not be set until the very end
125282 ** of this routine.
125284 if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
125286 /* Make sure the mutex subsystem is initialized. If unable to
125287 ** initialize the mutex subsystem, return early with the error.
125288 ** If the system is so sick that we are unable to allocate a mutex,
125289 ** there is not much SQLite is going to be able to do.
125291 ** The mutex subsystem must take care of serializing its own
125292 ** initialization.
125294 rc = sqlite3MutexInit();
125295 if( rc ) return rc;
125297 /* Initialize the malloc() system and the recursive pInitMutex mutex.
125298 ** This operation is protected by the STATIC_MASTER mutex. Note that
125299 ** MutexAlloc() is called for a static mutex prior to initializing the
125300 ** malloc subsystem - this implies that the allocation of a static
125301 ** mutex must not require support from the malloc subsystem.
125303 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
125304 sqlite3_mutex_enter(pMaster);
125305 sqlite3GlobalConfig.isMutexInit = 1;
125306 if( !sqlite3GlobalConfig.isMallocInit ){
125307 rc = sqlite3MallocInit();
125309 if( rc==SQLITE_OK ){
125310 sqlite3GlobalConfig.isMallocInit = 1;
125311 if( !sqlite3GlobalConfig.pInitMutex ){
125312 sqlite3GlobalConfig.pInitMutex =
125313 sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
125314 if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
125315 rc = SQLITE_NOMEM;
125319 if( rc==SQLITE_OK ){
125320 sqlite3GlobalConfig.nRefInitMutex++;
125322 sqlite3_mutex_leave(pMaster);
125324 /* If rc is not SQLITE_OK at this point, then either the malloc
125325 ** subsystem could not be initialized or the system failed to allocate
125326 ** the pInitMutex mutex. Return an error in either case. */
125327 if( rc!=SQLITE_OK ){
125328 return rc;
125331 /* Do the rest of the initialization under the recursive mutex so
125332 ** that we will be able to handle recursive calls into
125333 ** sqlite3_initialize(). The recursive calls normally come through
125334 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
125335 ** recursive calls might also be possible.
125337 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
125338 ** to the xInit method, so the xInit method need not be threadsafe.
125340 ** The following mutex is what serializes access to the appdef pcache xInit
125341 ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
125342 ** call to sqlite3PcacheInitialize().
125344 sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
125345 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
125346 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
125347 sqlite3GlobalConfig.inProgress = 1;
125348 memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
125349 sqlite3RegisterGlobalFunctions();
125350 if( sqlite3GlobalConfig.isPCacheInit==0 ){
125351 rc = sqlite3PcacheInitialize();
125353 if( rc==SQLITE_OK ){
125354 sqlite3GlobalConfig.isPCacheInit = 1;
125355 rc = sqlite3OsInit();
125357 if( rc==SQLITE_OK ){
125358 sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
125359 sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
125360 sqlite3GlobalConfig.isInit = 1;
125361 #ifdef SQLITE_EXTRA_INIT
125362 bRunExtraInit = 1;
125363 #endif
125365 sqlite3GlobalConfig.inProgress = 0;
125367 sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
125369 /* Go back under the static mutex and clean up the recursive
125370 ** mutex to prevent a resource leak.
125372 sqlite3_mutex_enter(pMaster);
125373 sqlite3GlobalConfig.nRefInitMutex--;
125374 if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
125375 assert( sqlite3GlobalConfig.nRefInitMutex==0 );
125376 sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
125377 sqlite3GlobalConfig.pInitMutex = 0;
125379 sqlite3_mutex_leave(pMaster);
125381 /* The following is just a sanity check to make sure SQLite has
125382 ** been compiled correctly. It is important to run this code, but
125383 ** we don't want to run it too often and soak up CPU cycles for no
125384 ** reason. So we run it once during initialization.
125386 #ifndef NDEBUG
125387 #ifndef SQLITE_OMIT_FLOATING_POINT
125388 /* This section of code's only "output" is via assert() statements. */
125389 if ( rc==SQLITE_OK ){
125390 u64 x = (((u64)1)<<63)-1;
125391 double y;
125392 assert(sizeof(x)==8);
125393 assert(sizeof(x)==sizeof(y));
125394 memcpy(&y, &x, 8);
125395 assert( sqlite3IsNaN(y) );
125397 #endif
125398 #endif
125400 /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
125401 ** compile-time option.
125403 #ifdef SQLITE_EXTRA_INIT
125404 if( bRunExtraInit ){
125405 int SQLITE_EXTRA_INIT(const char*);
125406 rc = SQLITE_EXTRA_INIT(0);
125408 #endif
125410 return rc;
125414 ** Undo the effects of sqlite3_initialize(). Must not be called while
125415 ** there are outstanding database connections or memory allocations or
125416 ** while any part of SQLite is otherwise in use in any thread. This
125417 ** routine is not threadsafe. But it is safe to invoke this routine
125418 ** on when SQLite is already shut down. If SQLite is already shut down
125419 ** when this routine is invoked, then this routine is a harmless no-op.
125421 SQLITE_API int sqlite3_shutdown(void){
125422 if( sqlite3GlobalConfig.isInit ){
125423 #ifdef SQLITE_EXTRA_SHUTDOWN
125424 void SQLITE_EXTRA_SHUTDOWN(void);
125425 SQLITE_EXTRA_SHUTDOWN();
125426 #endif
125427 sqlite3_os_end();
125428 sqlite3_reset_auto_extension();
125429 sqlite3GlobalConfig.isInit = 0;
125431 if( sqlite3GlobalConfig.isPCacheInit ){
125432 sqlite3PcacheShutdown();
125433 sqlite3GlobalConfig.isPCacheInit = 0;
125435 if( sqlite3GlobalConfig.isMallocInit ){
125436 sqlite3MallocEnd();
125437 sqlite3GlobalConfig.isMallocInit = 0;
125439 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
125440 /* The heap subsystem has now been shutdown and these values are supposed
125441 ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
125442 ** which would rely on that heap subsystem; therefore, make sure these
125443 ** values cannot refer to heap memory that was just invalidated when the
125444 ** heap subsystem was shutdown. This is only done if the current call to
125445 ** this function resulted in the heap subsystem actually being shutdown.
125447 sqlite3_data_directory = 0;
125448 sqlite3_temp_directory = 0;
125449 #endif
125451 if( sqlite3GlobalConfig.isMutexInit ){
125452 sqlite3MutexEnd();
125453 sqlite3GlobalConfig.isMutexInit = 0;
125456 return SQLITE_OK;
125460 ** This API allows applications to modify the global configuration of
125461 ** the SQLite library at run-time.
125463 ** This routine should only be called when there are no outstanding
125464 ** database connections or memory allocations. This routine is not
125465 ** threadsafe. Failure to heed these warnings can lead to unpredictable
125466 ** behavior.
125468 SQLITE_API int sqlite3_config(int op, ...){
125469 va_list ap;
125470 int rc = SQLITE_OK;
125472 /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
125473 ** the SQLite library is in use. */
125474 if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
125476 va_start(ap, op);
125477 switch( op ){
125479 /* Mutex configuration options are only available in a threadsafe
125480 ** compile.
125482 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
125483 case SQLITE_CONFIG_SINGLETHREAD: {
125484 /* Disable all mutexing */
125485 sqlite3GlobalConfig.bCoreMutex = 0;
125486 sqlite3GlobalConfig.bFullMutex = 0;
125487 break;
125489 case SQLITE_CONFIG_MULTITHREAD: {
125490 /* Disable mutexing of database connections */
125491 /* Enable mutexing of core data structures */
125492 sqlite3GlobalConfig.bCoreMutex = 1;
125493 sqlite3GlobalConfig.bFullMutex = 0;
125494 break;
125496 case SQLITE_CONFIG_SERIALIZED: {
125497 /* Enable all mutexing */
125498 sqlite3GlobalConfig.bCoreMutex = 1;
125499 sqlite3GlobalConfig.bFullMutex = 1;
125500 break;
125502 case SQLITE_CONFIG_MUTEX: {
125503 /* Specify an alternative mutex implementation */
125504 sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
125505 break;
125507 case SQLITE_CONFIG_GETMUTEX: {
125508 /* Retrieve the current mutex implementation */
125509 *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
125510 break;
125512 #endif
125515 case SQLITE_CONFIG_MALLOC: {
125516 /* Specify an alternative malloc implementation */
125517 sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
125518 break;
125520 case SQLITE_CONFIG_GETMALLOC: {
125521 /* Retrieve the current malloc() implementation */
125522 if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
125523 *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
125524 break;
125526 case SQLITE_CONFIG_MEMSTATUS: {
125527 /* Enable or disable the malloc status collection */
125528 sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
125529 break;
125531 case SQLITE_CONFIG_SCRATCH: {
125532 /* Designate a buffer for scratch memory space */
125533 sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
125534 sqlite3GlobalConfig.szScratch = va_arg(ap, int);
125535 sqlite3GlobalConfig.nScratch = va_arg(ap, int);
125536 break;
125538 case SQLITE_CONFIG_PAGECACHE: {
125539 /* Designate a buffer for page cache memory space */
125540 sqlite3GlobalConfig.pPage = va_arg(ap, void*);
125541 sqlite3GlobalConfig.szPage = va_arg(ap, int);
125542 sqlite3GlobalConfig.nPage = va_arg(ap, int);
125543 break;
125546 case SQLITE_CONFIG_PCACHE: {
125547 /* no-op */
125548 break;
125550 case SQLITE_CONFIG_GETPCACHE: {
125551 /* now an error */
125552 rc = SQLITE_ERROR;
125553 break;
125556 case SQLITE_CONFIG_PCACHE2: {
125557 /* Specify an alternative page cache implementation */
125558 sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
125559 break;
125561 case SQLITE_CONFIG_GETPCACHE2: {
125562 if( sqlite3GlobalConfig.pcache2.xInit==0 ){
125563 sqlite3PCacheSetDefault();
125565 *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
125566 break;
125569 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
125570 case SQLITE_CONFIG_HEAP: {
125571 /* Designate a buffer for heap memory space */
125572 sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
125573 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
125574 sqlite3GlobalConfig.mnReq = va_arg(ap, int);
125576 if( sqlite3GlobalConfig.mnReq<1 ){
125577 sqlite3GlobalConfig.mnReq = 1;
125578 }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
125579 /* cap min request size at 2^12 */
125580 sqlite3GlobalConfig.mnReq = (1<<12);
125583 if( sqlite3GlobalConfig.pHeap==0 ){
125584 /* If the heap pointer is NULL, then restore the malloc implementation
125585 ** back to NULL pointers too. This will cause the malloc to go
125586 ** back to its default implementation when sqlite3_initialize() is
125587 ** run.
125589 memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
125590 }else{
125591 /* The heap pointer is not NULL, then install one of the
125592 ** mem5.c/mem3.c methods. The enclosing #if guarantees at
125593 ** least one of these methods is currently enabled.
125595 #ifdef SQLITE_ENABLE_MEMSYS3
125596 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
125597 #endif
125598 #ifdef SQLITE_ENABLE_MEMSYS5
125599 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
125600 #endif
125602 break;
125604 #endif
125606 case SQLITE_CONFIG_LOOKASIDE: {
125607 sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
125608 sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
125609 break;
125612 /* Record a pointer to the logger function and its first argument.
125613 ** The default is NULL. Logging is disabled if the function pointer is
125614 ** NULL.
125616 case SQLITE_CONFIG_LOG: {
125617 /* MSVC is picky about pulling func ptrs from va lists.
125618 ** http://support.microsoft.com/kb/47961
125619 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
125621 typedef void(*LOGFUNC_t)(void*,int,const char*);
125622 sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
125623 sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
125624 break;
125627 /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
125628 ** can be changed at start-time using the
125629 ** sqlite3_config(SQLITE_CONFIG_URI,1) or
125630 ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
125632 case SQLITE_CONFIG_URI: {
125633 sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
125634 break;
125637 case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
125638 sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
125639 break;
125642 #ifdef SQLITE_ENABLE_SQLLOG
125643 case SQLITE_CONFIG_SQLLOG: {
125644 typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
125645 sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
125646 sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
125647 break;
125649 #endif
125651 case SQLITE_CONFIG_MMAP_SIZE: {
125652 sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
125653 sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
125654 if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
125655 mxMmap = SQLITE_MAX_MMAP_SIZE;
125657 sqlite3GlobalConfig.mxMmap = mxMmap;
125658 if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
125659 if( szMmap>mxMmap) szMmap = mxMmap;
125660 sqlite3GlobalConfig.szMmap = szMmap;
125661 break;
125664 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC)
125665 case SQLITE_CONFIG_WIN32_HEAPSIZE: {
125666 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
125667 break;
125669 #endif
125671 default: {
125672 rc = SQLITE_ERROR;
125673 break;
125676 va_end(ap);
125677 return rc;
125681 ** Set up the lookaside buffers for a database connection.
125682 ** Return SQLITE_OK on success.
125683 ** If lookaside is already active, return SQLITE_BUSY.
125685 ** The sz parameter is the number of bytes in each lookaside slot.
125686 ** The cnt parameter is the number of slots. If pStart is NULL the
125687 ** space for the lookaside memory is obtained from sqlite3_malloc().
125688 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
125689 ** the lookaside memory.
125691 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
125692 void *pStart;
125693 if( db->lookaside.nOut ){
125694 return SQLITE_BUSY;
125696 /* Free any existing lookaside buffer for this handle before
125697 ** allocating a new one so we don't have to have space for
125698 ** both at the same time.
125700 if( db->lookaside.bMalloced ){
125701 sqlite3_free(db->lookaside.pStart);
125703 /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
125704 ** than a pointer to be useful.
125706 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
125707 if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
125708 if( cnt<0 ) cnt = 0;
125709 if( sz==0 || cnt==0 ){
125710 sz = 0;
125711 pStart = 0;
125712 }else if( pBuf==0 ){
125713 sqlite3BeginBenignMalloc();
125714 pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
125715 sqlite3EndBenignMalloc();
125716 if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
125717 }else{
125718 pStart = pBuf;
125720 db->lookaside.pStart = pStart;
125721 db->lookaside.pFree = 0;
125722 db->lookaside.sz = (u16)sz;
125723 if( pStart ){
125724 int i;
125725 LookasideSlot *p;
125726 assert( sz > (int)sizeof(LookasideSlot*) );
125727 p = (LookasideSlot*)pStart;
125728 for(i=cnt-1; i>=0; i--){
125729 p->pNext = db->lookaside.pFree;
125730 db->lookaside.pFree = p;
125731 p = (LookasideSlot*)&((u8*)p)[sz];
125733 db->lookaside.pEnd = p;
125734 db->lookaside.bEnabled = 1;
125735 db->lookaside.bMalloced = pBuf==0 ?1:0;
125736 }else{
125737 db->lookaside.pStart = db;
125738 db->lookaside.pEnd = db;
125739 db->lookaside.bEnabled = 0;
125740 db->lookaside.bMalloced = 0;
125742 return SQLITE_OK;
125746 ** Return the mutex associated with a database connection.
125748 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
125749 return db->mutex;
125753 ** Free up as much memory as we can from the given database
125754 ** connection.
125756 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
125757 int i;
125758 sqlite3_mutex_enter(db->mutex);
125759 sqlite3BtreeEnterAll(db);
125760 for(i=0; i<db->nDb; i++){
125761 Btree *pBt = db->aDb[i].pBt;
125762 if( pBt ){
125763 Pager *pPager = sqlite3BtreePager(pBt);
125764 sqlite3PagerShrink(pPager);
125767 sqlite3BtreeLeaveAll(db);
125768 sqlite3_mutex_leave(db->mutex);
125769 return SQLITE_OK;
125773 ** Configuration settings for an individual database connection
125775 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
125776 va_list ap;
125777 int rc;
125778 va_start(ap, op);
125779 switch( op ){
125780 case SQLITE_DBCONFIG_LOOKASIDE: {
125781 void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
125782 int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
125783 int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
125784 rc = setupLookaside(db, pBuf, sz, cnt);
125785 break;
125787 default: {
125788 static const struct {
125789 int op; /* The opcode */
125790 u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
125791 } aFlagOp[] = {
125792 { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
125793 { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
125795 unsigned int i;
125796 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
125797 for(i=0; i<ArraySize(aFlagOp); i++){
125798 if( aFlagOp[i].op==op ){
125799 int onoff = va_arg(ap, int);
125800 int *pRes = va_arg(ap, int*);
125801 int oldFlags = db->flags;
125802 if( onoff>0 ){
125803 db->flags |= aFlagOp[i].mask;
125804 }else if( onoff==0 ){
125805 db->flags &= ~aFlagOp[i].mask;
125807 if( oldFlags!=db->flags ){
125808 sqlite3ExpirePreparedStatements(db);
125810 if( pRes ){
125811 *pRes = (db->flags & aFlagOp[i].mask)!=0;
125813 rc = SQLITE_OK;
125814 break;
125817 break;
125820 va_end(ap);
125821 return rc;
125826 ** Return true if the buffer z[0..n-1] contains all spaces.
125828 static int allSpaces(const char *z, int n){
125829 while( n>0 && z[n-1]==' ' ){ n--; }
125830 return n==0;
125834 ** This is the default collating function named "BINARY" which is always
125835 ** available.
125837 ** If the padFlag argument is not NULL then space padding at the end
125838 ** of strings is ignored. This implements the RTRIM collation.
125840 static int binCollFunc(
125841 void *padFlag,
125842 int nKey1, const void *pKey1,
125843 int nKey2, const void *pKey2
125845 int rc, n;
125846 n = nKey1<nKey2 ? nKey1 : nKey2;
125847 rc = memcmp(pKey1, pKey2, n);
125848 if( rc==0 ){
125849 if( padFlag
125850 && allSpaces(((char*)pKey1)+n, nKey1-n)
125851 && allSpaces(((char*)pKey2)+n, nKey2-n)
125853 /* Leave rc unchanged at 0 */
125854 }else{
125855 rc = nKey1 - nKey2;
125858 return rc;
125862 ** Another built-in collating sequence: NOCASE.
125864 ** This collating sequence is intended to be used for "case independent
125865 ** comparison". SQLite's knowledge of upper and lower case equivalents
125866 ** extends only to the 26 characters used in the English language.
125868 ** At the moment there is only a UTF-8 implementation.
125870 static int nocaseCollatingFunc(
125871 void *NotUsed,
125872 int nKey1, const void *pKey1,
125873 int nKey2, const void *pKey2
125875 int r = sqlite3StrNICmp(
125876 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
125877 UNUSED_PARAMETER(NotUsed);
125878 if( 0==r ){
125879 r = nKey1-nKey2;
125881 return r;
125885 ** Return the ROWID of the most recent insert
125887 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
125888 return db->lastRowid;
125892 ** Return the number of changes in the most recent call to sqlite3_exec().
125894 SQLITE_API int sqlite3_changes(sqlite3 *db){
125895 return db->nChange;
125899 ** Return the number of changes since the database handle was opened.
125901 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
125902 return db->nTotalChange;
125906 ** Close all open savepoints. This function only manipulates fields of the
125907 ** database handle object, it does not close any savepoints that may be open
125908 ** at the b-tree/pager level.
125910 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
125911 while( db->pSavepoint ){
125912 Savepoint *pTmp = db->pSavepoint;
125913 db->pSavepoint = pTmp->pNext;
125914 sqlite3DbFree(db, pTmp);
125916 db->nSavepoint = 0;
125917 db->nStatement = 0;
125918 db->isTransactionSavepoint = 0;
125922 ** Invoke the destructor function associated with FuncDef p, if any. Except,
125923 ** if this is not the last copy of the function, do not invoke it. Multiple
125924 ** copies of a single function are created when create_function() is called
125925 ** with SQLITE_ANY as the encoding.
125927 static void functionDestroy(sqlite3 *db, FuncDef *p){
125928 FuncDestructor *pDestructor = p->pDestructor;
125929 if( pDestructor ){
125930 pDestructor->nRef--;
125931 if( pDestructor->nRef==0 ){
125932 pDestructor->xDestroy(pDestructor->pUserData);
125933 sqlite3DbFree(db, pDestructor);
125939 ** Disconnect all sqlite3_vtab objects that belong to database connection
125940 ** db. This is called when db is being closed.
125942 static void disconnectAllVtab(sqlite3 *db){
125943 #ifndef SQLITE_OMIT_VIRTUALTABLE
125944 int i;
125945 sqlite3BtreeEnterAll(db);
125946 for(i=0; i<db->nDb; i++){
125947 Schema *pSchema = db->aDb[i].pSchema;
125948 if( db->aDb[i].pSchema ){
125949 HashElem *p;
125950 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
125951 Table *pTab = (Table *)sqliteHashData(p);
125952 if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
125956 sqlite3VtabUnlockList(db);
125957 sqlite3BtreeLeaveAll(db);
125958 #else
125959 UNUSED_PARAMETER(db);
125960 #endif
125964 ** Return TRUE if database connection db has unfinalized prepared
125965 ** statements or unfinished sqlite3_backup objects.
125967 static int connectionIsBusy(sqlite3 *db){
125968 int j;
125969 assert( sqlite3_mutex_held(db->mutex) );
125970 if( db->pVdbe ) return 1;
125971 for(j=0; j<db->nDb; j++){
125972 Btree *pBt = db->aDb[j].pBt;
125973 if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
125975 return 0;
125979 ** Close an existing SQLite database
125981 static int sqlite3Close(sqlite3 *db, int forceZombie){
125982 if( !db ){
125983 /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
125984 ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
125985 return SQLITE_OK;
125987 if( !sqlite3SafetyCheckSickOrOk(db) ){
125988 return SQLITE_MISUSE_BKPT;
125990 sqlite3_mutex_enter(db->mutex);
125992 /* Force xDisconnect calls on all virtual tables */
125993 disconnectAllVtab(db);
125995 /* If a transaction is open, the disconnectAllVtab() call above
125996 ** will not have called the xDisconnect() method on any virtual
125997 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
125998 ** call will do so. We need to do this before the check for active
125999 ** SQL statements below, as the v-table implementation may be storing
126000 ** some prepared statements internally.
126002 sqlite3VtabRollback(db);
126004 /* Legacy behavior (sqlite3_close() behavior) is to return
126005 ** SQLITE_BUSY if the connection can not be closed immediately.
126007 if( !forceZombie && connectionIsBusy(db) ){
126008 sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
126009 "statements or unfinished backups");
126010 sqlite3_mutex_leave(db->mutex);
126011 return SQLITE_BUSY;
126014 #ifdef SQLITE_ENABLE_SQLLOG
126015 if( sqlite3GlobalConfig.xSqllog ){
126016 /* Closing the handle. Fourth parameter is passed the value 2. */
126017 sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
126019 #endif
126021 /* Convert the connection into a zombie and then close it.
126023 db->magic = SQLITE_MAGIC_ZOMBIE;
126024 sqlite3LeaveMutexAndCloseZombie(db);
126025 return SQLITE_OK;
126029 ** Two variations on the public interface for closing a database
126030 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
126031 ** leaves the connection option if there are unfinalized prepared
126032 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
126033 ** version forces the connection to become a zombie if there are
126034 ** unclosed resources, and arranges for deallocation when the last
126035 ** prepare statement or sqlite3_backup closes.
126037 SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
126038 SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
126042 ** Close the mutex on database connection db.
126044 ** Furthermore, if database connection db is a zombie (meaning that there
126045 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
126046 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
126047 ** finished, then free all resources.
126049 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
126050 HashElem *i; /* Hash table iterator */
126051 int j;
126053 /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
126054 ** or if the connection has not yet been closed by sqlite3_close_v2(),
126055 ** then just leave the mutex and return.
126057 if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
126058 sqlite3_mutex_leave(db->mutex);
126059 return;
126062 /* If we reach this point, it means that the database connection has
126063 ** closed all sqlite3_stmt and sqlite3_backup objects and has been
126064 ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
126065 ** go ahead and free all resources.
126068 /* If a transaction is open, roll it back. This also ensures that if
126069 ** any database schemas have been modified by an uncommitted transaction
126070 ** they are reset. And that the required b-tree mutex is held to make
126071 ** the pager rollback and schema reset an atomic operation. */
126072 sqlite3RollbackAll(db, SQLITE_OK);
126074 /* Free any outstanding Savepoint structures. */
126075 sqlite3CloseSavepoints(db);
126077 /* Close all database connections */
126078 for(j=0; j<db->nDb; j++){
126079 struct Db *pDb = &db->aDb[j];
126080 if( pDb->pBt ){
126081 if( pDb->pSchema ){
126082 /* Must clear the KeyInfo cache. See ticket [e4a18565a36884b00edf] */
126083 sqlite3BtreeEnter(pDb->pBt);
126084 for(i=sqliteHashFirst(&pDb->pSchema->idxHash); i; i=sqliteHashNext(i)){
126085 Index *pIdx = sqliteHashData(i);
126086 sqlite3KeyInfoUnref(pIdx->pKeyInfo);
126087 pIdx->pKeyInfo = 0;
126089 sqlite3BtreeLeave(pDb->pBt);
126091 sqlite3BtreeClose(pDb->pBt);
126092 pDb->pBt = 0;
126093 if( j!=1 ){
126094 pDb->pSchema = 0;
126098 /* Clear the TEMP schema separately and last */
126099 if( db->aDb[1].pSchema ){
126100 sqlite3SchemaClear(db->aDb[1].pSchema);
126102 sqlite3VtabUnlockList(db);
126104 /* Free up the array of auxiliary databases */
126105 sqlite3CollapseDatabaseArray(db);
126106 assert( db->nDb<=2 );
126107 assert( db->aDb==db->aDbStatic );
126109 /* Tell the code in notify.c that the connection no longer holds any
126110 ** locks and does not require any further unlock-notify callbacks.
126112 sqlite3ConnectionClosed(db);
126114 for(j=0; j<ArraySize(db->aFunc.a); j++){
126115 FuncDef *pNext, *pHash, *p;
126116 for(p=db->aFunc.a[j]; p; p=pHash){
126117 pHash = p->pHash;
126118 while( p ){
126119 functionDestroy(db, p);
126120 pNext = p->pNext;
126121 sqlite3DbFree(db, p);
126122 p = pNext;
126126 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
126127 CollSeq *pColl = (CollSeq *)sqliteHashData(i);
126128 /* Invoke any destructors registered for collation sequence user data. */
126129 for(j=0; j<3; j++){
126130 if( pColl[j].xDel ){
126131 pColl[j].xDel(pColl[j].pUser);
126134 sqlite3DbFree(db, pColl);
126136 sqlite3HashClear(&db->aCollSeq);
126137 #ifndef SQLITE_OMIT_VIRTUALTABLE
126138 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
126139 Module *pMod = (Module *)sqliteHashData(i);
126140 if( pMod->xDestroy ){
126141 pMod->xDestroy(pMod->pAux);
126143 sqlite3DbFree(db, pMod);
126145 sqlite3HashClear(&db->aModule);
126146 #endif
126148 sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
126149 sqlite3ValueFree(db->pErr);
126150 sqlite3CloseExtensions(db);
126151 #if SQLITE_USER_AUTHENTICATION
126152 sqlite3_free(db->auth.zAuthUser);
126153 sqlite3_free(db->auth.zAuthPW);
126154 #endif
126156 db->magic = SQLITE_MAGIC_ERROR;
126158 /* The temp-database schema is allocated differently from the other schema
126159 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
126160 ** So it needs to be freed here. Todo: Why not roll the temp schema into
126161 ** the same sqliteMalloc() as the one that allocates the database
126162 ** structure?
126164 sqlite3DbFree(db, db->aDb[1].pSchema);
126165 sqlite3_mutex_leave(db->mutex);
126166 db->magic = SQLITE_MAGIC_CLOSED;
126167 sqlite3_mutex_free(db->mutex);
126168 assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
126169 if( db->lookaside.bMalloced ){
126170 sqlite3_free(db->lookaside.pStart);
126172 sqlite3_free(db);
126176 ** Rollback all database files. If tripCode is not SQLITE_OK, then
126177 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
126178 ** breaker") and made to return tripCode if there are any further
126179 ** attempts to use that cursor. Read cursors remain open and valid
126180 ** but are "saved" in case the table pages are moved around.
126182 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
126183 int i;
126184 int inTrans = 0;
126185 int schemaChange;
126186 assert( sqlite3_mutex_held(db->mutex) );
126187 sqlite3BeginBenignMalloc();
126189 /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
126190 ** This is important in case the transaction being rolled back has
126191 ** modified the database schema. If the b-tree mutexes are not taken
126192 ** here, then another shared-cache connection might sneak in between
126193 ** the database rollback and schema reset, which can cause false
126194 ** corruption reports in some cases. */
126195 sqlite3BtreeEnterAll(db);
126196 schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
126198 for(i=0; i<db->nDb; i++){
126199 Btree *p = db->aDb[i].pBt;
126200 if( p ){
126201 if( sqlite3BtreeIsInTrans(p) ){
126202 inTrans = 1;
126204 sqlite3BtreeRollback(p, tripCode, !schemaChange);
126207 sqlite3VtabRollback(db);
126208 sqlite3EndBenignMalloc();
126210 if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
126211 sqlite3ExpirePreparedStatements(db);
126212 sqlite3ResetAllSchemasOfConnection(db);
126214 sqlite3BtreeLeaveAll(db);
126216 /* Any deferred constraint violations have now been resolved. */
126217 db->nDeferredCons = 0;
126218 db->nDeferredImmCons = 0;
126219 db->flags &= ~SQLITE_DeferFKs;
126221 /* If one has been configured, invoke the rollback-hook callback */
126222 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
126223 db->xRollbackCallback(db->pRollbackArg);
126228 ** Return a static string containing the name corresponding to the error code
126229 ** specified in the argument.
126231 #if (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) || defined(SQLITE_TEST)
126232 SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
126233 const char *zName = 0;
126234 int i, origRc = rc;
126235 for(i=0; i<2 && zName==0; i++, rc &= 0xff){
126236 switch( rc ){
126237 case SQLITE_OK: zName = "SQLITE_OK"; break;
126238 case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
126239 case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
126240 case SQLITE_PERM: zName = "SQLITE_PERM"; break;
126241 case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
126242 case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
126243 case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
126244 case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
126245 case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
126246 case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
126247 case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
126248 case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
126249 case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
126250 case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
126251 case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
126252 case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
126253 case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
126254 case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
126255 case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
126256 case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
126257 case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
126258 case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
126259 case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
126260 case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
126261 case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
126262 case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
126263 case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
126264 case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
126265 case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
126266 case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
126267 case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
126268 case SQLITE_IOERR_CHECKRESERVEDLOCK:
126269 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
126270 case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
126271 case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
126272 case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
126273 case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
126274 case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
126275 case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
126276 case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
126277 case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
126278 case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
126279 case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
126280 case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
126281 case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
126282 case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
126283 case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
126284 case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
126285 case SQLITE_FULL: zName = "SQLITE_FULL"; break;
126286 case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
126287 case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
126288 case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
126289 case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
126290 case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
126291 case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
126292 case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
126293 case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
126294 case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
126295 case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
126296 case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
126297 case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
126298 case SQLITE_CONSTRAINT_FOREIGNKEY:
126299 zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
126300 case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
126301 case SQLITE_CONSTRAINT_PRIMARYKEY:
126302 zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
126303 case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
126304 case SQLITE_CONSTRAINT_COMMITHOOK:
126305 zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
126306 case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
126307 case SQLITE_CONSTRAINT_FUNCTION:
126308 zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
126309 case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
126310 case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
126311 case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
126312 case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
126313 case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
126314 case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
126315 case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
126316 case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
126317 case SQLITE_ROW: zName = "SQLITE_ROW"; break;
126318 case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
126319 case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
126320 case SQLITE_NOTICE_RECOVER_ROLLBACK:
126321 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
126322 case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
126323 case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
126324 case SQLITE_DONE: zName = "SQLITE_DONE"; break;
126327 if( zName==0 ){
126328 static char zBuf[50];
126329 sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
126330 zName = zBuf;
126332 return zName;
126334 #endif
126337 ** Return a static string that describes the kind of error specified in the
126338 ** argument.
126340 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
126341 static const char* const aMsg[] = {
126342 /* SQLITE_OK */ "not an error",
126343 /* SQLITE_ERROR */ "SQL logic error or missing database",
126344 /* SQLITE_INTERNAL */ 0,
126345 /* SQLITE_PERM */ "access permission denied",
126346 /* SQLITE_ABORT */ "callback requested query abort",
126347 /* SQLITE_BUSY */ "database is locked",
126348 /* SQLITE_LOCKED */ "database table is locked",
126349 /* SQLITE_NOMEM */ "out of memory",
126350 /* SQLITE_READONLY */ "attempt to write a readonly database",
126351 /* SQLITE_INTERRUPT */ "interrupted",
126352 /* SQLITE_IOERR */ "disk I/O error",
126353 /* SQLITE_CORRUPT */ "database disk image is malformed",
126354 /* SQLITE_NOTFOUND */ "unknown operation",
126355 /* SQLITE_FULL */ "database or disk is full",
126356 /* SQLITE_CANTOPEN */ "unable to open database file",
126357 /* SQLITE_PROTOCOL */ "locking protocol",
126358 /* SQLITE_EMPTY */ "table contains no data",
126359 /* SQLITE_SCHEMA */ "database schema has changed",
126360 /* SQLITE_TOOBIG */ "string or blob too big",
126361 /* SQLITE_CONSTRAINT */ "constraint failed",
126362 /* SQLITE_MISMATCH */ "datatype mismatch",
126363 /* SQLITE_MISUSE */ "library routine called out of sequence",
126364 /* SQLITE_NOLFS */ "large file support is disabled",
126365 /* SQLITE_AUTH */ "authorization denied",
126366 /* SQLITE_FORMAT */ "auxiliary database format error",
126367 /* SQLITE_RANGE */ "bind or column index out of range",
126368 /* SQLITE_NOTADB */ "file is encrypted or is not a database",
126370 const char *zErr = "unknown error";
126371 switch( rc ){
126372 case SQLITE_ABORT_ROLLBACK: {
126373 zErr = "abort due to ROLLBACK";
126374 break;
126376 default: {
126377 rc &= 0xff;
126378 if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
126379 zErr = aMsg[rc];
126381 break;
126384 return zErr;
126388 ** This routine implements a busy callback that sleeps and tries
126389 ** again until a timeout value is reached. The timeout value is
126390 ** an integer number of milliseconds passed in as the first
126391 ** argument.
126393 static int sqliteDefaultBusyCallback(
126394 void *ptr, /* Database connection */
126395 int count /* Number of times table has been busy */
126397 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
126398 static const u8 delays[] =
126399 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
126400 static const u8 totals[] =
126401 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
126402 # define NDELAY ArraySize(delays)
126403 sqlite3 *db = (sqlite3 *)ptr;
126404 int timeout = db->busyTimeout;
126405 int delay, prior;
126407 assert( count>=0 );
126408 if( count < NDELAY ){
126409 delay = delays[count];
126410 prior = totals[count];
126411 }else{
126412 delay = delays[NDELAY-1];
126413 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
126415 if( prior + delay > timeout ){
126416 delay = timeout - prior;
126417 if( delay<=0 ) return 0;
126419 sqlite3OsSleep(db->pVfs, delay*1000);
126420 return 1;
126421 #else
126422 sqlite3 *db = (sqlite3 *)ptr;
126423 int timeout = ((sqlite3 *)ptr)->busyTimeout;
126424 if( (count+1)*1000 > timeout ){
126425 return 0;
126427 sqlite3OsSleep(db->pVfs, 1000000);
126428 return 1;
126429 #endif
126433 ** Invoke the given busy handler.
126435 ** This routine is called when an operation failed with a lock.
126436 ** If this routine returns non-zero, the lock is retried. If it
126437 ** returns 0, the operation aborts with an SQLITE_BUSY error.
126439 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
126440 int rc;
126441 if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
126442 rc = p->xFunc(p->pArg, p->nBusy);
126443 if( rc==0 ){
126444 p->nBusy = -1;
126445 }else{
126446 p->nBusy++;
126448 return rc;
126452 ** This routine sets the busy callback for an Sqlite database to the
126453 ** given callback function with the given argument.
126455 SQLITE_API int sqlite3_busy_handler(
126456 sqlite3 *db,
126457 int (*xBusy)(void*,int),
126458 void *pArg
126460 sqlite3_mutex_enter(db->mutex);
126461 db->busyHandler.xFunc = xBusy;
126462 db->busyHandler.pArg = pArg;
126463 db->busyHandler.nBusy = 0;
126464 db->busyTimeout = 0;
126465 sqlite3_mutex_leave(db->mutex);
126466 return SQLITE_OK;
126469 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
126471 ** This routine sets the progress callback for an Sqlite database to the
126472 ** given callback function with the given argument. The progress callback will
126473 ** be invoked every nOps opcodes.
126475 SQLITE_API void sqlite3_progress_handler(
126476 sqlite3 *db,
126477 int nOps,
126478 int (*xProgress)(void*),
126479 void *pArg
126481 sqlite3_mutex_enter(db->mutex);
126482 if( nOps>0 ){
126483 db->xProgress = xProgress;
126484 db->nProgressOps = (unsigned)nOps;
126485 db->pProgressArg = pArg;
126486 }else{
126487 db->xProgress = 0;
126488 db->nProgressOps = 0;
126489 db->pProgressArg = 0;
126491 sqlite3_mutex_leave(db->mutex);
126493 #endif
126497 ** This routine installs a default busy handler that waits for the
126498 ** specified number of milliseconds before returning 0.
126500 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
126501 if( ms>0 ){
126502 sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
126503 db->busyTimeout = ms;
126504 }else{
126505 sqlite3_busy_handler(db, 0, 0);
126507 return SQLITE_OK;
126511 ** Cause any pending operation to stop at its earliest opportunity.
126513 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
126514 db->u1.isInterrupted = 1;
126519 ** This function is exactly the same as sqlite3_create_function(), except
126520 ** that it is designed to be called by internal code. The difference is
126521 ** that if a malloc() fails in sqlite3_create_function(), an error code
126522 ** is returned and the mallocFailed flag cleared.
126524 SQLITE_PRIVATE int sqlite3CreateFunc(
126525 sqlite3 *db,
126526 const char *zFunctionName,
126527 int nArg,
126528 int enc,
126529 void *pUserData,
126530 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
126531 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
126532 void (*xFinal)(sqlite3_context*),
126533 FuncDestructor *pDestructor
126535 FuncDef *p;
126536 int nName;
126537 int extraFlags;
126539 assert( sqlite3_mutex_held(db->mutex) );
126540 if( zFunctionName==0 ||
126541 (xFunc && (xFinal || xStep)) ||
126542 (!xFunc && (xFinal && !xStep)) ||
126543 (!xFunc && (!xFinal && xStep)) ||
126544 (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
126545 (255<(nName = sqlite3Strlen30( zFunctionName))) ){
126546 return SQLITE_MISUSE_BKPT;
126549 assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
126550 extraFlags = enc & SQLITE_DETERMINISTIC;
126551 enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
126553 #ifndef SQLITE_OMIT_UTF16
126554 /* If SQLITE_UTF16 is specified as the encoding type, transform this
126555 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
126556 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
126558 ** If SQLITE_ANY is specified, add three versions of the function
126559 ** to the hash table.
126561 if( enc==SQLITE_UTF16 ){
126562 enc = SQLITE_UTF16NATIVE;
126563 }else if( enc==SQLITE_ANY ){
126564 int rc;
126565 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
126566 pUserData, xFunc, xStep, xFinal, pDestructor);
126567 if( rc==SQLITE_OK ){
126568 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
126569 pUserData, xFunc, xStep, xFinal, pDestructor);
126571 if( rc!=SQLITE_OK ){
126572 return rc;
126574 enc = SQLITE_UTF16BE;
126576 #else
126577 enc = SQLITE_UTF8;
126578 #endif
126580 /* Check if an existing function is being overridden or deleted. If so,
126581 ** and there are active VMs, then return SQLITE_BUSY. If a function
126582 ** is being overridden/deleted but there are no active VMs, allow the
126583 ** operation to continue but invalidate all precompiled statements.
126585 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
126586 if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
126587 if( db->nVdbeActive ){
126588 sqlite3ErrorWithMsg(db, SQLITE_BUSY,
126589 "unable to delete/modify user-function due to active statements");
126590 assert( !db->mallocFailed );
126591 return SQLITE_BUSY;
126592 }else{
126593 sqlite3ExpirePreparedStatements(db);
126597 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
126598 assert(p || db->mallocFailed);
126599 if( !p ){
126600 return SQLITE_NOMEM;
126603 /* If an older version of the function with a configured destructor is
126604 ** being replaced invoke the destructor function here. */
126605 functionDestroy(db, p);
126607 if( pDestructor ){
126608 pDestructor->nRef++;
126610 p->pDestructor = pDestructor;
126611 p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
126612 testcase( p->funcFlags & SQLITE_DETERMINISTIC );
126613 p->xFunc = xFunc;
126614 p->xStep = xStep;
126615 p->xFinalize = xFinal;
126616 p->pUserData = pUserData;
126617 p->nArg = (u16)nArg;
126618 return SQLITE_OK;
126622 ** Create new user functions.
126624 SQLITE_API int sqlite3_create_function(
126625 sqlite3 *db,
126626 const char *zFunc,
126627 int nArg,
126628 int enc,
126629 void *p,
126630 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
126631 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
126632 void (*xFinal)(sqlite3_context*)
126634 return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
126635 xFinal, 0);
126638 SQLITE_API int sqlite3_create_function_v2(
126639 sqlite3 *db,
126640 const char *zFunc,
126641 int nArg,
126642 int enc,
126643 void *p,
126644 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
126645 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
126646 void (*xFinal)(sqlite3_context*),
126647 void (*xDestroy)(void *)
126649 int rc = SQLITE_ERROR;
126650 FuncDestructor *pArg = 0;
126651 sqlite3_mutex_enter(db->mutex);
126652 if( xDestroy ){
126653 pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
126654 if( !pArg ){
126655 xDestroy(p);
126656 goto out;
126658 pArg->xDestroy = xDestroy;
126659 pArg->pUserData = p;
126661 rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
126662 if( pArg && pArg->nRef==0 ){
126663 assert( rc!=SQLITE_OK );
126664 xDestroy(p);
126665 sqlite3DbFree(db, pArg);
126669 rc = sqlite3ApiExit(db, rc);
126670 sqlite3_mutex_leave(db->mutex);
126671 return rc;
126674 #ifndef SQLITE_OMIT_UTF16
126675 SQLITE_API int sqlite3_create_function16(
126676 sqlite3 *db,
126677 const void *zFunctionName,
126678 int nArg,
126679 int eTextRep,
126680 void *p,
126681 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
126682 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
126683 void (*xFinal)(sqlite3_context*)
126685 int rc;
126686 char *zFunc8;
126687 sqlite3_mutex_enter(db->mutex);
126688 assert( !db->mallocFailed );
126689 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
126690 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
126691 sqlite3DbFree(db, zFunc8);
126692 rc = sqlite3ApiExit(db, rc);
126693 sqlite3_mutex_leave(db->mutex);
126694 return rc;
126696 #endif
126700 ** Declare that a function has been overloaded by a virtual table.
126702 ** If the function already exists as a regular global function, then
126703 ** this routine is a no-op. If the function does not exist, then create
126704 ** a new one that always throws a run-time error.
126706 ** When virtual tables intend to provide an overloaded function, they
126707 ** should call this routine to make sure the global function exists.
126708 ** A global function must exist in order for name resolution to work
126709 ** properly.
126711 SQLITE_API int sqlite3_overload_function(
126712 sqlite3 *db,
126713 const char *zName,
126714 int nArg
126716 int nName = sqlite3Strlen30(zName);
126717 int rc = SQLITE_OK;
126718 sqlite3_mutex_enter(db->mutex);
126719 if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
126720 rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
126721 0, sqlite3InvalidFunction, 0, 0, 0);
126723 rc = sqlite3ApiExit(db, rc);
126724 sqlite3_mutex_leave(db->mutex);
126725 return rc;
126728 #ifndef SQLITE_OMIT_TRACE
126730 ** Register a trace function. The pArg from the previously registered trace
126731 ** is returned.
126733 ** A NULL trace function means that no tracing is executes. A non-NULL
126734 ** trace is a pointer to a function that is invoked at the start of each
126735 ** SQL statement.
126737 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
126738 void *pOld;
126739 sqlite3_mutex_enter(db->mutex);
126740 pOld = db->pTraceArg;
126741 db->xTrace = xTrace;
126742 db->pTraceArg = pArg;
126743 sqlite3_mutex_leave(db->mutex);
126744 return pOld;
126747 ** Register a profile function. The pArg from the previously registered
126748 ** profile function is returned.
126750 ** A NULL profile function means that no profiling is executes. A non-NULL
126751 ** profile is a pointer to a function that is invoked at the conclusion of
126752 ** each SQL statement that is run.
126754 SQLITE_API void *sqlite3_profile(
126755 sqlite3 *db,
126756 void (*xProfile)(void*,const char*,sqlite_uint64),
126757 void *pArg
126759 void *pOld;
126760 sqlite3_mutex_enter(db->mutex);
126761 pOld = db->pProfileArg;
126762 db->xProfile = xProfile;
126763 db->pProfileArg = pArg;
126764 sqlite3_mutex_leave(db->mutex);
126765 return pOld;
126767 #endif /* SQLITE_OMIT_TRACE */
126770 ** Register a function to be invoked when a transaction commits.
126771 ** If the invoked function returns non-zero, then the commit becomes a
126772 ** rollback.
126774 SQLITE_API void *sqlite3_commit_hook(
126775 sqlite3 *db, /* Attach the hook to this database */
126776 int (*xCallback)(void*), /* Function to invoke on each commit */
126777 void *pArg /* Argument to the function */
126779 void *pOld;
126780 sqlite3_mutex_enter(db->mutex);
126781 pOld = db->pCommitArg;
126782 db->xCommitCallback = xCallback;
126783 db->pCommitArg = pArg;
126784 sqlite3_mutex_leave(db->mutex);
126785 return pOld;
126789 ** Register a callback to be invoked each time a row is updated,
126790 ** inserted or deleted using this database connection.
126792 SQLITE_API void *sqlite3_update_hook(
126793 sqlite3 *db, /* Attach the hook to this database */
126794 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
126795 void *pArg /* Argument to the function */
126797 void *pRet;
126798 sqlite3_mutex_enter(db->mutex);
126799 pRet = db->pUpdateArg;
126800 db->xUpdateCallback = xCallback;
126801 db->pUpdateArg = pArg;
126802 sqlite3_mutex_leave(db->mutex);
126803 return pRet;
126807 ** Register a callback to be invoked each time a transaction is rolled
126808 ** back by this database connection.
126810 SQLITE_API void *sqlite3_rollback_hook(
126811 sqlite3 *db, /* Attach the hook to this database */
126812 void (*xCallback)(void*), /* Callback function */
126813 void *pArg /* Argument to the function */
126815 void *pRet;
126816 sqlite3_mutex_enter(db->mutex);
126817 pRet = db->pRollbackArg;
126818 db->xRollbackCallback = xCallback;
126819 db->pRollbackArg = pArg;
126820 sqlite3_mutex_leave(db->mutex);
126821 return pRet;
126824 #ifndef SQLITE_OMIT_WAL
126826 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
126827 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
126828 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
126829 ** wal_autocheckpoint()).
126831 SQLITE_PRIVATE int sqlite3WalDefaultHook(
126832 void *pClientData, /* Argument */
126833 sqlite3 *db, /* Connection */
126834 const char *zDb, /* Database */
126835 int nFrame /* Size of WAL */
126837 if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
126838 sqlite3BeginBenignMalloc();
126839 sqlite3_wal_checkpoint(db, zDb);
126840 sqlite3EndBenignMalloc();
126842 return SQLITE_OK;
126844 #endif /* SQLITE_OMIT_WAL */
126847 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
126848 ** a database after committing a transaction if there are nFrame or
126849 ** more frames in the log file. Passing zero or a negative value as the
126850 ** nFrame parameter disables automatic checkpoints entirely.
126852 ** The callback registered by this function replaces any existing callback
126853 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
126854 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
126855 ** configured by this function.
126857 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
126858 #ifdef SQLITE_OMIT_WAL
126859 UNUSED_PARAMETER(db);
126860 UNUSED_PARAMETER(nFrame);
126861 #else
126862 if( nFrame>0 ){
126863 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
126864 }else{
126865 sqlite3_wal_hook(db, 0, 0);
126867 #endif
126868 return SQLITE_OK;
126872 ** Register a callback to be invoked each time a transaction is written
126873 ** into the write-ahead-log by this database connection.
126875 SQLITE_API void *sqlite3_wal_hook(
126876 sqlite3 *db, /* Attach the hook to this db handle */
126877 int(*xCallback)(void *, sqlite3*, const char*, int),
126878 void *pArg /* First argument passed to xCallback() */
126880 #ifndef SQLITE_OMIT_WAL
126881 void *pRet;
126882 sqlite3_mutex_enter(db->mutex);
126883 pRet = db->pWalArg;
126884 db->xWalCallback = xCallback;
126885 db->pWalArg = pArg;
126886 sqlite3_mutex_leave(db->mutex);
126887 return pRet;
126888 #else
126889 return 0;
126890 #endif
126894 ** Checkpoint database zDb.
126896 SQLITE_API int sqlite3_wal_checkpoint_v2(
126897 sqlite3 *db, /* Database handle */
126898 const char *zDb, /* Name of attached database (or NULL) */
126899 int eMode, /* SQLITE_CHECKPOINT_* value */
126900 int *pnLog, /* OUT: Size of WAL log in frames */
126901 int *pnCkpt /* OUT: Total number of frames checkpointed */
126903 #ifdef SQLITE_OMIT_WAL
126904 return SQLITE_OK;
126905 #else
126906 int rc; /* Return code */
126907 int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
126909 /* Initialize the output variables to -1 in case an error occurs. */
126910 if( pnLog ) *pnLog = -1;
126911 if( pnCkpt ) *pnCkpt = -1;
126913 assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
126914 assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
126915 assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
126916 if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
126917 return SQLITE_MISUSE;
126920 sqlite3_mutex_enter(db->mutex);
126921 if( zDb && zDb[0] ){
126922 iDb = sqlite3FindDbName(db, zDb);
126924 if( iDb<0 ){
126925 rc = SQLITE_ERROR;
126926 sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
126927 }else{
126928 rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
126929 sqlite3Error(db, rc);
126931 rc = sqlite3ApiExit(db, rc);
126932 sqlite3_mutex_leave(db->mutex);
126933 return rc;
126934 #endif
126939 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
126940 ** to contains a zero-length string, all attached databases are
126941 ** checkpointed.
126943 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
126944 return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
126947 #ifndef SQLITE_OMIT_WAL
126949 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
126950 ** not currently open in WAL mode.
126952 ** If a transaction is open on the database being checkpointed, this
126953 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
126954 ** an error occurs while running the checkpoint, an SQLite error code is
126955 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
126957 ** The mutex on database handle db should be held by the caller. The mutex
126958 ** associated with the specific b-tree being checkpointed is taken by
126959 ** this function while the checkpoint is running.
126961 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
126962 ** checkpointed. If an error is encountered it is returned immediately -
126963 ** no attempt is made to checkpoint any remaining databases.
126965 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
126967 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
126968 int rc = SQLITE_OK; /* Return code */
126969 int i; /* Used to iterate through attached dbs */
126970 int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
126972 assert( sqlite3_mutex_held(db->mutex) );
126973 assert( !pnLog || *pnLog==-1 );
126974 assert( !pnCkpt || *pnCkpt==-1 );
126976 for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
126977 if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
126978 rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
126979 pnLog = 0;
126980 pnCkpt = 0;
126981 if( rc==SQLITE_BUSY ){
126982 bBusy = 1;
126983 rc = SQLITE_OK;
126988 return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
126990 #endif /* SQLITE_OMIT_WAL */
126993 ** This function returns true if main-memory should be used instead of
126994 ** a temporary file for transient pager files and statement journals.
126995 ** The value returned depends on the value of db->temp_store (runtime
126996 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
126997 ** following table describes the relationship between these two values
126998 ** and this functions return value.
127000 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
127001 ** ----------------- -------------- ------------------------------
127002 ** 0 any file (return 0)
127003 ** 1 1 file (return 0)
127004 ** 1 2 memory (return 1)
127005 ** 1 0 file (return 0)
127006 ** 2 1 file (return 0)
127007 ** 2 2 memory (return 1)
127008 ** 2 0 memory (return 1)
127009 ** 3 any memory (return 1)
127011 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
127012 #if SQLITE_TEMP_STORE==1
127013 return ( db->temp_store==2 );
127014 #endif
127015 #if SQLITE_TEMP_STORE==2
127016 return ( db->temp_store!=1 );
127017 #endif
127018 #if SQLITE_TEMP_STORE==3
127019 return 1;
127020 #endif
127021 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
127022 return 0;
127023 #endif
127027 ** Return UTF-8 encoded English language explanation of the most recent
127028 ** error.
127030 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
127031 const char *z;
127032 if( !db ){
127033 return sqlite3ErrStr(SQLITE_NOMEM);
127035 if( !sqlite3SafetyCheckSickOrOk(db) ){
127036 return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
127038 sqlite3_mutex_enter(db->mutex);
127039 if( db->mallocFailed ){
127040 z = sqlite3ErrStr(SQLITE_NOMEM);
127041 }else{
127042 testcase( db->pErr==0 );
127043 z = (char*)sqlite3_value_text(db->pErr);
127044 assert( !db->mallocFailed );
127045 if( z==0 ){
127046 z = sqlite3ErrStr(db->errCode);
127049 sqlite3_mutex_leave(db->mutex);
127050 return z;
127053 #ifndef SQLITE_OMIT_UTF16
127055 ** Return UTF-16 encoded English language explanation of the most recent
127056 ** error.
127058 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
127059 static const u16 outOfMem[] = {
127060 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
127062 static const u16 misuse[] = {
127063 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
127064 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
127065 'c', 'a', 'l', 'l', 'e', 'd', ' ',
127066 'o', 'u', 't', ' ',
127067 'o', 'f', ' ',
127068 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
127071 const void *z;
127072 if( !db ){
127073 return (void *)outOfMem;
127075 if( !sqlite3SafetyCheckSickOrOk(db) ){
127076 return (void *)misuse;
127078 sqlite3_mutex_enter(db->mutex);
127079 if( db->mallocFailed ){
127080 z = (void *)outOfMem;
127081 }else{
127082 z = sqlite3_value_text16(db->pErr);
127083 if( z==0 ){
127084 sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
127085 z = sqlite3_value_text16(db->pErr);
127087 /* A malloc() may have failed within the call to sqlite3_value_text16()
127088 ** above. If this is the case, then the db->mallocFailed flag needs to
127089 ** be cleared before returning. Do this directly, instead of via
127090 ** sqlite3ApiExit(), to avoid setting the database handle error message.
127092 db->mallocFailed = 0;
127094 sqlite3_mutex_leave(db->mutex);
127095 return z;
127097 #endif /* SQLITE_OMIT_UTF16 */
127100 ** Return the most recent error code generated by an SQLite routine. If NULL is
127101 ** passed to this function, we assume a malloc() failed during sqlite3_open().
127103 SQLITE_API int sqlite3_errcode(sqlite3 *db){
127104 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
127105 return SQLITE_MISUSE_BKPT;
127107 if( !db || db->mallocFailed ){
127108 return SQLITE_NOMEM;
127110 return db->errCode & db->errMask;
127112 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
127113 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
127114 return SQLITE_MISUSE_BKPT;
127116 if( !db || db->mallocFailed ){
127117 return SQLITE_NOMEM;
127119 return db->errCode;
127123 ** Return a string that describes the kind of error specified in the
127124 ** argument. For now, this simply calls the internal sqlite3ErrStr()
127125 ** function.
127127 SQLITE_API const char *sqlite3_errstr(int rc){
127128 return sqlite3ErrStr(rc);
127132 ** Invalidate all cached KeyInfo objects for database connection "db"
127134 static void invalidateCachedKeyInfo(sqlite3 *db){
127135 Db *pDb; /* A single database */
127136 int iDb; /* The database index number */
127137 HashElem *k; /* For looping over tables in pDb */
127138 Table *pTab; /* A table in the database */
127139 Index *pIdx; /* Each index */
127141 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
127142 if( pDb->pBt==0 ) continue;
127143 sqlite3BtreeEnter(pDb->pBt);
127144 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
127145 pTab = (Table*)sqliteHashData(k);
127146 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
127147 if( pIdx->pKeyInfo && pIdx->pKeyInfo->db==db ){
127148 sqlite3KeyInfoUnref(pIdx->pKeyInfo);
127149 pIdx->pKeyInfo = 0;
127153 sqlite3BtreeLeave(pDb->pBt);
127158 ** Create a new collating function for database "db". The name is zName
127159 ** and the encoding is enc.
127161 static int createCollation(
127162 sqlite3* db,
127163 const char *zName,
127164 u8 enc,
127165 void* pCtx,
127166 int(*xCompare)(void*,int,const void*,int,const void*),
127167 void(*xDel)(void*)
127169 CollSeq *pColl;
127170 int enc2;
127172 assert( sqlite3_mutex_held(db->mutex) );
127174 /* If SQLITE_UTF16 is specified as the encoding type, transform this
127175 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
127176 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
127178 enc2 = enc;
127179 testcase( enc2==SQLITE_UTF16 );
127180 testcase( enc2==SQLITE_UTF16_ALIGNED );
127181 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
127182 enc2 = SQLITE_UTF16NATIVE;
127184 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
127185 return SQLITE_MISUSE_BKPT;
127188 /* Check if this call is removing or replacing an existing collation
127189 ** sequence. If so, and there are active VMs, return busy. If there
127190 ** are no active VMs, invalidate any pre-compiled statements.
127192 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
127193 if( pColl && pColl->xCmp ){
127194 if( db->nVdbeActive ){
127195 sqlite3ErrorWithMsg(db, SQLITE_BUSY,
127196 "unable to delete/modify collation sequence due to active statements");
127197 return SQLITE_BUSY;
127199 sqlite3ExpirePreparedStatements(db);
127200 invalidateCachedKeyInfo(db);
127202 /* If collation sequence pColl was created directly by a call to
127203 ** sqlite3_create_collation, and not generated by synthCollSeq(),
127204 ** then any copies made by synthCollSeq() need to be invalidated.
127205 ** Also, collation destructor - CollSeq.xDel() - function may need
127206 ** to be called.
127208 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
127209 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
127210 int j;
127211 for(j=0; j<3; j++){
127212 CollSeq *p = &aColl[j];
127213 if( p->enc==pColl->enc ){
127214 if( p->xDel ){
127215 p->xDel(p->pUser);
127217 p->xCmp = 0;
127223 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
127224 if( pColl==0 ) return SQLITE_NOMEM;
127225 pColl->xCmp = xCompare;
127226 pColl->pUser = pCtx;
127227 pColl->xDel = xDel;
127228 pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
127229 sqlite3Error(db, SQLITE_OK);
127230 return SQLITE_OK;
127235 ** This array defines hard upper bounds on limit values. The
127236 ** initializer must be kept in sync with the SQLITE_LIMIT_*
127237 ** #defines in sqlite3.h.
127239 static const int aHardLimit[] = {
127240 SQLITE_MAX_LENGTH,
127241 SQLITE_MAX_SQL_LENGTH,
127242 SQLITE_MAX_COLUMN,
127243 SQLITE_MAX_EXPR_DEPTH,
127244 SQLITE_MAX_COMPOUND_SELECT,
127245 SQLITE_MAX_VDBE_OP,
127246 SQLITE_MAX_FUNCTION_ARG,
127247 SQLITE_MAX_ATTACHED,
127248 SQLITE_MAX_LIKE_PATTERN_LENGTH,
127249 SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
127250 SQLITE_MAX_TRIGGER_DEPTH,
127251 SQLITE_MAX_WORKER_THREADS,
127255 ** Make sure the hard limits are set to reasonable values
127257 #if SQLITE_MAX_LENGTH<100
127258 # error SQLITE_MAX_LENGTH must be at least 100
127259 #endif
127260 #if SQLITE_MAX_SQL_LENGTH<100
127261 # error SQLITE_MAX_SQL_LENGTH must be at least 100
127262 #endif
127263 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
127264 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
127265 #endif
127266 #if SQLITE_MAX_COMPOUND_SELECT<2
127267 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
127268 #endif
127269 #if SQLITE_MAX_VDBE_OP<40
127270 # error SQLITE_MAX_VDBE_OP must be at least 40
127271 #endif
127272 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
127273 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
127274 #endif
127275 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
127276 # error SQLITE_MAX_ATTACHED must be between 0 and 125
127277 #endif
127278 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
127279 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
127280 #endif
127281 #if SQLITE_MAX_COLUMN>32767
127282 # error SQLITE_MAX_COLUMN must not exceed 32767
127283 #endif
127284 #if SQLITE_MAX_TRIGGER_DEPTH<1
127285 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
127286 #endif
127287 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
127288 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
127289 #endif
127293 ** Change the value of a limit. Report the old value.
127294 ** If an invalid limit index is supplied, report -1.
127295 ** Make no changes but still report the old value if the
127296 ** new limit is negative.
127298 ** A new lower limit does not shrink existing constructs.
127299 ** It merely prevents new constructs that exceed the limit
127300 ** from forming.
127302 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
127303 int oldLimit;
127306 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
127307 ** there is a hard upper bound set at compile-time by a C preprocessor
127308 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
127309 ** "_MAX_".)
127311 assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
127312 assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
127313 assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
127314 assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
127315 assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
127316 assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
127317 assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
127318 assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
127319 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
127320 SQLITE_MAX_LIKE_PATTERN_LENGTH );
127321 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
127322 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
127323 assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
127324 assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
127327 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
127328 return -1;
127330 oldLimit = db->aLimit[limitId];
127331 if( newLimit>=0 ){ /* IMP: R-52476-28732 */
127332 if( newLimit>aHardLimit[limitId] ){
127333 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
127335 db->aLimit[limitId] = newLimit;
127337 return oldLimit; /* IMP: R-53341-35419 */
127341 ** This function is used to parse both URIs and non-URI filenames passed by the
127342 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
127343 ** URIs specified as part of ATTACH statements.
127345 ** The first argument to this function is the name of the VFS to use (or
127346 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
127347 ** query parameter. The second argument contains the URI (or non-URI filename)
127348 ** itself. When this function is called the *pFlags variable should contain
127349 ** the default flags to open the database handle with. The value stored in
127350 ** *pFlags may be updated before returning if the URI filename contains
127351 ** "cache=xxx" or "mode=xxx" query parameters.
127353 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
127354 ** the VFS that should be used to open the database file. *pzFile is set to
127355 ** point to a buffer containing the name of the file to open. It is the
127356 ** responsibility of the caller to eventually call sqlite3_free() to release
127357 ** this buffer.
127359 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
127360 ** may be set to point to a buffer containing an English language error
127361 ** message. It is the responsibility of the caller to eventually release
127362 ** this buffer by calling sqlite3_free().
127364 SQLITE_PRIVATE int sqlite3ParseUri(
127365 const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
127366 const char *zUri, /* Nul-terminated URI to parse */
127367 unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
127368 sqlite3_vfs **ppVfs, /* OUT: VFS to use */
127369 char **pzFile, /* OUT: Filename component of URI */
127370 char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
127372 int rc = SQLITE_OK;
127373 unsigned int flags = *pFlags;
127374 const char *zVfs = zDefaultVfs;
127375 char *zFile;
127376 char c;
127377 int nUri = sqlite3Strlen30(zUri);
127379 assert( *pzErrMsg==0 );
127381 if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
127382 && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
127384 char *zOpt;
127385 int eState; /* Parser state when parsing URI */
127386 int iIn; /* Input character index */
127387 int iOut = 0; /* Output character index */
127388 int nByte = nUri+2; /* Bytes of space to allocate */
127390 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
127391 ** method that there may be extra parameters following the file-name. */
127392 flags |= SQLITE_OPEN_URI;
127394 for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
127395 zFile = sqlite3_malloc(nByte);
127396 if( !zFile ) return SQLITE_NOMEM;
127398 iIn = 5;
127399 #ifndef SQLITE_ALLOW_URI_AUTHORITY
127400 /* Discard the scheme and authority segments of the URI. */
127401 if( zUri[5]=='/' && zUri[6]=='/' ){
127402 iIn = 7;
127403 while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
127404 if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
127405 *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
127406 iIn-7, &zUri[7]);
127407 rc = SQLITE_ERROR;
127408 goto parse_uri_out;
127411 #endif
127413 /* Copy the filename and any query parameters into the zFile buffer.
127414 ** Decode %HH escape codes along the way.
127416 ** Within this loop, variable eState may be set to 0, 1 or 2, depending
127417 ** on the parsing context. As follows:
127419 ** 0: Parsing file-name.
127420 ** 1: Parsing name section of a name=value query parameter.
127421 ** 2: Parsing value section of a name=value query parameter.
127423 eState = 0;
127424 while( (c = zUri[iIn])!=0 && c!='#' ){
127425 iIn++;
127426 if( c=='%'
127427 && sqlite3Isxdigit(zUri[iIn])
127428 && sqlite3Isxdigit(zUri[iIn+1])
127430 int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
127431 octet += sqlite3HexToInt(zUri[iIn++]);
127433 assert( octet>=0 && octet<256 );
127434 if( octet==0 ){
127435 /* This branch is taken when "%00" appears within the URI. In this
127436 ** case we ignore all text in the remainder of the path, name or
127437 ** value currently being parsed. So ignore the current character
127438 ** and skip to the next "?", "=" or "&", as appropriate. */
127439 while( (c = zUri[iIn])!=0 && c!='#'
127440 && (eState!=0 || c!='?')
127441 && (eState!=1 || (c!='=' && c!='&'))
127442 && (eState!=2 || c!='&')
127444 iIn++;
127446 continue;
127448 c = octet;
127449 }else if( eState==1 && (c=='&' || c=='=') ){
127450 if( zFile[iOut-1]==0 ){
127451 /* An empty option name. Ignore this option altogether. */
127452 while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
127453 continue;
127455 if( c=='&' ){
127456 zFile[iOut++] = '\0';
127457 }else{
127458 eState = 2;
127460 c = 0;
127461 }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
127462 c = 0;
127463 eState = 1;
127465 zFile[iOut++] = c;
127467 if( eState==1 ) zFile[iOut++] = '\0';
127468 zFile[iOut++] = '\0';
127469 zFile[iOut++] = '\0';
127471 /* Check if there were any options specified that should be interpreted
127472 ** here. Options that are interpreted here include "vfs" and those that
127473 ** correspond to flags that may be passed to the sqlite3_open_v2()
127474 ** method. */
127475 zOpt = &zFile[sqlite3Strlen30(zFile)+1];
127476 while( zOpt[0] ){
127477 int nOpt = sqlite3Strlen30(zOpt);
127478 char *zVal = &zOpt[nOpt+1];
127479 int nVal = sqlite3Strlen30(zVal);
127481 if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
127482 zVfs = zVal;
127483 }else{
127484 struct OpenMode {
127485 const char *z;
127486 int mode;
127487 } *aMode = 0;
127488 char *zModeType = 0;
127489 int mask = 0;
127490 int limit = 0;
127492 if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
127493 static struct OpenMode aCacheMode[] = {
127494 { "shared", SQLITE_OPEN_SHAREDCACHE },
127495 { "private", SQLITE_OPEN_PRIVATECACHE },
127496 { 0, 0 }
127499 mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
127500 aMode = aCacheMode;
127501 limit = mask;
127502 zModeType = "cache";
127504 if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
127505 static struct OpenMode aOpenMode[] = {
127506 { "ro", SQLITE_OPEN_READONLY },
127507 { "rw", SQLITE_OPEN_READWRITE },
127508 { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
127509 { "memory", SQLITE_OPEN_MEMORY },
127510 { 0, 0 }
127513 mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
127514 | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
127515 aMode = aOpenMode;
127516 limit = mask & flags;
127517 zModeType = "access";
127520 if( aMode ){
127521 int i;
127522 int mode = 0;
127523 for(i=0; aMode[i].z; i++){
127524 const char *z = aMode[i].z;
127525 if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
127526 mode = aMode[i].mode;
127527 break;
127530 if( mode==0 ){
127531 *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
127532 rc = SQLITE_ERROR;
127533 goto parse_uri_out;
127535 if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
127536 *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
127537 zModeType, zVal);
127538 rc = SQLITE_PERM;
127539 goto parse_uri_out;
127541 flags = (flags & ~mask) | mode;
127545 zOpt = &zVal[nVal+1];
127548 }else{
127549 zFile = sqlite3_malloc(nUri+2);
127550 if( !zFile ) return SQLITE_NOMEM;
127551 memcpy(zFile, zUri, nUri);
127552 zFile[nUri] = '\0';
127553 zFile[nUri+1] = '\0';
127554 flags &= ~SQLITE_OPEN_URI;
127557 *ppVfs = sqlite3_vfs_find(zVfs);
127558 if( *ppVfs==0 ){
127559 *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
127560 rc = SQLITE_ERROR;
127562 parse_uri_out:
127563 if( rc!=SQLITE_OK ){
127564 sqlite3_free(zFile);
127565 zFile = 0;
127567 *pFlags = flags;
127568 *pzFile = zFile;
127569 return rc;
127574 ** This routine does the work of opening a database on behalf of
127575 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
127576 ** is UTF-8 encoded.
127578 static int openDatabase(
127579 const char *zFilename, /* Database filename UTF-8 encoded */
127580 sqlite3 **ppDb, /* OUT: Returned database handle */
127581 unsigned int flags, /* Operational flags */
127582 const char *zVfs /* Name of the VFS to use */
127584 sqlite3 *db; /* Store allocated handle here */
127585 int rc; /* Return code */
127586 int isThreadsafe; /* True for threadsafe connections */
127587 char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
127588 char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
127590 *ppDb = 0;
127591 #ifndef SQLITE_OMIT_AUTOINIT
127592 rc = sqlite3_initialize();
127593 if( rc ) return rc;
127594 #endif
127596 /* Only allow sensible combinations of bits in the flags argument.
127597 ** Throw an error if any non-sense combination is used. If we
127598 ** do not block illegal combinations here, it could trigger
127599 ** assert() statements in deeper layers. Sensible combinations
127600 ** are:
127602 ** 1: SQLITE_OPEN_READONLY
127603 ** 2: SQLITE_OPEN_READWRITE
127604 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
127606 assert( SQLITE_OPEN_READONLY == 0x01 );
127607 assert( SQLITE_OPEN_READWRITE == 0x02 );
127608 assert( SQLITE_OPEN_CREATE == 0x04 );
127609 testcase( (1<<(flags&7))==0x02 ); /* READONLY */
127610 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
127611 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
127612 if( ((1<<(flags&7)) & 0x46)==0 ){
127613 return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
127616 if( sqlite3GlobalConfig.bCoreMutex==0 ){
127617 isThreadsafe = 0;
127618 }else if( flags & SQLITE_OPEN_NOMUTEX ){
127619 isThreadsafe = 0;
127620 }else if( flags & SQLITE_OPEN_FULLMUTEX ){
127621 isThreadsafe = 1;
127622 }else{
127623 isThreadsafe = sqlite3GlobalConfig.bFullMutex;
127625 if( flags & SQLITE_OPEN_PRIVATECACHE ){
127626 flags &= ~SQLITE_OPEN_SHAREDCACHE;
127627 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
127628 flags |= SQLITE_OPEN_SHAREDCACHE;
127631 /* Remove harmful bits from the flags parameter
127633 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
127634 ** dealt with in the previous code block. Besides these, the only
127635 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
127636 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
127637 ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
127638 ** off all other flags.
127640 flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
127641 SQLITE_OPEN_EXCLUSIVE |
127642 SQLITE_OPEN_MAIN_DB |
127643 SQLITE_OPEN_TEMP_DB |
127644 SQLITE_OPEN_TRANSIENT_DB |
127645 SQLITE_OPEN_MAIN_JOURNAL |
127646 SQLITE_OPEN_TEMP_JOURNAL |
127647 SQLITE_OPEN_SUBJOURNAL |
127648 SQLITE_OPEN_MASTER_JOURNAL |
127649 SQLITE_OPEN_NOMUTEX |
127650 SQLITE_OPEN_FULLMUTEX |
127651 SQLITE_OPEN_WAL
127654 /* Allocate the sqlite data structure */
127655 db = sqlite3MallocZero( sizeof(sqlite3) );
127656 if( db==0 ) goto opendb_out;
127657 if( isThreadsafe ){
127658 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
127659 if( db->mutex==0 ){
127660 sqlite3_free(db);
127661 db = 0;
127662 goto opendb_out;
127665 sqlite3_mutex_enter(db->mutex);
127666 db->errMask = 0xff;
127667 db->nDb = 2;
127668 db->magic = SQLITE_MAGIC_BUSY;
127669 db->aDb = db->aDbStatic;
127671 assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
127672 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
127673 db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
127674 db->autoCommit = 1;
127675 db->nextAutovac = -1;
127676 db->szMmap = sqlite3GlobalConfig.szMmap;
127677 db->nextPagesize = 0;
127678 db->nMaxSorterMmap = 0x7FFFFFFF;
127679 db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
127680 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
127681 | SQLITE_AutoIndex
127682 #endif
127683 #if SQLITE_DEFAULT_FILE_FORMAT<4
127684 | SQLITE_LegacyFileFmt
127685 #endif
127686 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
127687 | SQLITE_LoadExtension
127688 #endif
127689 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
127690 | SQLITE_RecTriggers
127691 #endif
127692 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
127693 | SQLITE_ForeignKeys
127694 #endif
127696 sqlite3HashInit(&db->aCollSeq);
127697 #ifndef SQLITE_OMIT_VIRTUALTABLE
127698 sqlite3HashInit(&db->aModule);
127699 #endif
127701 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
127702 ** and UTF-16, so add a version for each to avoid any unnecessary
127703 ** conversions. The only error that can occur here is a malloc() failure.
127705 createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
127706 createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
127707 createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
127708 createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
127709 if( db->mallocFailed ){
127710 goto opendb_out;
127712 db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
127713 assert( db->pDfltColl!=0 );
127715 /* Also add a UTF-8 case-insensitive collation sequence. */
127716 createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
127718 /* Parse the filename/URI argument. */
127719 db->openFlags = flags;
127720 rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
127721 if( rc!=SQLITE_OK ){
127722 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
127723 sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
127724 sqlite3_free(zErrMsg);
127725 goto opendb_out;
127728 /* Open the backend database driver */
127729 rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
127730 flags | SQLITE_OPEN_MAIN_DB);
127731 if( rc!=SQLITE_OK ){
127732 if( rc==SQLITE_IOERR_NOMEM ){
127733 rc = SQLITE_NOMEM;
127735 sqlite3Error(db, rc);
127736 goto opendb_out;
127738 sqlite3BtreeEnter(db->aDb[0].pBt);
127739 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
127740 sqlite3BtreeLeave(db->aDb[0].pBt);
127741 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
127743 /* The default safety_level for the main database is 'full'; for the temp
127744 ** database it is 'NONE'. This matches the pager layer defaults.
127746 db->aDb[0].zName = "main";
127747 db->aDb[0].safety_level = 3;
127748 db->aDb[1].zName = "temp";
127749 db->aDb[1].safety_level = 1;
127751 db->magic = SQLITE_MAGIC_OPEN;
127752 if( db->mallocFailed ){
127753 goto opendb_out;
127756 /* Register all built-in functions, but do not attempt to read the
127757 ** database schema yet. This is delayed until the first time the database
127758 ** is accessed.
127760 sqlite3Error(db, SQLITE_OK);
127761 sqlite3RegisterBuiltinFunctions(db);
127763 /* Load automatic extensions - extensions that have been registered
127764 ** using the sqlite3_automatic_extension() API.
127766 rc = sqlite3_errcode(db);
127767 if( rc==SQLITE_OK ){
127768 sqlite3AutoLoadExtensions(db);
127769 rc = sqlite3_errcode(db);
127770 if( rc!=SQLITE_OK ){
127771 goto opendb_out;
127775 #ifdef SQLITE_ENABLE_FTS1
127776 if( !db->mallocFailed ){
127777 extern int sqlite3Fts1Init(sqlite3*);
127778 rc = sqlite3Fts1Init(db);
127780 #endif
127782 #ifdef SQLITE_ENABLE_FTS2
127783 if( !db->mallocFailed && rc==SQLITE_OK ){
127784 extern int sqlite3Fts2Init(sqlite3*);
127785 rc = sqlite3Fts2Init(db);
127787 #endif
127789 #ifdef SQLITE_ENABLE_FTS3
127790 if( !db->mallocFailed && rc==SQLITE_OK ){
127791 rc = sqlite3Fts3Init(db);
127793 #endif
127795 #ifdef DEFAULT_ENABLE_RECOVER
127796 /* Initialize recover virtual table for testing. */
127797 extern int recoverVtableInit(sqlite3 *db);
127798 if( !db->mallocFailed && rc==SQLITE_OK ){
127799 rc = recoverVtableInit(db);
127801 #endif
127803 #ifdef SQLITE_ENABLE_ICU
127804 if( !db->mallocFailed && rc==SQLITE_OK ){
127805 rc = sqlite3IcuInit(db);
127807 #endif
127809 #ifdef SQLITE_ENABLE_RTREE
127810 if( !db->mallocFailed && rc==SQLITE_OK){
127811 rc = sqlite3RtreeInit(db);
127813 #endif
127815 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
127816 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
127817 ** mode. Doing nothing at all also makes NORMAL the default.
127819 #ifdef SQLITE_DEFAULT_LOCKING_MODE
127820 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
127821 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
127822 SQLITE_DEFAULT_LOCKING_MODE);
127823 #endif
127825 if( rc ) sqlite3Error(db, rc);
127827 /* Enable the lookaside-malloc subsystem */
127828 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
127829 sqlite3GlobalConfig.nLookaside);
127831 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
127833 opendb_out:
127834 sqlite3_free(zOpen);
127835 if( db ){
127836 assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
127837 sqlite3_mutex_leave(db->mutex);
127839 rc = sqlite3_errcode(db);
127840 assert( db!=0 || rc==SQLITE_NOMEM );
127841 if( rc==SQLITE_NOMEM ){
127842 sqlite3_close(db);
127843 db = 0;
127844 }else if( rc!=SQLITE_OK ){
127845 db->magic = SQLITE_MAGIC_SICK;
127847 *ppDb = db;
127848 #ifdef SQLITE_ENABLE_SQLLOG
127849 if( sqlite3GlobalConfig.xSqllog ){
127850 /* Opening a db handle. Fourth parameter is passed 0. */
127851 void *pArg = sqlite3GlobalConfig.pSqllogArg;
127852 sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
127854 #endif
127855 return sqlite3ApiExit(0, rc);
127859 ** Open a new database handle.
127861 SQLITE_API int sqlite3_open(
127862 const char *zFilename,
127863 sqlite3 **ppDb
127865 return openDatabase(zFilename, ppDb,
127866 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
127868 SQLITE_API int sqlite3_open_v2(
127869 const char *filename, /* Database filename (UTF-8) */
127870 sqlite3 **ppDb, /* OUT: SQLite db handle */
127871 int flags, /* Flags */
127872 const char *zVfs /* Name of VFS module to use */
127874 return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
127877 #ifndef SQLITE_OMIT_UTF16
127879 ** Open a new database handle.
127881 SQLITE_API int sqlite3_open16(
127882 const void *zFilename,
127883 sqlite3 **ppDb
127885 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
127886 sqlite3_value *pVal;
127887 int rc;
127889 assert( zFilename );
127890 assert( ppDb );
127891 *ppDb = 0;
127892 #ifndef SQLITE_OMIT_AUTOINIT
127893 rc = sqlite3_initialize();
127894 if( rc ) return rc;
127895 #endif
127896 pVal = sqlite3ValueNew(0);
127897 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
127898 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
127899 if( zFilename8 ){
127900 rc = openDatabase(zFilename8, ppDb,
127901 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
127902 assert( *ppDb || rc==SQLITE_NOMEM );
127903 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
127904 ENC(*ppDb) = SQLITE_UTF16NATIVE;
127906 }else{
127907 rc = SQLITE_NOMEM;
127909 sqlite3ValueFree(pVal);
127911 return sqlite3ApiExit(0, rc);
127913 #endif /* SQLITE_OMIT_UTF16 */
127916 ** Register a new collation sequence with the database handle db.
127918 SQLITE_API int sqlite3_create_collation(
127919 sqlite3* db,
127920 const char *zName,
127921 int enc,
127922 void* pCtx,
127923 int(*xCompare)(void*,int,const void*,int,const void*)
127925 int rc;
127926 sqlite3_mutex_enter(db->mutex);
127927 assert( !db->mallocFailed );
127928 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
127929 rc = sqlite3ApiExit(db, rc);
127930 sqlite3_mutex_leave(db->mutex);
127931 return rc;
127935 ** Register a new collation sequence with the database handle db.
127937 SQLITE_API int sqlite3_create_collation_v2(
127938 sqlite3* db,
127939 const char *zName,
127940 int enc,
127941 void* pCtx,
127942 int(*xCompare)(void*,int,const void*,int,const void*),
127943 void(*xDel)(void*)
127945 int rc;
127946 sqlite3_mutex_enter(db->mutex);
127947 assert( !db->mallocFailed );
127948 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
127949 rc = sqlite3ApiExit(db, rc);
127950 sqlite3_mutex_leave(db->mutex);
127951 return rc;
127954 #ifndef SQLITE_OMIT_UTF16
127956 ** Register a new collation sequence with the database handle db.
127958 SQLITE_API int sqlite3_create_collation16(
127959 sqlite3* db,
127960 const void *zName,
127961 int enc,
127962 void* pCtx,
127963 int(*xCompare)(void*,int,const void*,int,const void*)
127965 int rc = SQLITE_OK;
127966 char *zName8;
127967 sqlite3_mutex_enter(db->mutex);
127968 assert( !db->mallocFailed );
127969 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
127970 if( zName8 ){
127971 rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
127972 sqlite3DbFree(db, zName8);
127974 rc = sqlite3ApiExit(db, rc);
127975 sqlite3_mutex_leave(db->mutex);
127976 return rc;
127978 #endif /* SQLITE_OMIT_UTF16 */
127981 ** Register a collation sequence factory callback with the database handle
127982 ** db. Replace any previously installed collation sequence factory.
127984 SQLITE_API int sqlite3_collation_needed(
127985 sqlite3 *db,
127986 void *pCollNeededArg,
127987 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
127989 sqlite3_mutex_enter(db->mutex);
127990 db->xCollNeeded = xCollNeeded;
127991 db->xCollNeeded16 = 0;
127992 db->pCollNeededArg = pCollNeededArg;
127993 sqlite3_mutex_leave(db->mutex);
127994 return SQLITE_OK;
127997 #ifndef SQLITE_OMIT_UTF16
127999 ** Register a collation sequence factory callback with the database handle
128000 ** db. Replace any previously installed collation sequence factory.
128002 SQLITE_API int sqlite3_collation_needed16(
128003 sqlite3 *db,
128004 void *pCollNeededArg,
128005 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
128007 sqlite3_mutex_enter(db->mutex);
128008 db->xCollNeeded = 0;
128009 db->xCollNeeded16 = xCollNeeded16;
128010 db->pCollNeededArg = pCollNeededArg;
128011 sqlite3_mutex_leave(db->mutex);
128012 return SQLITE_OK;
128014 #endif /* SQLITE_OMIT_UTF16 */
128016 #ifndef SQLITE_OMIT_DEPRECATED
128018 ** This function is now an anachronism. It used to be used to recover from a
128019 ** malloc() failure, but SQLite now does this automatically.
128021 SQLITE_API int sqlite3_global_recover(void){
128022 return SQLITE_OK;
128024 #endif
128027 ** Test to see whether or not the database connection is in autocommit
128028 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
128029 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
128030 ** by the next COMMIT or ROLLBACK.
128032 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
128033 return db->autoCommit;
128037 ** The following routines are substitutes for constants SQLITE_CORRUPT,
128038 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
128039 ** constants. They serve two purposes:
128041 ** 1. Serve as a convenient place to set a breakpoint in a debugger
128042 ** to detect when version error conditions occurs.
128044 ** 2. Invoke sqlite3_log() to provide the source code location where
128045 ** a low-level error is first detected.
128047 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
128048 testcase( sqlite3GlobalConfig.xLog!=0 );
128049 sqlite3_log(SQLITE_CORRUPT,
128050 "database corruption at line %d of [%.10s]",
128051 lineno, 20+sqlite3_sourceid());
128052 return SQLITE_CORRUPT;
128054 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
128055 testcase( sqlite3GlobalConfig.xLog!=0 );
128056 sqlite3_log(SQLITE_MISUSE,
128057 "misuse at line %d of [%.10s]",
128058 lineno, 20+sqlite3_sourceid());
128059 return SQLITE_MISUSE;
128061 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
128062 testcase( sqlite3GlobalConfig.xLog!=0 );
128063 sqlite3_log(SQLITE_CANTOPEN,
128064 "cannot open file at line %d of [%.10s]",
128065 lineno, 20+sqlite3_sourceid());
128066 return SQLITE_CANTOPEN;
128070 #ifndef SQLITE_OMIT_DEPRECATED
128072 ** This is a convenience routine that makes sure that all thread-specific
128073 ** data for this thread has been deallocated.
128075 ** SQLite no longer uses thread-specific data so this routine is now a
128076 ** no-op. It is retained for historical compatibility.
128078 SQLITE_API void sqlite3_thread_cleanup(void){
128080 #endif
128083 ** Return meta information about a specific column of a database table.
128084 ** See comment in sqlite3.h (sqlite.h.in) for details.
128086 #ifdef SQLITE_ENABLE_COLUMN_METADATA
128087 SQLITE_API int sqlite3_table_column_metadata(
128088 sqlite3 *db, /* Connection handle */
128089 const char *zDbName, /* Database name or NULL */
128090 const char *zTableName, /* Table name */
128091 const char *zColumnName, /* Column name */
128092 char const **pzDataType, /* OUTPUT: Declared data type */
128093 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
128094 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
128095 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
128096 int *pAutoinc /* OUTPUT: True if column is auto-increment */
128098 int rc;
128099 char *zErrMsg = 0;
128100 Table *pTab = 0;
128101 Column *pCol = 0;
128102 int iCol;
128104 char const *zDataType = 0;
128105 char const *zCollSeq = 0;
128106 int notnull = 0;
128107 int primarykey = 0;
128108 int autoinc = 0;
128110 /* Ensure the database schema has been loaded */
128111 sqlite3_mutex_enter(db->mutex);
128112 sqlite3BtreeEnterAll(db);
128113 rc = sqlite3Init(db, &zErrMsg);
128114 if( SQLITE_OK!=rc ){
128115 goto error_out;
128118 /* Locate the table in question */
128119 pTab = sqlite3FindTable(db, zTableName, zDbName);
128120 if( !pTab || pTab->pSelect ){
128121 pTab = 0;
128122 goto error_out;
128125 /* Find the column for which info is requested */
128126 if( sqlite3IsRowid(zColumnName) ){
128127 iCol = pTab->iPKey;
128128 if( iCol>=0 ){
128129 pCol = &pTab->aCol[iCol];
128131 }else{
128132 for(iCol=0; iCol<pTab->nCol; iCol++){
128133 pCol = &pTab->aCol[iCol];
128134 if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
128135 break;
128138 if( iCol==pTab->nCol ){
128139 pTab = 0;
128140 goto error_out;
128144 /* The following block stores the meta information that will be returned
128145 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
128146 ** and autoinc. At this point there are two possibilities:
128148 ** 1. The specified column name was rowid", "oid" or "_rowid_"
128149 ** and there is no explicitly declared IPK column.
128151 ** 2. The table is not a view and the column name identified an
128152 ** explicitly declared column. Copy meta information from *pCol.
128154 if( pCol ){
128155 zDataType = pCol->zType;
128156 zCollSeq = pCol->zColl;
128157 notnull = pCol->notNull!=0;
128158 primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
128159 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
128160 }else{
128161 zDataType = "INTEGER";
128162 primarykey = 1;
128164 if( !zCollSeq ){
128165 zCollSeq = "BINARY";
128168 error_out:
128169 sqlite3BtreeLeaveAll(db);
128171 /* Whether the function call succeeded or failed, set the output parameters
128172 ** to whatever their local counterparts contain. If an error did occur,
128173 ** this has the effect of zeroing all output parameters.
128175 if( pzDataType ) *pzDataType = zDataType;
128176 if( pzCollSeq ) *pzCollSeq = zCollSeq;
128177 if( pNotNull ) *pNotNull = notnull;
128178 if( pPrimaryKey ) *pPrimaryKey = primarykey;
128179 if( pAutoinc ) *pAutoinc = autoinc;
128181 if( SQLITE_OK==rc && !pTab ){
128182 sqlite3DbFree(db, zErrMsg);
128183 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
128184 zColumnName);
128185 rc = SQLITE_ERROR;
128187 sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
128188 sqlite3DbFree(db, zErrMsg);
128189 rc = sqlite3ApiExit(db, rc);
128190 sqlite3_mutex_leave(db->mutex);
128191 return rc;
128193 #endif
128196 ** Sleep for a little while. Return the amount of time slept.
128198 SQLITE_API int sqlite3_sleep(int ms){
128199 sqlite3_vfs *pVfs;
128200 int rc;
128201 pVfs = sqlite3_vfs_find(0);
128202 if( pVfs==0 ) return 0;
128204 /* This function works in milliseconds, but the underlying OsSleep()
128205 ** API uses microseconds. Hence the 1000's.
128207 rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
128208 return rc;
128212 ** Enable or disable the extended result codes.
128214 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
128215 sqlite3_mutex_enter(db->mutex);
128216 db->errMask = onoff ? 0xffffffff : 0xff;
128217 sqlite3_mutex_leave(db->mutex);
128218 return SQLITE_OK;
128222 ** Invoke the xFileControl method on a particular database.
128224 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
128225 int rc = SQLITE_ERROR;
128226 Btree *pBtree;
128228 sqlite3_mutex_enter(db->mutex);
128229 pBtree = sqlite3DbNameToBtree(db, zDbName);
128230 if( pBtree ){
128231 Pager *pPager;
128232 sqlite3_file *fd;
128233 sqlite3BtreeEnter(pBtree);
128234 pPager = sqlite3BtreePager(pBtree);
128235 assert( pPager!=0 );
128236 fd = sqlite3PagerFile(pPager);
128237 assert( fd!=0 );
128238 if( op==SQLITE_FCNTL_FILE_POINTER ){
128239 *(sqlite3_file**)pArg = fd;
128240 rc = SQLITE_OK;
128241 }else if( fd->pMethods ){
128242 rc = sqlite3OsFileControl(fd, op, pArg);
128243 }else{
128244 rc = SQLITE_NOTFOUND;
128246 sqlite3BtreeLeave(pBtree);
128248 sqlite3_mutex_leave(db->mutex);
128249 return rc;
128253 ** Interface to the testing logic.
128255 SQLITE_API int sqlite3_test_control(int op, ...){
128256 int rc = 0;
128257 #ifndef SQLITE_OMIT_BUILTIN_TEST
128258 va_list ap;
128259 va_start(ap, op);
128260 switch( op ){
128263 ** Save the current state of the PRNG.
128265 case SQLITE_TESTCTRL_PRNG_SAVE: {
128266 sqlite3PrngSaveState();
128267 break;
128271 ** Restore the state of the PRNG to the last state saved using
128272 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
128273 ** this verb acts like PRNG_RESET.
128275 case SQLITE_TESTCTRL_PRNG_RESTORE: {
128276 sqlite3PrngRestoreState();
128277 break;
128281 ** Reset the PRNG back to its uninitialized state. The next call
128282 ** to sqlite3_randomness() will reseed the PRNG using a single call
128283 ** to the xRandomness method of the default VFS.
128285 case SQLITE_TESTCTRL_PRNG_RESET: {
128286 sqlite3_randomness(0,0);
128287 break;
128291 ** sqlite3_test_control(BITVEC_TEST, size, program)
128293 ** Run a test against a Bitvec object of size. The program argument
128294 ** is an array of integers that defines the test. Return -1 on a
128295 ** memory allocation error, 0 on success, or non-zero for an error.
128296 ** See the sqlite3BitvecBuiltinTest() for additional information.
128298 case SQLITE_TESTCTRL_BITVEC_TEST: {
128299 int sz = va_arg(ap, int);
128300 int *aProg = va_arg(ap, int*);
128301 rc = sqlite3BitvecBuiltinTest(sz, aProg);
128302 break;
128306 ** sqlite3_test_control(FAULT_INSTALL, xCallback)
128308 ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
128309 ** if xCallback is not NULL.
128311 ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
128312 ** is called immediately after installing the new callback and the return
128313 ** value from sqlite3FaultSim(0) becomes the return from
128314 ** sqlite3_test_control().
128316 case SQLITE_TESTCTRL_FAULT_INSTALL: {
128317 /* MSVC is picky about pulling func ptrs from va lists.
128318 ** http://support.microsoft.com/kb/47961
128319 ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
128321 typedef int(*TESTCALLBACKFUNC_t)(int);
128322 sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
128323 rc = sqlite3FaultSim(0);
128324 break;
128328 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
128330 ** Register hooks to call to indicate which malloc() failures
128331 ** are benign.
128333 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
128334 typedef void (*void_function)(void);
128335 void_function xBenignBegin;
128336 void_function xBenignEnd;
128337 xBenignBegin = va_arg(ap, void_function);
128338 xBenignEnd = va_arg(ap, void_function);
128339 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
128340 break;
128344 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
128346 ** Set the PENDING byte to the value in the argument, if X>0.
128347 ** Make no changes if X==0. Return the value of the pending byte
128348 ** as it existing before this routine was called.
128350 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
128351 ** an incompatible database file format. Changing the PENDING byte
128352 ** while any database connection is open results in undefined and
128353 ** deleterious behavior.
128355 case SQLITE_TESTCTRL_PENDING_BYTE: {
128356 rc = PENDING_BYTE;
128357 #ifndef SQLITE_OMIT_WSD
128359 unsigned int newVal = va_arg(ap, unsigned int);
128360 if( newVal ) sqlite3PendingByte = newVal;
128362 #endif
128363 break;
128367 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
128369 ** This action provides a run-time test to see whether or not
128370 ** assert() was enabled at compile-time. If X is true and assert()
128371 ** is enabled, then the return value is true. If X is true and
128372 ** assert() is disabled, then the return value is zero. If X is
128373 ** false and assert() is enabled, then the assertion fires and the
128374 ** process aborts. If X is false and assert() is disabled, then the
128375 ** return value is zero.
128377 case SQLITE_TESTCTRL_ASSERT: {
128378 volatile int x = 0;
128379 assert( (x = va_arg(ap,int))!=0 );
128380 rc = x;
128381 break;
128386 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
128388 ** This action provides a run-time test to see how the ALWAYS and
128389 ** NEVER macros were defined at compile-time.
128391 ** The return value is ALWAYS(X).
128393 ** The recommended test is X==2. If the return value is 2, that means
128394 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
128395 ** default setting. If the return value is 1, then ALWAYS() is either
128396 ** hard-coded to true or else it asserts if its argument is false.
128397 ** The first behavior (hard-coded to true) is the case if
128398 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
128399 ** behavior (assert if the argument to ALWAYS() is false) is the case if
128400 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
128402 ** The run-time test procedure might look something like this:
128404 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
128405 ** // ALWAYS() and NEVER() are no-op pass-through macros
128406 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
128407 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
128408 ** }else{
128409 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
128412 case SQLITE_TESTCTRL_ALWAYS: {
128413 int x = va_arg(ap,int);
128414 rc = ALWAYS(x);
128415 break;
128419 ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
128421 ** The integer returned reveals the byte-order of the computer on which
128422 ** SQLite is running:
128424 ** 1 big-endian, determined at run-time
128425 ** 10 little-endian, determined at run-time
128426 ** 432101 big-endian, determined at compile-time
128427 ** 123410 little-endian, determined at compile-time
128429 case SQLITE_TESTCTRL_BYTEORDER: {
128430 rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
128431 break;
128434 /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
128436 ** Set the nReserve size to N for the main database on the database
128437 ** connection db.
128439 case SQLITE_TESTCTRL_RESERVE: {
128440 sqlite3 *db = va_arg(ap, sqlite3*);
128441 int x = va_arg(ap,int);
128442 sqlite3_mutex_enter(db->mutex);
128443 sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
128444 sqlite3_mutex_leave(db->mutex);
128445 break;
128448 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
128450 ** Enable or disable various optimizations for testing purposes. The
128451 ** argument N is a bitmask of optimizations to be disabled. For normal
128452 ** operation N should be 0. The idea is that a test program (like the
128453 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
128454 ** with various optimizations disabled to verify that the same answer
128455 ** is obtained in every case.
128457 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
128458 sqlite3 *db = va_arg(ap, sqlite3*);
128459 db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
128460 break;
128463 #ifdef SQLITE_N_KEYWORD
128464 /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
128466 ** If zWord is a keyword recognized by the parser, then return the
128467 ** number of keywords. Or if zWord is not a keyword, return 0.
128469 ** This test feature is only available in the amalgamation since
128470 ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
128471 ** is built using separate source files.
128473 case SQLITE_TESTCTRL_ISKEYWORD: {
128474 const char *zWord = va_arg(ap, const char*);
128475 int n = sqlite3Strlen30(zWord);
128476 rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
128477 break;
128479 #endif
128481 /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
128483 ** Pass pFree into sqlite3ScratchFree().
128484 ** If sz>0 then allocate a scratch buffer into pNew.
128486 case SQLITE_TESTCTRL_SCRATCHMALLOC: {
128487 void *pFree, **ppNew;
128488 int sz;
128489 sz = va_arg(ap, int);
128490 ppNew = va_arg(ap, void**);
128491 pFree = va_arg(ap, void*);
128492 if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
128493 sqlite3ScratchFree(pFree);
128494 break;
128497 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
128499 ** If parameter onoff is non-zero, configure the wrappers so that all
128500 ** subsequent calls to localtime() and variants fail. If onoff is zero,
128501 ** undo this setting.
128503 case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
128504 sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
128505 break;
128508 /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
128510 ** Set or clear a flag that indicates that the database file is always well-
128511 ** formed and never corrupt. This flag is clear by default, indicating that
128512 ** database files might have arbitrary corruption. Setting the flag during
128513 ** testing causes certain assert() statements in the code to be activated
128514 ** that demonstrat invariants on well-formed database files.
128516 case SQLITE_TESTCTRL_NEVER_CORRUPT: {
128517 sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
128518 break;
128522 /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
128524 ** Set the VDBE coverage callback function to xCallback with context
128525 ** pointer ptr.
128527 case SQLITE_TESTCTRL_VDBE_COVERAGE: {
128528 #ifdef SQLITE_VDBE_COVERAGE
128529 typedef void (*branch_callback)(void*,int,u8,u8);
128530 sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
128531 sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
128532 #endif
128533 break;
128536 /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
128537 case SQLITE_TESTCTRL_SORTER_MMAP: {
128538 sqlite3 *db = va_arg(ap, sqlite3*);
128539 db->nMaxSorterMmap = va_arg(ap, int);
128540 break;
128543 /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
128545 ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
128546 ** not.
128548 case SQLITE_TESTCTRL_ISINIT: {
128549 if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
128550 break;
128553 va_end(ap);
128554 #endif /* SQLITE_OMIT_BUILTIN_TEST */
128555 return rc;
128559 ** This is a utility routine, useful to VFS implementations, that checks
128560 ** to see if a database file was a URI that contained a specific query
128561 ** parameter, and if so obtains the value of the query parameter.
128563 ** The zFilename argument is the filename pointer passed into the xOpen()
128564 ** method of a VFS implementation. The zParam argument is the name of the
128565 ** query parameter we seek. This routine returns the value of the zParam
128566 ** parameter if it exists. If the parameter does not exist, this routine
128567 ** returns a NULL pointer.
128569 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
128570 if( zFilename==0 ) return 0;
128571 zFilename += sqlite3Strlen30(zFilename) + 1;
128572 while( zFilename[0] ){
128573 int x = strcmp(zFilename, zParam);
128574 zFilename += sqlite3Strlen30(zFilename) + 1;
128575 if( x==0 ) return zFilename;
128576 zFilename += sqlite3Strlen30(zFilename) + 1;
128578 return 0;
128582 ** Return a boolean value for a query parameter.
128584 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
128585 const char *z = sqlite3_uri_parameter(zFilename, zParam);
128586 bDflt = bDflt!=0;
128587 return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
128591 ** Return a 64-bit integer value for a query parameter.
128593 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
128594 const char *zFilename, /* Filename as passed to xOpen */
128595 const char *zParam, /* URI parameter sought */
128596 sqlite3_int64 bDflt /* return if parameter is missing */
128598 const char *z = sqlite3_uri_parameter(zFilename, zParam);
128599 sqlite3_int64 v;
128600 if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
128601 bDflt = v;
128603 return bDflt;
128607 ** Return the Btree pointer identified by zDbName. Return NULL if not found.
128609 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
128610 int i;
128611 for(i=0; i<db->nDb; i++){
128612 if( db->aDb[i].pBt
128613 && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
128615 return db->aDb[i].pBt;
128618 return 0;
128622 ** Return the filename of the database associated with a database
128623 ** connection.
128625 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
128626 Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
128627 return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
128631 ** Return 1 if database is read-only or 0 if read/write. Return -1 if
128632 ** no such database exists.
128634 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
128635 Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
128636 return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
128639 /************** End of main.c ************************************************/
128640 /************** Begin file notify.c ******************************************/
128642 ** 2009 March 3
128644 ** The author disclaims copyright to this source code. In place of
128645 ** a legal notice, here is a blessing:
128647 ** May you do good and not evil.
128648 ** May you find forgiveness for yourself and forgive others.
128649 ** May you share freely, never taking more than you give.
128651 *************************************************************************
128653 ** This file contains the implementation of the sqlite3_unlock_notify()
128654 ** API method and its associated functionality.
128657 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
128658 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
128661 ** Public interfaces:
128663 ** sqlite3ConnectionBlocked()
128664 ** sqlite3ConnectionUnlocked()
128665 ** sqlite3ConnectionClosed()
128666 ** sqlite3_unlock_notify()
128669 #define assertMutexHeld() \
128670 assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
128673 ** Head of a linked list of all sqlite3 objects created by this process
128674 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
128675 ** is not NULL. This variable may only accessed while the STATIC_MASTER
128676 ** mutex is held.
128678 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
128680 #ifndef NDEBUG
128682 ** This function is a complex assert() that verifies the following
128683 ** properties of the blocked connections list:
128685 ** 1) Each entry in the list has a non-NULL value for either
128686 ** pUnlockConnection or pBlockingConnection, or both.
128688 ** 2) All entries in the list that share a common value for
128689 ** xUnlockNotify are grouped together.
128691 ** 3) If the argument db is not NULL, then none of the entries in the
128692 ** blocked connections list have pUnlockConnection or pBlockingConnection
128693 ** set to db. This is used when closing connection db.
128695 static void checkListProperties(sqlite3 *db){
128696 sqlite3 *p;
128697 for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
128698 int seen = 0;
128699 sqlite3 *p2;
128701 /* Verify property (1) */
128702 assert( p->pUnlockConnection || p->pBlockingConnection );
128704 /* Verify property (2) */
128705 for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
128706 if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
128707 assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
128708 assert( db==0 || p->pUnlockConnection!=db );
128709 assert( db==0 || p->pBlockingConnection!=db );
128713 #else
128714 # define checkListProperties(x)
128715 #endif
128718 ** Remove connection db from the blocked connections list. If connection
128719 ** db is not currently a part of the list, this function is a no-op.
128721 static void removeFromBlockedList(sqlite3 *db){
128722 sqlite3 **pp;
128723 assertMutexHeld();
128724 for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
128725 if( *pp==db ){
128726 *pp = (*pp)->pNextBlocked;
128727 break;
128733 ** Add connection db to the blocked connections list. It is assumed
128734 ** that it is not already a part of the list.
128736 static void addToBlockedList(sqlite3 *db){
128737 sqlite3 **pp;
128738 assertMutexHeld();
128740 pp=&sqlite3BlockedList;
128741 *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
128742 pp=&(*pp)->pNextBlocked
128744 db->pNextBlocked = *pp;
128745 *pp = db;
128749 ** Obtain the STATIC_MASTER mutex.
128751 static void enterMutex(void){
128752 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
128753 checkListProperties(0);
128757 ** Release the STATIC_MASTER mutex.
128759 static void leaveMutex(void){
128760 assertMutexHeld();
128761 checkListProperties(0);
128762 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
128766 ** Register an unlock-notify callback.
128768 ** This is called after connection "db" has attempted some operation
128769 ** but has received an SQLITE_LOCKED error because another connection
128770 ** (call it pOther) in the same process was busy using the same shared
128771 ** cache. pOther is found by looking at db->pBlockingConnection.
128773 ** If there is no blocking connection, the callback is invoked immediately,
128774 ** before this routine returns.
128776 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
128777 ** a deadlock.
128779 ** Otherwise, make arrangements to invoke xNotify when pOther drops
128780 ** its locks.
128782 ** Each call to this routine overrides any prior callbacks registered
128783 ** on the same "db". If xNotify==0 then any prior callbacks are immediately
128784 ** cancelled.
128786 SQLITE_API int sqlite3_unlock_notify(
128787 sqlite3 *db,
128788 void (*xNotify)(void **, int),
128789 void *pArg
128791 int rc = SQLITE_OK;
128793 sqlite3_mutex_enter(db->mutex);
128794 enterMutex();
128796 if( xNotify==0 ){
128797 removeFromBlockedList(db);
128798 db->pBlockingConnection = 0;
128799 db->pUnlockConnection = 0;
128800 db->xUnlockNotify = 0;
128801 db->pUnlockArg = 0;
128802 }else if( 0==db->pBlockingConnection ){
128803 /* The blocking transaction has been concluded. Or there never was a
128804 ** blocking transaction. In either case, invoke the notify callback
128805 ** immediately.
128807 xNotify(&pArg, 1);
128808 }else{
128809 sqlite3 *p;
128811 for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
128812 if( p ){
128813 rc = SQLITE_LOCKED; /* Deadlock detected. */
128814 }else{
128815 db->pUnlockConnection = db->pBlockingConnection;
128816 db->xUnlockNotify = xNotify;
128817 db->pUnlockArg = pArg;
128818 removeFromBlockedList(db);
128819 addToBlockedList(db);
128823 leaveMutex();
128824 assert( !db->mallocFailed );
128825 sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
128826 sqlite3_mutex_leave(db->mutex);
128827 return rc;
128831 ** This function is called while stepping or preparing a statement
128832 ** associated with connection db. The operation will return SQLITE_LOCKED
128833 ** to the user because it requires a lock that will not be available
128834 ** until connection pBlocker concludes its current transaction.
128836 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
128837 enterMutex();
128838 if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
128839 addToBlockedList(db);
128841 db->pBlockingConnection = pBlocker;
128842 leaveMutex();
128846 ** This function is called when
128847 ** the transaction opened by database db has just finished. Locks held
128848 ** by database connection db have been released.
128850 ** This function loops through each entry in the blocked connections
128851 ** list and does the following:
128853 ** 1) If the sqlite3.pBlockingConnection member of a list entry is
128854 ** set to db, then set pBlockingConnection=0.
128856 ** 2) If the sqlite3.pUnlockConnection member of a list entry is
128857 ** set to db, then invoke the configured unlock-notify callback and
128858 ** set pUnlockConnection=0.
128860 ** 3) If the two steps above mean that pBlockingConnection==0 and
128861 ** pUnlockConnection==0, remove the entry from the blocked connections
128862 ** list.
128864 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
128865 void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
128866 int nArg = 0; /* Number of entries in aArg[] */
128867 sqlite3 **pp; /* Iterator variable */
128868 void **aArg; /* Arguments to the unlock callback */
128869 void **aDyn = 0; /* Dynamically allocated space for aArg[] */
128870 void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
128872 aArg = aStatic;
128873 enterMutex(); /* Enter STATIC_MASTER mutex */
128875 /* This loop runs once for each entry in the blocked-connections list. */
128876 for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
128877 sqlite3 *p = *pp;
128879 /* Step 1. */
128880 if( p->pBlockingConnection==db ){
128881 p->pBlockingConnection = 0;
128884 /* Step 2. */
128885 if( p->pUnlockConnection==db ){
128886 assert( p->xUnlockNotify );
128887 if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
128888 xUnlockNotify(aArg, nArg);
128889 nArg = 0;
128892 sqlite3BeginBenignMalloc();
128893 assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
128894 assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
128895 if( (!aDyn && nArg==(int)ArraySize(aStatic))
128896 || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
128898 /* The aArg[] array needs to grow. */
128899 void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
128900 if( pNew ){
128901 memcpy(pNew, aArg, nArg*sizeof(void *));
128902 sqlite3_free(aDyn);
128903 aDyn = aArg = pNew;
128904 }else{
128905 /* This occurs when the array of context pointers that need to
128906 ** be passed to the unlock-notify callback is larger than the
128907 ** aStatic[] array allocated on the stack and the attempt to
128908 ** allocate a larger array from the heap has failed.
128910 ** This is a difficult situation to handle. Returning an error
128911 ** code to the caller is insufficient, as even if an error code
128912 ** is returned the transaction on connection db will still be
128913 ** closed and the unlock-notify callbacks on blocked connections
128914 ** will go unissued. This might cause the application to wait
128915 ** indefinitely for an unlock-notify callback that will never
128916 ** arrive.
128918 ** Instead, invoke the unlock-notify callback with the context
128919 ** array already accumulated. We can then clear the array and
128920 ** begin accumulating any further context pointers without
128921 ** requiring any dynamic allocation. This is sub-optimal because
128922 ** it means that instead of one callback with a large array of
128923 ** context pointers the application will receive two or more
128924 ** callbacks with smaller arrays of context pointers, which will
128925 ** reduce the applications ability to prioritize multiple
128926 ** connections. But it is the best that can be done under the
128927 ** circumstances.
128929 xUnlockNotify(aArg, nArg);
128930 nArg = 0;
128933 sqlite3EndBenignMalloc();
128935 aArg[nArg++] = p->pUnlockArg;
128936 xUnlockNotify = p->xUnlockNotify;
128937 p->pUnlockConnection = 0;
128938 p->xUnlockNotify = 0;
128939 p->pUnlockArg = 0;
128942 /* Step 3. */
128943 if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
128944 /* Remove connection p from the blocked connections list. */
128945 *pp = p->pNextBlocked;
128946 p->pNextBlocked = 0;
128947 }else{
128948 pp = &p->pNextBlocked;
128952 if( nArg!=0 ){
128953 xUnlockNotify(aArg, nArg);
128955 sqlite3_free(aDyn);
128956 leaveMutex(); /* Leave STATIC_MASTER mutex */
128960 ** This is called when the database connection passed as an argument is
128961 ** being closed. The connection is removed from the blocked list.
128963 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
128964 sqlite3ConnectionUnlocked(db);
128965 enterMutex();
128966 removeFromBlockedList(db);
128967 checkListProperties(db);
128968 leaveMutex();
128970 #endif
128972 /************** End of notify.c **********************************************/
128973 /************** Begin file recover.c *****************************************/
128975 ** 2012 Jan 11
128977 ** The author disclaims copyright to this source code. In place of
128978 ** a legal notice, here is a blessing:
128980 ** May you do good and not evil.
128981 ** May you find forgiveness for yourself and forgive others.
128982 ** May you share freely, never taking more than you give.
128984 /* TODO(shess): THIS MODULE IS STILL EXPERIMENTAL. DO NOT USE IT. */
128985 /* Implements a virtual table "recover" which can be used to recover
128986 * data from a corrupt table. The table is walked manually, with
128987 * corrupt items skipped. Additionally, any errors while reading will
128988 * be skipped.
128990 * Given a table with this definition:
128992 * CREATE TABLE Stuff (
128993 * name TEXT PRIMARY KEY,
128994 * value TEXT NOT NULL
128997 * to recover the data from teh table, you could do something like:
128999 * -- Attach another database, the original is not trustworthy.
129000 * ATTACH DATABASE '/tmp/db.db' AS rdb;
129001 * -- Create a new version of the table.
129002 * CREATE TABLE rdb.Stuff (
129003 * name TEXT PRIMARY KEY,
129004 * value TEXT NOT NULL
129006 * -- This will read the original table's data.
129007 * CREATE VIRTUAL TABLE temp.recover_Stuff using recover(
129008 * main.Stuff,
129009 * name TEXT STRICT NOT NULL, -- only real TEXT data allowed
129010 * value TEXT STRICT NOT NULL
129012 * -- Corruption means the UNIQUE constraint may no longer hold for
129013 * -- Stuff, so either OR REPLACE or OR IGNORE must be used.
129014 * INSERT OR REPLACE INTO rdb.Stuff (rowid, name, value )
129015 * SELECT rowid, name, value FROM temp.recover_Stuff;
129016 * DROP TABLE temp.recover_Stuff;
129017 * DETACH DATABASE rdb;
129018 * -- Move db.db to replace original db in filesystem.
129021 * Usage
129023 * Given the goal of dealing with corruption, it would not be safe to
129024 * create a recovery table in the database being recovered. So
129025 * recovery tables must be created in the temp database. They are not
129026 * appropriate to persist, in any case. [As a bonus, sqlite_master
129027 * tables can be recovered. Perhaps more cute than useful, though.]
129029 * The parameters are a specifier for the table to read, and a column
129030 * definition for each bit of data stored in that table. The named
129031 * table must be convertable to a root page number by reading the
129032 * sqlite_master table. Bare table names are assumed to be in
129033 * database 0 ("main"), other databases can be specified in db.table
129034 * fashion.
129036 * Column definitions are similar to BUT NOT THE SAME AS those
129037 * provided to CREATE statements:
129038 * column-def: column-name [type-name [STRICT] [NOT NULL]]
129039 * type-name: (ANY|ROWID|INTEGER|FLOAT|NUMERIC|TEXT|BLOB)
129041 * Only those exact type names are accepted, there is no type
129042 * intuition. The only constraints accepted are STRICT (see below)
129043 * and NOT NULL. Anything unexpected will cause the create to fail.
129045 * ANY is a convenience to indicate that manifest typing is desired.
129046 * It is equivalent to not specifying a type at all. The results for
129047 * such columns will have the type of the data's storage. The exposed
129048 * schema will contain no type for that column.
129050 * ROWID is used for columns representing aliases to the rowid
129051 * (INTEGER PRIMARY KEY, with or without AUTOINCREMENT), to make the
129052 * concept explicit. Such columns are actually stored as NULL, so
129053 * they cannot be simply ignored. The exposed schema will be INTEGER
129054 * for that column.
129056 * NOT NULL causes rows with a NULL in that column to be skipped. It
129057 * also adds NOT NULL to the column in the exposed schema. If the
129058 * table has ever had columns added using ALTER TABLE, then those
129059 * columns implicitly contain NULL for rows which have not been
129060 * updated. [Workaround using COALESCE() in your SELECT statement.]
129062 * The created table is read-only, with no indices. Any SELECT will
129063 * be a full-table scan, returning each valid row read from the
129064 * storage of the backing table. The rowid will be the rowid of the
129065 * row from the backing table. "Valid" means:
129066 * - The cell metadata for the row is well-formed. Mainly this means that
129067 * the cell header info describes a payload of the size indicated by
129068 * the cell's payload size.
129069 * - The cell does not run off the page.
129070 * - The cell does not overlap any other cell on the page.
129071 * - The cell contains doesn't contain too many columns.
129072 * - The types of the serialized data match the indicated types (see below).
129075 * Type affinity versus type storage.
129077 * http://www.sqlite.org/datatype3.html describes SQLite's type
129078 * affinity system. The system provides for automated coercion of
129079 * types in certain cases, transparently enough that many developers
129080 * do not realize that it is happening. Importantly, it implies that
129081 * the raw data stored in the database may not have the obvious type.
129083 * Differences between the stored data types and the expected data
129084 * types may be a signal of corruption. This module makes some
129085 * allowances for automatic coercion. It is important to be concious
129086 * of the difference between the schema exposed by the module, and the
129087 * data types read from storage. The following table describes how
129088 * the module interprets things:
129090 * type schema data STRICT
129091 * ---- ------ ---- ------
129092 * ANY <none> any any
129093 * ROWID INTEGER n/a n/a
129094 * INTEGER INTEGER integer integer
129095 * FLOAT FLOAT integer or float float
129096 * NUMERIC NUMERIC integer, float, or text integer or float
129097 * TEXT TEXT text or blob text
129098 * BLOB BLOB blob blob
129100 * type is the type provided to the recover module, schema is the
129101 * schema exposed by the module, data is the acceptable types of data
129102 * decoded from storage, and STRICT is a modification of that.
129104 * A very loose recovery system might use ANY for all columns, then
129105 * use the appropriate sqlite3_column_*() calls to coerce to expected
129106 * types. This doesn't provide much protection if a page from a
129107 * different table with the same column count is linked into an
129108 * inappropriate btree.
129110 * A very tight recovery system might use STRICT to enforce typing on
129111 * all columns, preferring to skip rows which are valid at the storage
129112 * level but don't contain the right types. Note that FLOAT STRICT is
129113 * almost certainly not appropriate, since integral values are
129114 * transparently stored as integers, when that is more efficient.
129116 * Another option is to use ANY for all columns and inspect each
129117 * result manually (using sqlite3_column_*). This should only be
129118 * necessary in cases where developers have used manifest typing (test
129119 * to make sure before you decide that you aren't using manifest
129120 * typing!).
129123 * Caveats
129125 * Leaf pages not referenced by interior nodes will not be found.
129127 * Leaf pages referenced from interior nodes of other tables will not
129128 * be resolved.
129130 * Rows referencing invalid overflow pages will be skipped.
129132 * SQlite rows have a header which describes how to interpret the rest
129133 * of the payload. The header can be valid in cases where the rest of
129134 * the record is actually corrupt (in the sense that the data is not
129135 * the intended data). This can especially happen WRT overflow pages,
129136 * as lack of atomic updates between pages is the primary form of
129137 * corruption I have seen in the wild.
129139 /* The implementation is via a series of cursors. The cursor
129140 * implementations follow the pattern:
129142 * // Creates the cursor using various initialization info.
129143 * int cursorCreate(...);
129145 * // Returns 1 if there is no more data, 0 otherwise.
129146 * int cursorEOF(Cursor *pCursor);
129148 * // Various accessors can be used if not at EOF.
129150 * // Move to the next item.
129151 * int cursorNext(Cursor *pCursor);
129153 * // Destroy the memory associated with the cursor.
129154 * void cursorDestroy(Cursor *pCursor);
129156 * References in the following are to sections at
129157 * http://www.sqlite.org/fileformat2.html .
129159 * RecoverLeafCursor iterates the records in a leaf table node
129160 * described in section 1.5 "B-tree Pages". When the node is
129161 * exhausted, an interior cursor is used to get the next leaf node,
129162 * and iteration continues there.
129164 * RecoverInteriorCursor iterates the child pages in an interior table
129165 * node described in section 1.5 "B-tree Pages". When the node is
129166 * exhausted, a parent interior cursor is used to get the next
129167 * interior node at the same level, and iteration continues there.
129169 * Together these record the path from the leaf level to the root of
129170 * the tree. Iteration happens from the leaves rather than the root
129171 * both for efficiency and putting the special case at the front of
129172 * the list is easier to implement.
129174 * RecoverCursor uses a RecoverLeafCursor to iterate the rows of a
129175 * table, returning results via the SQLite virtual table interface.
129177 /* TODO(shess): It might be useful to allow DEFAULT in types to
129178 * specify what to do for NULL when an ALTER TABLE case comes up.
129179 * Unfortunately, simply adding it to the exposed schema and using
129180 * sqlite3_result_null() does not cause the default to be generate.
129181 * Handling it ourselves seems hard, unfortunately.
129184 /* #include <assert.h> */
129185 /* #include <ctype.h> */
129186 /* #include <stdio.h> */
129187 /* #include <string.h> */
129189 /* Internal SQLite things that are used:
129190 * u32, u64, i64 types.
129191 * Btree, Pager, and DbPage structs.
129192 * DbPage.pData, .pPager, and .pgno
129193 * sqlite3 struct.
129194 * sqlite3BtreePager() and sqlite3BtreeGetPageSize()
129195 * sqlite3PagerAcquire() and sqlite3PagerUnref()
129196 * getVarint().
129199 /* For debugging. */
129200 #if 0
129201 #define FNENTRY() fprintf(stderr, "In %s\n", __FUNCTION__)
129202 #else
129203 #define FNENTRY()
129204 #endif
129206 /* Generic constants and helper functions. */
129208 static const unsigned char kTableLeafPage = 0x0D;
129209 static const unsigned char kTableInteriorPage = 0x05;
129211 /* From section 1.5. */
129212 static const unsigned kiPageTypeOffset = 0;
129213 static const unsigned kiPageFreeBlockOffset = 1;
129214 static const unsigned kiPageCellCountOffset = 3;
129215 static const unsigned kiPageCellContentOffset = 5;
129216 static const unsigned kiPageFragmentedBytesOffset = 7;
129217 static const unsigned knPageLeafHeaderBytes = 8;
129218 /* Interior pages contain an additional field. */
129219 static const unsigned kiPageRightChildOffset = 8;
129220 static const unsigned kiPageInteriorHeaderBytes = 12;
129222 /* Accepted types are specified by a mask. */
129223 #define MASK_ROWID (1<<0)
129224 #define MASK_INTEGER (1<<1)
129225 #define MASK_FLOAT (1<<2)
129226 #define MASK_TEXT (1<<3)
129227 #define MASK_BLOB (1<<4)
129228 #define MASK_NULL (1<<5)
129230 /* Helpers to decode fixed-size fields. */
129231 static u32 decodeUnsigned16(const unsigned char *pData){
129232 return (pData[0]<<8) + pData[1];
129234 static u32 decodeUnsigned32(const unsigned char *pData){
129235 return (decodeUnsigned16(pData)<<16) + decodeUnsigned16(pData+2);
129237 static i64 decodeSigned(const unsigned char *pData, unsigned nBytes){
129238 i64 r = (char)(*pData);
129239 while( --nBytes ){
129240 r <<= 8;
129241 r += *(++pData);
129243 return r;
129245 /* Derived from vdbeaux.c, sqlite3VdbeSerialGet(), case 7. */
129246 /* TODO(shess): Determine if swapMixedEndianFloat() applies. */
129247 static double decodeFloat64(const unsigned char *pData){
129248 #if !defined(NDEBUG)
129249 static const u64 t1 = ((u64)0x3ff00000)<<32;
129250 static const double r1 = 1.0;
129251 u64 t2 = t1;
129252 assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
129253 #endif
129254 i64 x = decodeSigned(pData, 8);
129255 double d;
129256 memcpy(&d, &x, sizeof(x));
129257 return d;
129260 /* Return true if a varint can safely be read from pData/nData. */
129261 /* TODO(shess): DbPage points into the middle of a buffer which
129262 * contains the page data before DbPage. So code should always be
129263 * able to read a small number of varints safely. Consider whether to
129264 * trust that or not.
129266 static int checkVarint(const unsigned char *pData, unsigned nData){
129267 unsigned i;
129269 /* In the worst case the decoder takes all 8 bits of the 9th byte. */
129270 if( nData>=9 ){
129271 return 1;
129274 /* Look for a high-bit-clear byte in what's left. */
129275 for( i=0; i<nData; ++i ){
129276 if( !(pData[i]&0x80) ){
129277 return 1;
129281 /* Cannot decode in the space given. */
129282 return 0;
129285 /* Return 1 if n varints can be read from pData/nData. */
129286 static int checkVarints(const unsigned char *pData, unsigned nData,
129287 unsigned n){
129288 unsigned nCur = 0; /* Byte offset within current varint. */
129289 unsigned nFound = 0; /* Number of varints found. */
129290 unsigned i;
129292 /* In the worst case the decoder takes all 8 bits of the 9th byte. */
129293 if( nData>=9*n ){
129294 return 1;
129297 for( i=0; nFound<n && i<nData; ++i ){
129298 nCur++;
129299 if( nCur==9 || !(pData[i]&0x80) ){
129300 nFound++;
129301 nCur = 0;
129305 return nFound==n;
129308 /* ctype and str[n]casecmp() can be affected by locale (eg, tr_TR).
129309 * These versions consider only the ASCII space.
129311 /* TODO(shess): It may be reasonable to just remove the need for these
129312 * entirely. The module could require "TEXT STRICT NOT NULL", not
129313 * "Text Strict Not Null" or whatever the developer felt like typing
129314 * that day. Handling corrupt data is a PERFECT place to be pedantic.
129316 static int ascii_isspace(char c){
129317 /* From fts3_expr.c */
129318 return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
129320 static int ascii_isalnum(int x){
129321 /* From fts3_tokenizer1.c */
129322 return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
129324 static int ascii_tolower(int x){
129325 /* From fts3_tokenizer1.c */
129326 return (x>='A' && x<='Z') ? x-'A'+'a' : x;
129328 /* TODO(shess): Consider sqlite3_strnicmp() */
129329 static int ascii_strncasecmp(const char *s1, const char *s2, size_t n){
129330 const unsigned char *us1 = (const unsigned char *)s1;
129331 const unsigned char *us2 = (const unsigned char *)s2;
129332 while( *us1 && *us2 && n && ascii_tolower(*us1)==ascii_tolower(*us2) ){
129333 us1++, us2++, n--;
129335 return n ? ascii_tolower(*us1)-ascii_tolower(*us2) : 0;
129337 static int ascii_strcasecmp(const char *s1, const char *s2){
129338 /* If s2 is equal through strlen(s1), will exit while() due to s1's
129339 * trailing NUL, and return NUL-s2[strlen(s1)].
129341 return ascii_strncasecmp(s1, s2, strlen(s1)+1);
129344 /* For some reason I kept making mistakes with offset calculations. */
129345 static const unsigned char *PageData(DbPage *pPage, unsigned iOffset){
129346 assert( iOffset<=pPage->nPageSize );
129347 return (unsigned char *)pPage->pData + iOffset;
129350 /* The first page in the file contains a file header in the first 100
129351 * bytes. The page's header information comes after that. Note that
129352 * the offsets in the page's header information are relative to the
129353 * beginning of the page, NOT the end of the page header.
129355 static const unsigned char *PageHeader(DbPage *pPage){
129356 if( pPage->pgno==1 ){
129357 const unsigned nDatabaseHeader = 100;
129358 return PageData(pPage, nDatabaseHeader);
129359 }else{
129360 return PageData(pPage, 0);
129364 /* Helper to fetch the pager and page size for the named database. */
129365 static int GetPager(sqlite3 *db, const char *zName,
129366 Pager **pPager, unsigned *pnPageSize){
129367 Btree *pBt = NULL;
129368 int i;
129369 for( i=0; i<db->nDb; ++i ){
129370 if( ascii_strcasecmp(db->aDb[i].zName, zName)==0 ){
129371 pBt = db->aDb[i].pBt;
129372 break;
129375 if( !pBt ){
129376 return SQLITE_ERROR;
129379 *pPager = sqlite3BtreePager(pBt);
129380 *pnPageSize = sqlite3BtreeGetPageSize(pBt) - sqlite3BtreeGetReserve(pBt);
129381 return SQLITE_OK;
129384 /* iSerialType is a type read from a record header. See "2.1 Record Format".
129387 /* Storage size of iSerialType in bytes. My interpretation of SQLite
129388 * documentation is that text and blob fields can have 32-bit length.
129389 * Values past 2^31-12 will need more than 32 bits to encode, which is
129390 * why iSerialType is u64.
129392 static u32 SerialTypeLength(u64 iSerialType){
129393 switch( iSerialType ){
129394 case 0 : return 0; /* NULL */
129395 case 1 : return 1; /* Various integers. */
129396 case 2 : return 2;
129397 case 3 : return 3;
129398 case 4 : return 4;
129399 case 5 : return 6;
129400 case 6 : return 8;
129401 case 7 : return 8; /* 64-bit float. */
129402 case 8 : return 0; /* Constant 0. */
129403 case 9 : return 0; /* Constant 1. */
129404 case 10 : case 11 : assert( !"RESERVED TYPE"); return 0;
129406 return (u32)((iSerialType>>1) - 6);
129409 /* True if iSerialType refers to a blob. */
129410 static int SerialTypeIsBlob(u64 iSerialType){
129411 assert( iSerialType>=12 );
129412 return (iSerialType%2)==0;
129415 /* Returns true if the serialized type represented by iSerialType is
129416 * compatible with the given type mask.
129418 static int SerialTypeIsCompatible(u64 iSerialType, unsigned char mask){
129419 switch( iSerialType ){
129420 case 0 : return (mask&MASK_NULL)!=0;
129421 case 1 : return (mask&MASK_INTEGER)!=0;
129422 case 2 : return (mask&MASK_INTEGER)!=0;
129423 case 3 : return (mask&MASK_INTEGER)!=0;
129424 case 4 : return (mask&MASK_INTEGER)!=0;
129425 case 5 : return (mask&MASK_INTEGER)!=0;
129426 case 6 : return (mask&MASK_INTEGER)!=0;
129427 case 7 : return (mask&MASK_FLOAT)!=0;
129428 case 8 : return (mask&MASK_INTEGER)!=0;
129429 case 9 : return (mask&MASK_INTEGER)!=0;
129430 case 10 : assert( !"RESERVED TYPE"); return 0;
129431 case 11 : assert( !"RESERVED TYPE"); return 0;
129433 return (mask&(SerialTypeIsBlob(iSerialType) ? MASK_BLOB : MASK_TEXT));
129436 /* Versions of strdup() with return values appropriate for
129437 * sqlite3_free(). malloc.c has sqlite3DbStrDup()/NDup(), but those
129438 * need sqlite3DbFree(), which seems intrusive.
129440 static char *sqlite3_strndup(const char *z, unsigned n){
129441 char *zNew;
129443 if( z==NULL ){
129444 return NULL;
129447 zNew = sqlite3_malloc(n+1);
129448 if( zNew!=NULL ){
129449 memcpy(zNew, z, n);
129450 zNew[n] = '\0';
129452 return zNew;
129454 static char *sqlite3_strdup(const char *z){
129455 if( z==NULL ){
129456 return NULL;
129458 return sqlite3_strndup(z, strlen(z));
129461 /* Fetch the page number of zTable in zDb from sqlite_master in zDb,
129462 * and put it in *piRootPage.
129464 static int getRootPage(sqlite3 *db, const char *zDb, const char *zTable,
129465 u32 *piRootPage){
129466 char *zSql; /* SQL selecting root page of named element. */
129467 sqlite3_stmt *pStmt;
129468 int rc;
129470 if( strcmp(zTable, "sqlite_master")==0 ){
129471 *piRootPage = 1;
129472 return SQLITE_OK;
129475 zSql = sqlite3_mprintf("SELECT rootpage FROM %s.sqlite_master "
129476 "WHERE type = 'table' AND tbl_name = %Q",
129477 zDb, zTable);
129478 if( !zSql ){
129479 return SQLITE_NOMEM;
129482 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
129483 sqlite3_free(zSql);
129484 if( rc!=SQLITE_OK ){
129485 return rc;
129488 /* Require a result. */
129489 rc = sqlite3_step(pStmt);
129490 if( rc==SQLITE_DONE ){
129491 rc = SQLITE_CORRUPT;
129492 }else if( rc==SQLITE_ROW ){
129493 *piRootPage = sqlite3_column_int(pStmt, 0);
129495 /* Require only one result. */
129496 rc = sqlite3_step(pStmt);
129497 if( rc==SQLITE_DONE ){
129498 rc = SQLITE_OK;
129499 }else if( rc==SQLITE_ROW ){
129500 rc = SQLITE_CORRUPT;
129503 sqlite3_finalize(pStmt);
129504 return rc;
129507 static int getEncoding(sqlite3 *db, const char *zDb, int* piEncoding){
129508 sqlite3_stmt *pStmt;
129509 int rc;
129510 char *zSql = sqlite3_mprintf("PRAGMA %s.encoding", zDb);
129511 if( !zSql ){
129512 return SQLITE_NOMEM;
129515 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
129516 sqlite3_free(zSql);
129517 if( rc!=SQLITE_OK ){
129518 return rc;
129521 /* Require a result. */
129522 rc = sqlite3_step(pStmt);
129523 if( rc==SQLITE_DONE ){
129524 /* This case should not be possible. */
129525 rc = SQLITE_CORRUPT;
129526 }else if( rc==SQLITE_ROW ){
129527 if( sqlite3_column_type(pStmt, 0)==SQLITE_TEXT ){
129528 const char* z = (const char *)sqlite3_column_text(pStmt, 0);
129529 /* These strings match the literals in pragma.c. */
129530 if( !strcmp(z, "UTF-16le") ){
129531 *piEncoding = SQLITE_UTF16LE;
129532 }else if( !strcmp(z, "UTF-16be") ){
129533 *piEncoding = SQLITE_UTF16BE;
129534 }else if( !strcmp(z, "UTF-8") ){
129535 *piEncoding = SQLITE_UTF8;
129536 }else{
129537 /* This case should not be possible. */
129538 *piEncoding = SQLITE_UTF8;
129540 }else{
129541 /* This case should not be possible. */
129542 *piEncoding = SQLITE_UTF8;
129545 /* Require only one result. */
129546 rc = sqlite3_step(pStmt);
129547 if( rc==SQLITE_DONE ){
129548 rc = SQLITE_OK;
129549 }else if( rc==SQLITE_ROW ){
129550 /* This case should not be possible. */
129551 rc = SQLITE_CORRUPT;
129554 sqlite3_finalize(pStmt);
129555 return rc;
129558 /* Cursor for iterating interior nodes. Interior page cells contain a
129559 * child page number and a rowid. The child page contains items left
129560 * of the rowid (less than). The rightmost page of the subtree is
129561 * stored in the page header.
129563 * interiorCursorDestroy - release all resources associated with the
129564 * cursor and any parent cursors.
129565 * interiorCursorCreate - create a cursor with the given parent and page.
129566 * interiorCursorEOF - returns true if neither the cursor nor the
129567 * parent cursors can return any more data.
129568 * interiorCursorNextPage - fetch the next child page from the cursor.
129570 * Logically, interiorCursorNextPage() returns the next child page
129571 * number from the page the cursor is currently reading, calling the
129572 * parent cursor as necessary to get new pages to read, until done.
129573 * SQLITE_ROW if a page is returned, SQLITE_DONE if out of pages,
129574 * error otherwise. Unfortunately, if the table is corrupted
129575 * unexpected pages can be returned. If any unexpected page is found,
129576 * leaf or otherwise, it is returned to the caller for processing,
129577 * with the interior cursor left empty. The next call to
129578 * interiorCursorNextPage() will recurse to the parent cursor until an
129579 * interior page to iterate is returned.
129581 * Note that while interiorCursorNextPage() will refuse to follow
129582 * loops, it does not keep track of pages returned for purposes of
129583 * preventing duplication.
129585 * Note that interiorCursorEOF() could return false (not at EOF), and
129586 * interiorCursorNextPage() could still return SQLITE_DONE. This
129587 * could happen if there are more cells to iterate in an interior
129588 * page, but those cells refer to invalid pages.
129590 typedef struct RecoverInteriorCursor RecoverInteriorCursor;
129591 struct RecoverInteriorCursor {
129592 RecoverInteriorCursor *pParent; /* Parent node to this node. */
129593 DbPage *pPage; /* Reference to leaf page. */
129594 unsigned nPageSize; /* Size of page. */
129595 unsigned nChildren; /* Number of children on the page. */
129596 unsigned iChild; /* Index of next child to return. */
129599 static void interiorCursorDestroy(RecoverInteriorCursor *pCursor){
129600 /* Destroy all the cursors to the root. */
129601 while( pCursor ){
129602 RecoverInteriorCursor *p = pCursor;
129603 pCursor = pCursor->pParent;
129605 if( p->pPage ){
129606 sqlite3PagerUnref(p->pPage);
129607 p->pPage = NULL;
129610 memset(p, 0xA5, sizeof(*p));
129611 sqlite3_free(p);
129615 /* Internal helper. Reset storage in preparation for iterating pPage. */
129616 static void interiorCursorSetPage(RecoverInteriorCursor *pCursor,
129617 DbPage *pPage){
129618 const unsigned knMinCellLength = 2 + 4 + 1;
129619 unsigned nMaxChildren;
129620 assert( PageHeader(pPage)[kiPageTypeOffset]==kTableInteriorPage );
129622 if( pCursor->pPage ){
129623 sqlite3PagerUnref(pCursor->pPage);
129624 pCursor->pPage = NULL;
129626 pCursor->pPage = pPage;
129627 pCursor->iChild = 0;
129629 /* A child for each cell, plus one in the header. */
129630 pCursor->nChildren = decodeUnsigned16(PageHeader(pPage) +
129631 kiPageCellCountOffset) + 1;
129633 /* Each child requires a 16-bit offset from an array after the header,
129634 * and each child contains a 32-bit page number and at least a varint
129635 * (min size of one byte). The final child page is in the header. So
129636 * the maximum value for nChildren is:
129637 * (nPageSize - kiPageInteriorHeaderBytes) /
129638 * (sizeof(uint16) + sizeof(uint32) + 1) + 1
129640 /* TODO(shess): This count is very unlikely to be corrupted in
129641 * isolation, so seeing this could signal to skip the page. OTOH, I
129642 * can't offhand think of how to get here unless this or the page-type
129643 * byte is corrupted. Could be an overflow page, but it would require
129644 * a very large database.
129646 nMaxChildren =
129647 (pCursor->nPageSize - kiPageInteriorHeaderBytes) / knMinCellLength + 1;
129648 if (pCursor->nChildren > nMaxChildren) {
129649 pCursor->nChildren = nMaxChildren;
129653 static int interiorCursorCreate(RecoverInteriorCursor *pParent,
129654 DbPage *pPage, int nPageSize,
129655 RecoverInteriorCursor **ppCursor){
129656 RecoverInteriorCursor *pCursor =
129657 sqlite3_malloc(sizeof(RecoverInteriorCursor));
129658 if( !pCursor ){
129659 return SQLITE_NOMEM;
129662 memset(pCursor, 0, sizeof(*pCursor));
129663 pCursor->pParent = pParent;
129664 pCursor->nPageSize = nPageSize;
129665 interiorCursorSetPage(pCursor, pPage);
129666 *ppCursor = pCursor;
129667 return SQLITE_OK;
129670 /* Internal helper. Return the child page number at iChild. */
129671 static unsigned interiorCursorChildPage(RecoverInteriorCursor *pCursor){
129672 const unsigned char *pPageHeader; /* Header of the current page. */
129673 const unsigned char *pCellOffsets; /* Offset to page's cell offsets. */
129674 unsigned iCellOffset; /* Offset of target cell. */
129676 assert( pCursor->iChild<pCursor->nChildren );
129678 /* Rightmost child is in the header. */
129679 pPageHeader = PageHeader(pCursor->pPage);
129680 if( pCursor->iChild==pCursor->nChildren-1 ){
129681 return decodeUnsigned32(pPageHeader + kiPageRightChildOffset);
129684 /* Each cell is a 4-byte integer page number and a varint rowid
129685 * which is greater than the rowid of items in that sub-tree (this
129686 * module ignores ordering). The offset is from the beginning of the
129687 * page, not from the page header.
129689 pCellOffsets = pPageHeader + kiPageInteriorHeaderBytes;
129690 iCellOffset = decodeUnsigned16(pCellOffsets + pCursor->iChild*2);
129691 if( iCellOffset<=pCursor->nPageSize-4 ){
129692 return decodeUnsigned32(PageData(pCursor->pPage, iCellOffset));
129695 /* TODO(shess): Check for cell overlaps? Cells require 4 bytes plus
129696 * a varint. Check could be identical to leaf check (or even a
129697 * shared helper testing for "Cells starting in this range"?).
129700 /* If the offset is broken, return an invalid page number. */
129701 return 0;
129704 static int interiorCursorEOF(RecoverInteriorCursor *pCursor){
129705 /* Find a parent with remaining children. EOF if none found. */
129706 while( pCursor && pCursor->iChild>=pCursor->nChildren ){
129707 pCursor = pCursor->pParent;
129709 return pCursor==NULL;
129712 /* Internal helper. Used to detect if iPage would cause a loop. */
129713 static int interiorCursorPageInUse(RecoverInteriorCursor *pCursor,
129714 unsigned iPage){
129715 /* Find any parent using the indicated page. */
129716 while( pCursor && pCursor->pPage->pgno!=iPage ){
129717 pCursor = pCursor->pParent;
129719 return pCursor!=NULL;
129722 /* Get the next page from the interior cursor at *ppCursor. Returns
129723 * SQLITE_ROW with the page in *ppPage, or SQLITE_DONE if out of
129724 * pages, or the error SQLite returned.
129726 * If the tree is uneven, then when the cursor attempts to get a new
129727 * interior page from the parent cursor, it may get a non-interior
129728 * page. In that case, the new page is returned, and *ppCursor is
129729 * updated to point to the parent cursor (this cursor is freed).
129731 /* TODO(shess): I've tried to avoid recursion in most of this code,
129732 * but this case is more challenging because the recursive call is in
129733 * the middle of operation. One option for converting it without
129734 * adding memory management would be to retain the head pointer and
129735 * use a helper to "back up" as needed. Another option would be to
129736 * reverse the list during traversal.
129738 static int interiorCursorNextPage(RecoverInteriorCursor **ppCursor,
129739 DbPage **ppPage){
129740 RecoverInteriorCursor *pCursor = *ppCursor;
129741 while( 1 ){
129742 int rc;
129743 const unsigned char *pPageHeader; /* Header of found page. */
129745 /* Find a valid child page which isn't on the stack. */
129746 while( pCursor->iChild<pCursor->nChildren ){
129747 const unsigned iPage = interiorCursorChildPage(pCursor);
129748 pCursor->iChild++;
129749 if( interiorCursorPageInUse(pCursor, iPage) ){
129750 fprintf(stderr, "Loop detected at %d\n", iPage);
129751 }else{
129752 int rc = sqlite3PagerAcquire(pCursor->pPage->pPager, iPage, ppPage, 0);
129753 if( rc==SQLITE_OK ){
129754 return SQLITE_ROW;
129759 /* This page has no more children. Get next page from parent. */
129760 if( !pCursor->pParent ){
129761 return SQLITE_DONE;
129763 rc = interiorCursorNextPage(&pCursor->pParent, ppPage);
129764 if( rc!=SQLITE_ROW ){
129765 return rc;
129768 /* If a non-interior page is received, that either means that the
129769 * tree is uneven, or that a child was re-used (say as an overflow
129770 * page). Remove this cursor and let the caller handle the page.
129772 pPageHeader = PageHeader(*ppPage);
129773 if( pPageHeader[kiPageTypeOffset]!=kTableInteriorPage ){
129774 *ppCursor = pCursor->pParent;
129775 pCursor->pParent = NULL;
129776 interiorCursorDestroy(pCursor);
129777 return SQLITE_ROW;
129780 /* Iterate the new page. */
129781 interiorCursorSetPage(pCursor, *ppPage);
129782 *ppPage = NULL;
129785 assert(NULL); /* NOTREACHED() */
129786 return SQLITE_CORRUPT;
129789 /* Large rows are spilled to overflow pages. The row's main page
129790 * stores the overflow page number after the local payload, with a
129791 * linked list forward from there as necessary. overflowMaybeCreate()
129792 * and overflowGetSegment() provide an abstraction for accessing such
129793 * data while centralizing the code.
129795 * overflowDestroy - releases all resources associated with the structure.
129796 * overflowMaybeCreate - create the overflow structure if it is needed
129797 * to represent the given record. See function comment.
129798 * overflowGetSegment - fetch a segment from the record, accounting
129799 * for overflow pages. Segments which are not
129800 * entirely contained with a page are constructed
129801 * into a buffer which is returned. See function comment.
129803 typedef struct RecoverOverflow RecoverOverflow;
129804 struct RecoverOverflow {
129805 RecoverOverflow *pNextOverflow;
129806 DbPage *pPage;
129807 unsigned nPageSize;
129810 static void overflowDestroy(RecoverOverflow *pOverflow){
129811 while( pOverflow ){
129812 RecoverOverflow *p = pOverflow;
129813 pOverflow = p->pNextOverflow;
129815 if( p->pPage ){
129816 sqlite3PagerUnref(p->pPage);
129817 p->pPage = NULL;
129820 memset(p, 0xA5, sizeof(*p));
129821 sqlite3_free(p);
129825 /* Internal helper. Used to detect if iPage would cause a loop. */
129826 static int overflowPageInUse(RecoverOverflow *pOverflow, unsigned iPage){
129827 while( pOverflow && pOverflow->pPage->pgno!=iPage ){
129828 pOverflow = pOverflow->pNextOverflow;
129830 return pOverflow!=NULL;
129833 /* Setup to access an nRecordBytes record beginning at iRecordOffset
129834 * in pPage. If nRecordBytes can be satisfied entirely from pPage,
129835 * then no overflow pages are needed an *pnLocalRecordBytes is set to
129836 * nRecordBytes. Otherwise, *ppOverflow is set to the head of a list
129837 * of overflow pages, and *pnLocalRecordBytes is set to the number of
129838 * bytes local to pPage.
129840 * overflowGetSegment() will do the right thing regardless of whether
129841 * those values are set to be in-page or not.
129843 static int overflowMaybeCreate(DbPage *pPage, unsigned nPageSize,
129844 unsigned iRecordOffset, unsigned nRecordBytes,
129845 unsigned *pnLocalRecordBytes,
129846 RecoverOverflow **ppOverflow){
129847 unsigned nLocalRecordBytes; /* Record bytes in the leaf page. */
129848 unsigned iNextPage; /* Next page number for record data. */
129849 unsigned nBytes; /* Maximum record bytes as of current page. */
129850 int rc;
129851 RecoverOverflow *pFirstOverflow; /* First in linked list of pages. */
129852 RecoverOverflow *pLastOverflow; /* End of linked list. */
129854 /* Calculations from the "Table B-Tree Leaf Cell" part of section
129855 * 1.5 of http://www.sqlite.org/fileformat2.html . maxLocal and
129856 * minLocal to match naming in btree.c.
129858 const unsigned maxLocal = nPageSize - 35;
129859 const unsigned minLocal = ((nPageSize-12)*32/255)-23; /* m */
129861 /* Always fit anything smaller than maxLocal. */
129862 if( nRecordBytes<=maxLocal ){
129863 *pnLocalRecordBytes = nRecordBytes;
129864 *ppOverflow = NULL;
129865 return SQLITE_OK;
129868 /* Calculate the remainder after accounting for minLocal on the leaf
129869 * page and what packs evenly into overflow pages. If the remainder
129870 * does not fit into maxLocal, then a partially-full overflow page
129871 * will be required in any case, so store as little as possible locally.
129873 nLocalRecordBytes = minLocal+((nRecordBytes-minLocal)%(nPageSize-4));
129874 if( maxLocal<nLocalRecordBytes ){
129875 nLocalRecordBytes = minLocal;
129878 /* Don't read off the end of the page. */
129879 if( iRecordOffset+nLocalRecordBytes+4>nPageSize ){
129880 return SQLITE_CORRUPT;
129883 /* First overflow page number is after the local bytes. */
129884 iNextPage =
129885 decodeUnsigned32(PageData(pPage, iRecordOffset + nLocalRecordBytes));
129886 nBytes = nLocalRecordBytes;
129888 /* While there are more pages to read, and more bytes are needed,
129889 * get another page.
129891 pFirstOverflow = pLastOverflow = NULL;
129892 rc = SQLITE_OK;
129893 while( iNextPage && nBytes<nRecordBytes ){
129894 RecoverOverflow *pOverflow; /* New overflow page for the list. */
129896 rc = sqlite3PagerAcquire(pPage->pPager, iNextPage, &pPage, 0);
129897 if( rc!=SQLITE_OK ){
129898 break;
129901 pOverflow = sqlite3_malloc(sizeof(RecoverOverflow));
129902 if( !pOverflow ){
129903 sqlite3PagerUnref(pPage);
129904 rc = SQLITE_NOMEM;
129905 break;
129907 memset(pOverflow, 0, sizeof(*pOverflow));
129908 pOverflow->pPage = pPage;
129909 pOverflow->nPageSize = nPageSize;
129911 if( !pFirstOverflow ){
129912 pFirstOverflow = pOverflow;
129913 }else{
129914 pLastOverflow->pNextOverflow = pOverflow;
129916 pLastOverflow = pOverflow;
129918 iNextPage = decodeUnsigned32(pPage->pData);
129919 nBytes += nPageSize-4;
129921 /* Avoid loops. */
129922 if( overflowPageInUse(pFirstOverflow, iNextPage) ){
129923 fprintf(stderr, "Overflow loop detected at %d\n", iNextPage);
129924 rc = SQLITE_CORRUPT;
129925 break;
129929 /* If there were not enough pages, or too many, things are corrupt.
129930 * Not having enough pages is an obvious problem, all the data
129931 * cannot be read. Too many pages means that the contents of the
129932 * row between the main page and the overflow page(s) is
129933 * inconsistent (most likely one or more of the overflow pages does
129934 * not really belong to this row).
129936 if( rc==SQLITE_OK && (nBytes<nRecordBytes || iNextPage) ){
129937 rc = SQLITE_CORRUPT;
129940 if( rc==SQLITE_OK ){
129941 *ppOverflow = pFirstOverflow;
129942 *pnLocalRecordBytes = nLocalRecordBytes;
129943 }else if( pFirstOverflow ){
129944 overflowDestroy(pFirstOverflow);
129946 return rc;
129949 /* Use in concert with overflowMaybeCreate() to efficiently read parts
129950 * of a potentially-overflowing record. pPage and iRecordOffset are
129951 * the values passed into overflowMaybeCreate(), nLocalRecordBytes and
129952 * pOverflow are the values returned by that call.
129954 * On SQLITE_OK, *ppBase points to nRequestBytes of data at
129955 * iRequestOffset within the record. If the data exists contiguously
129956 * in a page, a direct pointer is returned, otherwise a buffer from
129957 * sqlite3_malloc() is returned with the data. *pbFree is set true if
129958 * sqlite3_free() should be called on *ppBase.
129960 /* Operation of this function is subtle. At any time, pPage is the
129961 * current page, with iRecordOffset and nLocalRecordBytes being record
129962 * data within pPage, and pOverflow being the overflow page after
129963 * pPage. This allows the code to handle both the initial leaf page
129964 * and overflow pages consistently by adjusting the values
129965 * appropriately.
129967 static int overflowGetSegment(DbPage *pPage, unsigned iRecordOffset,
129968 unsigned nLocalRecordBytes,
129969 RecoverOverflow *pOverflow,
129970 unsigned iRequestOffset, unsigned nRequestBytes,
129971 unsigned char **ppBase, int *pbFree){
129972 unsigned nBase; /* Amount of data currently collected. */
129973 unsigned char *pBase; /* Buffer to collect record data into. */
129975 /* Skip to the page containing the start of the data. */
129976 while( iRequestOffset>=nLocalRecordBytes && pOverflow ){
129977 /* Factor out current page's contribution. */
129978 iRequestOffset -= nLocalRecordBytes;
129980 /* Move forward to the next page in the list. */
129981 pPage = pOverflow->pPage;
129982 iRecordOffset = 4;
129983 nLocalRecordBytes = pOverflow->nPageSize - iRecordOffset;
129984 pOverflow = pOverflow->pNextOverflow;
129987 /* If the requested data is entirely within this page, return a
129988 * pointer into the page.
129990 if( iRequestOffset+nRequestBytes<=nLocalRecordBytes ){
129991 /* TODO(shess): "assignment discards qualifiers from pointer target type"
129992 * Having ppBase be const makes sense, but sqlite3_free() takes non-const.
129994 *ppBase = (unsigned char *)PageData(pPage, iRecordOffset + iRequestOffset);
129995 *pbFree = 0;
129996 return SQLITE_OK;
129999 /* The data range would require additional pages. */
130000 if( !pOverflow ){
130001 /* Should never happen, the range is outside the nRecordBytes
130002 * passed to overflowMaybeCreate().
130004 assert(NULL); /* NOTREACHED */
130005 return SQLITE_ERROR;
130008 /* Get a buffer to construct into. */
130009 nBase = 0;
130010 pBase = sqlite3_malloc(nRequestBytes);
130011 if( !pBase ){
130012 return SQLITE_NOMEM;
130014 while( nBase<nRequestBytes ){
130015 /* Copy over data present on this page. */
130016 unsigned nCopyBytes = nRequestBytes - nBase;
130017 if( nLocalRecordBytes-iRequestOffset<nCopyBytes ){
130018 nCopyBytes = nLocalRecordBytes - iRequestOffset;
130020 memcpy(pBase + nBase, PageData(pPage, iRecordOffset + iRequestOffset),
130021 nCopyBytes);
130022 nBase += nCopyBytes;
130024 if( pOverflow ){
130025 /* Copy from start of record data in future pages. */
130026 iRequestOffset = 0;
130028 /* Move forward to the next page in the list. Should match
130029 * first while() loop.
130031 pPage = pOverflow->pPage;
130032 iRecordOffset = 4;
130033 nLocalRecordBytes = pOverflow->nPageSize - iRecordOffset;
130034 pOverflow = pOverflow->pNextOverflow;
130035 }else if( nBase<nRequestBytes ){
130036 /* Ran out of overflow pages with data left to deliver. Not
130037 * possible if the requested range fits within nRecordBytes
130038 * passed to overflowMaybeCreate() when creating pOverflow.
130040 assert(NULL); /* NOTREACHED */
130041 sqlite3_free(pBase);
130042 return SQLITE_ERROR;
130045 assert( nBase==nRequestBytes );
130046 *ppBase = pBase;
130047 *pbFree = 1;
130048 return SQLITE_OK;
130051 /* Primary structure for iterating the contents of a table.
130053 * leafCursorDestroy - release all resources associated with the cursor.
130054 * leafCursorCreate - create a cursor to iterate items from tree at
130055 * the provided root page.
130056 * leafCursorNextValidCell - get the cursor ready to access data from
130057 * the next valid cell in the table.
130058 * leafCursorCellRowid - get the current cell's rowid.
130059 * leafCursorCellColumns - get current cell's column count.
130060 * leafCursorCellColInfo - get type and data for a column in current cell.
130062 * leafCursorNextValidCell skips cells which fail simple integrity
130063 * checks, such as overlapping other cells, or being located at
130064 * impossible offsets, or where header data doesn't correctly describe
130065 * payload data. Returns SQLITE_ROW if a valid cell is found,
130066 * SQLITE_DONE if all pages in the tree were exhausted.
130068 * leafCursorCellColInfo() accounts for overflow pages in the style of
130069 * overflowGetSegment().
130071 typedef struct RecoverLeafCursor RecoverLeafCursor;
130072 struct RecoverLeafCursor {
130073 RecoverInteriorCursor *pParent; /* Parent node to this node. */
130074 DbPage *pPage; /* Reference to leaf page. */
130075 unsigned nPageSize; /* Size of pPage. */
130076 unsigned nCells; /* Number of cells in pPage. */
130077 unsigned iCell; /* Current cell. */
130079 /* Info parsed from data in iCell. */
130080 i64 iRowid; /* rowid parsed. */
130081 unsigned nRecordCols; /* how many items in the record. */
130082 u64 iRecordOffset; /* offset to record data. */
130083 /* TODO(shess): nRecordBytes and nRecordHeaderBytes are used in
130084 * leafCursorCellColInfo() to prevent buffer overruns.
130085 * leafCursorCellDecode() already verified that the cell is valid, so
130086 * those checks should be redundant.
130088 u64 nRecordBytes; /* Size of record data. */
130089 unsigned nLocalRecordBytes; /* Amount of record data in-page. */
130090 unsigned nRecordHeaderBytes; /* Size of record header data. */
130091 unsigned char *pRecordHeader; /* Pointer to record header data. */
130092 int bFreeRecordHeader; /* True if record header requires free. */
130093 RecoverOverflow *pOverflow; /* Cell overflow info, if needed. */
130096 /* Internal helper shared between next-page and create-cursor. If
130097 * pPage is a leaf page, it will be stored in the cursor and state
130098 * initialized for reading cells.
130100 * If pPage is an interior page, a new parent cursor is created and
130101 * injected on the stack. This is necessary to handle trees with
130102 * uneven depth, but also is used during initial setup.
130104 * If pPage is not a table page at all, it is discarded.
130106 * If SQLITE_OK is returned, the caller no longer owns pPage,
130107 * otherwise the caller is responsible for discarding it.
130109 static int leafCursorLoadPage(RecoverLeafCursor *pCursor, DbPage *pPage){
130110 const unsigned char *pPageHeader; /* Header of *pPage */
130112 /* Release the current page. */
130113 if( pCursor->pPage ){
130114 sqlite3PagerUnref(pCursor->pPage);
130115 pCursor->pPage = NULL;
130116 pCursor->iCell = pCursor->nCells = 0;
130119 /* If the page is an unexpected interior node, inject a new stack
130120 * layer and try again from there.
130122 pPageHeader = PageHeader(pPage);
130123 if( pPageHeader[kiPageTypeOffset]==kTableInteriorPage ){
130124 RecoverInteriorCursor *pParent;
130125 int rc = interiorCursorCreate(pCursor->pParent, pPage, pCursor->nPageSize,
130126 &pParent);
130127 if( rc!=SQLITE_OK ){
130128 return rc;
130130 pCursor->pParent = pParent;
130131 return SQLITE_OK;
130134 /* Not a leaf page, skip it. */
130135 if( pPageHeader[kiPageTypeOffset]!=kTableLeafPage ){
130136 sqlite3PagerUnref(pPage);
130137 return SQLITE_OK;
130140 /* Take ownership of the page and start decoding. */
130141 pCursor->pPage = pPage;
130142 pCursor->iCell = 0;
130143 pCursor->nCells = decodeUnsigned16(pPageHeader + kiPageCellCountOffset);
130144 return SQLITE_OK;
130147 /* Get the next leaf-level page in the tree. Returns SQLITE_ROW when
130148 * a leaf page is found, SQLITE_DONE when no more leaves exist, or any
130149 * error which occurred.
130151 static int leafCursorNextPage(RecoverLeafCursor *pCursor){
130152 if( !pCursor->pParent ){
130153 return SQLITE_DONE;
130156 /* Repeatedly load the parent's next child page until a leaf is found. */
130158 DbPage *pNextPage;
130159 int rc = interiorCursorNextPage(&pCursor->pParent, &pNextPage);
130160 if( rc!=SQLITE_ROW ){
130161 assert( rc==SQLITE_DONE );
130162 return rc;
130165 rc = leafCursorLoadPage(pCursor, pNextPage);
130166 if( rc!=SQLITE_OK ){
130167 sqlite3PagerUnref(pNextPage);
130168 return rc;
130170 } while( !pCursor->pPage );
130172 return SQLITE_ROW;
130175 static void leafCursorDestroyCellData(RecoverLeafCursor *pCursor){
130176 if( pCursor->bFreeRecordHeader ){
130177 sqlite3_free(pCursor->pRecordHeader);
130179 pCursor->bFreeRecordHeader = 0;
130180 pCursor->pRecordHeader = NULL;
130182 if( pCursor->pOverflow ){
130183 overflowDestroy(pCursor->pOverflow);
130184 pCursor->pOverflow = NULL;
130188 static void leafCursorDestroy(RecoverLeafCursor *pCursor){
130189 leafCursorDestroyCellData(pCursor);
130191 if( pCursor->pParent ){
130192 interiorCursorDestroy(pCursor->pParent);
130193 pCursor->pParent = NULL;
130196 if( pCursor->pPage ){
130197 sqlite3PagerUnref(pCursor->pPage);
130198 pCursor->pPage = NULL;
130201 memset(pCursor, 0xA5, sizeof(*pCursor));
130202 sqlite3_free(pCursor);
130205 /* Create a cursor to iterate the rows from the leaf pages of a table
130206 * rooted at iRootPage.
130208 /* TODO(shess): recoverOpen() calls this to setup the cursor, and I
130209 * think that recoverFilter() may make a hard assumption that the
130210 * cursor returned will turn up at least one valid cell.
130212 * The cases I can think of which break this assumption are:
130213 * - pPage is a valid leaf page with no valid cells.
130214 * - pPage is a valid interior page with no valid leaves.
130215 * - pPage is a valid interior page who's leaves contain no valid cells.
130216 * - pPage is not a valid leaf or interior page.
130218 static int leafCursorCreate(Pager *pPager, unsigned nPageSize,
130219 u32 iRootPage, RecoverLeafCursor **ppCursor){
130220 DbPage *pPage; /* Reference to page at iRootPage. */
130221 RecoverLeafCursor *pCursor; /* Leaf cursor being constructed. */
130222 int rc;
130224 /* Start out with the root page. */
130225 rc = sqlite3PagerAcquire(pPager, iRootPage, &pPage, 0);
130226 if( rc!=SQLITE_OK ){
130227 return rc;
130230 pCursor = sqlite3_malloc(sizeof(RecoverLeafCursor));
130231 if( !pCursor ){
130232 sqlite3PagerUnref(pPage);
130233 return SQLITE_NOMEM;
130235 memset(pCursor, 0, sizeof(*pCursor));
130237 pCursor->nPageSize = nPageSize;
130239 rc = leafCursorLoadPage(pCursor, pPage);
130240 if( rc!=SQLITE_OK ){
130241 sqlite3PagerUnref(pPage);
130242 leafCursorDestroy(pCursor);
130243 return rc;
130246 /* pPage wasn't a leaf page, find the next leaf page. */
130247 if( !pCursor->pPage ){
130248 rc = leafCursorNextPage(pCursor);
130249 if( rc!=SQLITE_DONE && rc!=SQLITE_ROW ){
130250 leafCursorDestroy(pCursor);
130251 return rc;
130255 *ppCursor = pCursor;
130256 return SQLITE_OK;
130259 /* Useful for setting breakpoints. */
130260 static int ValidateError(){
130261 return SQLITE_ERROR;
130264 /* Setup the cursor for reading the information from cell iCell. */
130265 static int leafCursorCellDecode(RecoverLeafCursor *pCursor){
130266 const unsigned char *pPageHeader; /* Header of current page. */
130267 const unsigned char *pPageEnd; /* Byte after end of current page. */
130268 const unsigned char *pCellOffsets; /* Pointer to page's cell offsets. */
130269 unsigned iCellOffset; /* Offset of current cell (iCell). */
130270 const unsigned char *pCell; /* Pointer to data at iCellOffset. */
130271 unsigned nCellMaxBytes; /* Maximum local size of iCell. */
130272 unsigned iEndOffset; /* End of iCell's in-page data. */
130273 u64 nRecordBytes; /* Expected size of cell, w/overflow. */
130274 u64 iRowid; /* iCell's rowid (in table). */
130275 unsigned nRead; /* Amount of cell read. */
130276 unsigned nRecordHeaderRead; /* Header data read. */
130277 u64 nRecordHeaderBytes; /* Header size expected. */
130278 unsigned nRecordCols; /* Columns read from header. */
130279 u64 nRecordColBytes; /* Bytes in payload for those columns. */
130280 unsigned i;
130281 int rc;
130283 assert( pCursor->iCell<pCursor->nCells );
130285 leafCursorDestroyCellData(pCursor);
130287 /* Find the offset to the row. */
130288 pPageHeader = PageHeader(pCursor->pPage);
130289 pCellOffsets = pPageHeader + knPageLeafHeaderBytes;
130290 pPageEnd = PageData(pCursor->pPage, pCursor->nPageSize);
130291 if( pCellOffsets + pCursor->iCell*2 + 2 > pPageEnd ){
130292 return ValidateError();
130294 iCellOffset = decodeUnsigned16(pCellOffsets + pCursor->iCell*2);
130295 if( iCellOffset>=pCursor->nPageSize ){
130296 return ValidateError();
130299 pCell = PageData(pCursor->pPage, iCellOffset);
130300 nCellMaxBytes = pCursor->nPageSize - iCellOffset;
130302 /* B-tree leaf cells lead with varint record size, varint rowid and
130303 * varint header size.
130305 /* TODO(shess): The smallest page size is 512 bytes, which has an m
130306 * of 39. Three varints need at most 27 bytes to encode. I think.
130308 if( !checkVarints(pCell, nCellMaxBytes, 3) ){
130309 return ValidateError();
130312 nRead = getVarint(pCell, &nRecordBytes);
130313 assert( iCellOffset+nRead<=pCursor->nPageSize );
130314 pCursor->nRecordBytes = nRecordBytes;
130316 nRead += getVarint(pCell + nRead, &iRowid);
130317 assert( iCellOffset+nRead<=pCursor->nPageSize );
130318 pCursor->iRowid = (i64)iRowid;
130320 pCursor->iRecordOffset = iCellOffset + nRead;
130322 /* Start overflow setup here because nLocalRecordBytes is needed to
130323 * check cell overlap.
130325 rc = overflowMaybeCreate(pCursor->pPage, pCursor->nPageSize,
130326 pCursor->iRecordOffset, pCursor->nRecordBytes,
130327 &pCursor->nLocalRecordBytes,
130328 &pCursor->pOverflow);
130329 if( rc!=SQLITE_OK ){
130330 return ValidateError();
130333 /* Check that no other cell starts within this cell. */
130334 iEndOffset = pCursor->iRecordOffset + pCursor->nLocalRecordBytes;
130335 for( i=0; i<pCursor->nCells && pCellOffsets + i*2 + 2 <= pPageEnd; ++i ){
130336 const unsigned iOtherOffset = decodeUnsigned16(pCellOffsets + i*2);
130337 if( iOtherOffset>iCellOffset && iOtherOffset<iEndOffset ){
130338 return ValidateError();
130342 nRecordHeaderRead = getVarint(pCell + nRead, &nRecordHeaderBytes);
130343 assert( nRecordHeaderBytes<=nRecordBytes );
130344 pCursor->nRecordHeaderBytes = nRecordHeaderBytes;
130346 /* Large headers could overflow if pages are small. */
130347 rc = overflowGetSegment(pCursor->pPage,
130348 pCursor->iRecordOffset, pCursor->nLocalRecordBytes,
130349 pCursor->pOverflow, 0, nRecordHeaderBytes,
130350 &pCursor->pRecordHeader, &pCursor->bFreeRecordHeader);
130351 if( rc!=SQLITE_OK ){
130352 return ValidateError();
130355 /* Tally up the column count and size of data. */
130356 nRecordCols = 0;
130357 nRecordColBytes = 0;
130358 while( nRecordHeaderRead<nRecordHeaderBytes ){
130359 u64 iSerialType; /* Type descriptor for current column. */
130360 if( !checkVarint(pCursor->pRecordHeader + nRecordHeaderRead,
130361 nRecordHeaderBytes - nRecordHeaderRead) ){
130362 return ValidateError();
130364 nRecordHeaderRead += getVarint(pCursor->pRecordHeader + nRecordHeaderRead,
130365 &iSerialType);
130366 if( iSerialType==10 || iSerialType==11 ){
130367 return ValidateError();
130369 nRecordColBytes += SerialTypeLength(iSerialType);
130370 nRecordCols++;
130372 pCursor->nRecordCols = nRecordCols;
130374 /* Parsing the header used as many bytes as expected. */
130375 if( nRecordHeaderRead!=nRecordHeaderBytes ){
130376 return ValidateError();
130379 /* Calculated record is size of expected record. */
130380 if( nRecordHeaderBytes+nRecordColBytes!=nRecordBytes ){
130381 return ValidateError();
130384 return SQLITE_OK;
130387 static i64 leafCursorCellRowid(RecoverLeafCursor *pCursor){
130388 return pCursor->iRowid;
130391 static unsigned leafCursorCellColumns(RecoverLeafCursor *pCursor){
130392 return pCursor->nRecordCols;
130395 /* Get the column info for the cell. Pass NULL for ppBase to prevent
130396 * retrieving the data segment. If *pbFree is true, *ppBase must be
130397 * freed by the caller using sqlite3_free().
130399 static int leafCursorCellColInfo(RecoverLeafCursor *pCursor,
130400 unsigned iCol, u64 *piColType,
130401 unsigned char **ppBase, int *pbFree){
130402 const unsigned char *pRecordHeader; /* Current cell's header. */
130403 u64 nRecordHeaderBytes; /* Bytes in pRecordHeader. */
130404 unsigned nRead; /* Bytes read from header. */
130405 u64 iColEndOffset; /* Offset to end of column in cell. */
130406 unsigned nColsSkipped; /* Count columns as procesed. */
130407 u64 iSerialType; /* Type descriptor for current column. */
130409 /* Implicit NULL for columns past the end. This case happens when
130410 * rows have not been updated since an ALTER TABLE added columns.
130411 * It is more convenient to address here than in callers.
130413 if( iCol>=pCursor->nRecordCols ){
130414 *piColType = 0;
130415 if( ppBase ){
130416 *ppBase = 0;
130417 *pbFree = 0;
130419 return SQLITE_OK;
130422 /* Must be able to decode header size. */
130423 pRecordHeader = pCursor->pRecordHeader;
130424 if( !checkVarint(pRecordHeader, pCursor->nRecordHeaderBytes) ){
130425 return SQLITE_CORRUPT;
130428 /* Rather than caching the header size and how many bytes it took,
130429 * decode it every time.
130431 nRead = getVarint(pRecordHeader, &nRecordHeaderBytes);
130432 assert( nRecordHeaderBytes==pCursor->nRecordHeaderBytes );
130434 /* Scan forward to the indicated column. Scans to _after_ column
130435 * for later range checking.
130437 /* TODO(shess): This could get expensive for very wide tables. An
130438 * array of iSerialType could be built in leafCursorCellDecode(), but
130439 * the number of columns is dynamic per row, so it would add memory
130440 * management complexity. Enough info to efficiently forward
130441 * iterate could be kept, if all clients forward iterate
130442 * (recoverColumn() may not).
130444 iColEndOffset = 0;
130445 nColsSkipped = 0;
130446 while( nColsSkipped<=iCol && nRead<nRecordHeaderBytes ){
130447 if( !checkVarint(pRecordHeader + nRead, nRecordHeaderBytes - nRead) ){
130448 return SQLITE_CORRUPT;
130450 nRead += getVarint(pRecordHeader + nRead, &iSerialType);
130451 iColEndOffset += SerialTypeLength(iSerialType);
130452 nColsSkipped++;
130455 /* Column's data extends past record's end. */
130456 if( nRecordHeaderBytes+iColEndOffset>pCursor->nRecordBytes ){
130457 return SQLITE_CORRUPT;
130460 *piColType = iSerialType;
130461 if( ppBase ){
130462 const u32 nColBytes = SerialTypeLength(iSerialType);
130464 /* Offset from start of record to beginning of column. */
130465 const unsigned iColOffset = nRecordHeaderBytes+iColEndOffset-nColBytes;
130467 return overflowGetSegment(pCursor->pPage, pCursor->iRecordOffset,
130468 pCursor->nLocalRecordBytes, pCursor->pOverflow,
130469 iColOffset, nColBytes, ppBase, pbFree);
130471 return SQLITE_OK;
130474 static int leafCursorNextValidCell(RecoverLeafCursor *pCursor){
130475 while( 1 ){
130476 int rc;
130478 /* Move to the next cell. */
130479 pCursor->iCell++;
130481 /* No more cells, get the next leaf. */
130482 if( pCursor->iCell>=pCursor->nCells ){
130483 rc = leafCursorNextPage(pCursor);
130484 if( rc!=SQLITE_ROW ){
130485 return rc;
130487 assert( pCursor->iCell==0 );
130490 /* If the cell is valid, indicate that a row is available. */
130491 rc = leafCursorCellDecode(pCursor);
130492 if( rc==SQLITE_OK ){
130493 return SQLITE_ROW;
130496 /* Iterate until done or a valid row is found. */
130497 /* TODO(shess): Remove debugging output. */
130498 fprintf(stderr, "Skipping invalid cell\n");
130500 return SQLITE_ERROR;
130503 typedef struct Recover Recover;
130504 struct Recover {
130505 sqlite3_vtab base;
130506 sqlite3 *db; /* Host database connection */
130507 char *zDb; /* Database containing target table */
130508 char *zTable; /* Target table */
130509 unsigned nCols; /* Number of columns in target table */
130510 unsigned char *pTypes; /* Types of columns in target table */
130513 /* Internal helper for deleting the module. */
130514 static void recoverRelease(Recover *pRecover){
130515 sqlite3_free(pRecover->zDb);
130516 sqlite3_free(pRecover->zTable);
130517 sqlite3_free(pRecover->pTypes);
130518 memset(pRecover, 0xA5, sizeof(*pRecover));
130519 sqlite3_free(pRecover);
130522 /* Helper function for initializing the module. Forward-declared so
130523 * recoverCreate() and recoverConnect() can see it.
130525 static int recoverInit(
130526 sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **
130529 static int recoverCreate(
130530 sqlite3 *db,
130531 void *pAux,
130532 int argc, const char *const*argv,
130533 sqlite3_vtab **ppVtab,
130534 char **pzErr
130536 FNENTRY();
130537 return recoverInit(db, pAux, argc, argv, ppVtab, pzErr);
130540 /* This should never be called. */
130541 static int recoverConnect(
130542 sqlite3 *db,
130543 void *pAux,
130544 int argc, const char *const*argv,
130545 sqlite3_vtab **ppVtab,
130546 char **pzErr
130548 FNENTRY();
130549 return recoverInit(db, pAux, argc, argv, ppVtab, pzErr);
130552 /* No indices supported. */
130553 static int recoverBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
130554 FNENTRY();
130555 return SQLITE_OK;
130558 /* Logically, this should never be called. */
130559 static int recoverDisconnect(sqlite3_vtab *pVtab){
130560 FNENTRY();
130561 recoverRelease((Recover*)pVtab);
130562 return SQLITE_OK;
130565 static int recoverDestroy(sqlite3_vtab *pVtab){
130566 FNENTRY();
130567 recoverRelease((Recover*)pVtab);
130568 return SQLITE_OK;
130571 typedef struct RecoverCursor RecoverCursor;
130572 struct RecoverCursor {
130573 sqlite3_vtab_cursor base;
130574 RecoverLeafCursor *pLeafCursor;
130575 int iEncoding;
130576 int bEOF;
130579 static int recoverOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
130580 Recover *pRecover = (Recover*)pVTab;
130581 u32 iRootPage; /* Root page of the backing table. */
130582 int iEncoding; /* UTF encoding for backing database. */
130583 unsigned nPageSize; /* Size of pages in backing database. */
130584 Pager *pPager; /* Backing database pager. */
130585 RecoverLeafCursor *pLeafCursor; /* Cursor to read table's leaf pages. */
130586 RecoverCursor *pCursor; /* Cursor to read rows from leaves. */
130587 int rc;
130589 FNENTRY();
130591 iRootPage = 0;
130592 rc = getRootPage(pRecover->db, pRecover->zDb, pRecover->zTable,
130593 &iRootPage);
130594 if( rc!=SQLITE_OK ){
130595 return rc;
130598 iEncoding = 0;
130599 rc = getEncoding(pRecover->db, pRecover->zDb, &iEncoding);
130600 if( rc!=SQLITE_OK ){
130601 return rc;
130604 rc = GetPager(pRecover->db, pRecover->zDb, &pPager, &nPageSize);
130605 if( rc!=SQLITE_OK ){
130606 return rc;
130609 rc = leafCursorCreate(pPager, nPageSize, iRootPage, &pLeafCursor);
130610 if( rc!=SQLITE_OK ){
130611 return rc;
130614 pCursor = sqlite3_malloc(sizeof(RecoverCursor));
130615 if( !pCursor ){
130616 leafCursorDestroy(pLeafCursor);
130617 return SQLITE_NOMEM;
130619 memset(pCursor, 0, sizeof(*pCursor));
130620 pCursor->base.pVtab = pVTab;
130621 pCursor->pLeafCursor = pLeafCursor;
130622 pCursor->iEncoding = iEncoding;
130624 /* If no leaf pages were found, empty result set. */
130625 /* TODO(shess): leafCursorNextValidCell() would return SQLITE_ROW or
130626 * SQLITE_DONE to indicate whether there is further data to consider.
130628 pCursor->bEOF = (pLeafCursor->pPage==NULL);
130630 *ppCursor = (sqlite3_vtab_cursor*)pCursor;
130631 return SQLITE_OK;
130634 static int recoverClose(sqlite3_vtab_cursor *cur){
130635 RecoverCursor *pCursor = (RecoverCursor*)cur;
130636 FNENTRY();
130637 if( pCursor->pLeafCursor ){
130638 leafCursorDestroy(pCursor->pLeafCursor);
130639 pCursor->pLeafCursor = NULL;
130641 memset(pCursor, 0xA5, sizeof(*pCursor));
130642 sqlite3_free(cur);
130643 return SQLITE_OK;
130646 /* Helpful place to set a breakpoint. */
130647 static int RecoverInvalidCell(){
130648 return SQLITE_ERROR;
130651 /* Returns SQLITE_OK if the cell has an appropriate number of columns
130652 * with the appropriate types of data.
130654 static int recoverValidateLeafCell(Recover *pRecover, RecoverCursor *pCursor){
130655 unsigned i;
130657 /* If the row's storage has too many columns, skip it. */
130658 if( leafCursorCellColumns(pCursor->pLeafCursor)>pRecover->nCols ){
130659 return RecoverInvalidCell();
130662 /* Skip rows with unexpected types. */
130663 for( i=0; i<pRecover->nCols; ++i ){
130664 u64 iType; /* Storage type of column i. */
130665 int rc;
130667 /* ROWID alias. */
130668 if( (pRecover->pTypes[i]&MASK_ROWID) ){
130669 continue;
130672 rc = leafCursorCellColInfo(pCursor->pLeafCursor, i, &iType, NULL, NULL);
130673 assert( rc==SQLITE_OK );
130674 if( rc!=SQLITE_OK || !SerialTypeIsCompatible(iType, pRecover->pTypes[i]) ){
130675 return RecoverInvalidCell();
130679 return SQLITE_OK;
130682 static int recoverNext(sqlite3_vtab_cursor *pVtabCursor){
130683 RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
130684 Recover *pRecover = (Recover*)pCursor->base.pVtab;
130685 int rc;
130687 FNENTRY();
130689 /* Scan forward to the next cell with valid storage, then check that
130690 * the stored data matches the schema.
130692 while( (rc = leafCursorNextValidCell(pCursor->pLeafCursor))==SQLITE_ROW ){
130693 if( recoverValidateLeafCell(pRecover, pCursor)==SQLITE_OK ){
130694 return SQLITE_OK;
130698 if( rc==SQLITE_DONE ){
130699 pCursor->bEOF = 1;
130700 return SQLITE_OK;
130703 assert( rc!=SQLITE_OK );
130704 return rc;
130707 static int recoverFilter(
130708 sqlite3_vtab_cursor *pVtabCursor,
130709 int idxNum, const char *idxStr,
130710 int argc, sqlite3_value **argv
130712 RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
130713 Recover *pRecover = (Recover*)pCursor->base.pVtab;
130714 int rc;
130716 FNENTRY();
130718 /* There were no valid leaf pages in the table. */
130719 if( pCursor->bEOF ){
130720 return SQLITE_OK;
130723 /* Load the first cell, and iterate forward if it's not valid. If no cells at
130724 * all are valid, recoverNext() sets bEOF and returns appropriately.
130726 rc = leafCursorCellDecode(pCursor->pLeafCursor);
130727 if( rc!=SQLITE_OK || recoverValidateLeafCell(pRecover, pCursor)!=SQLITE_OK ){
130728 return recoverNext(pVtabCursor);
130731 return SQLITE_OK;
130734 static int recoverEof(sqlite3_vtab_cursor *pVtabCursor){
130735 RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
130736 FNENTRY();
130737 return pCursor->bEOF;
130740 static int recoverColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
130741 RecoverCursor *pCursor = (RecoverCursor*)cur;
130742 Recover *pRecover = (Recover*)pCursor->base.pVtab;
130743 u64 iColType; /* Storage type of column i. */
130744 unsigned char *pColData; /* Column i's data. */
130745 int shouldFree; /* Non-zero if pColData should be freed. */
130746 int rc;
130748 FNENTRY();
130750 if( (unsigned)i>=pRecover->nCols ){
130751 return SQLITE_ERROR;
130754 /* ROWID alias. */
130755 if( (pRecover->pTypes[i]&MASK_ROWID) ){
130756 sqlite3_result_int64(ctx, leafCursorCellRowid(pCursor->pLeafCursor));
130757 return SQLITE_OK;
130760 pColData = NULL;
130761 shouldFree = 0;
130762 rc = leafCursorCellColInfo(pCursor->pLeafCursor, i, &iColType,
130763 &pColData, &shouldFree);
130764 if( rc!=SQLITE_OK ){
130765 return rc;
130767 /* recoverValidateLeafCell() should guarantee that this will never
130768 * occur.
130770 if( !SerialTypeIsCompatible(iColType, pRecover->pTypes[i]) ){
130771 if( shouldFree ){
130772 sqlite3_free(pColData);
130774 return SQLITE_ERROR;
130777 switch( iColType ){
130778 case 0 : sqlite3_result_null(ctx); break;
130779 case 1 : sqlite3_result_int64(ctx, decodeSigned(pColData, 1)); break;
130780 case 2 : sqlite3_result_int64(ctx, decodeSigned(pColData, 2)); break;
130781 case 3 : sqlite3_result_int64(ctx, decodeSigned(pColData, 3)); break;
130782 case 4 : sqlite3_result_int64(ctx, decodeSigned(pColData, 4)); break;
130783 case 5 : sqlite3_result_int64(ctx, decodeSigned(pColData, 6)); break;
130784 case 6 : sqlite3_result_int64(ctx, decodeSigned(pColData, 8)); break;
130785 case 7 : sqlite3_result_double(ctx, decodeFloat64(pColData)); break;
130786 case 8 : sqlite3_result_int(ctx, 0); break;
130787 case 9 : sqlite3_result_int(ctx, 1); break;
130788 case 10 : assert( iColType!=10 ); break;
130789 case 11 : assert( iColType!=11 ); break;
130791 default : {
130792 u32 l = SerialTypeLength(iColType);
130794 /* If pColData was already allocated, arrange to pass ownership. */
130795 sqlite3_destructor_type pFn = SQLITE_TRANSIENT;
130796 if( shouldFree ){
130797 pFn = sqlite3_free;
130798 shouldFree = 0;
130801 if( SerialTypeIsBlob(iColType) ){
130802 sqlite3_result_blob(ctx, pColData, l, pFn);
130803 }else{
130804 if( pCursor->iEncoding==SQLITE_UTF16LE ){
130805 sqlite3_result_text16le(ctx, (const void*)pColData, l, pFn);
130806 }else if( pCursor->iEncoding==SQLITE_UTF16BE ){
130807 sqlite3_result_text16be(ctx, (const void*)pColData, l, pFn);
130808 }else{
130809 sqlite3_result_text(ctx, (const char*)pColData, l, pFn);
130812 } break;
130814 if( shouldFree ){
130815 sqlite3_free(pColData);
130817 return SQLITE_OK;
130820 static int recoverRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
130821 RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
130822 FNENTRY();
130823 *pRowid = leafCursorCellRowid(pCursor->pLeafCursor);
130824 return SQLITE_OK;
130827 static sqlite3_module recoverModule = {
130828 0, /* iVersion */
130829 recoverCreate, /* xCreate - create a table */
130830 recoverConnect, /* xConnect - connect to an existing table */
130831 recoverBestIndex, /* xBestIndex - Determine search strategy */
130832 recoverDisconnect, /* xDisconnect - Disconnect from a table */
130833 recoverDestroy, /* xDestroy - Drop a table */
130834 recoverOpen, /* xOpen - open a cursor */
130835 recoverClose, /* xClose - close a cursor */
130836 recoverFilter, /* xFilter - configure scan constraints */
130837 recoverNext, /* xNext - advance a cursor */
130838 recoverEof, /* xEof */
130839 recoverColumn, /* xColumn - read data */
130840 recoverRowid, /* xRowid - read data */
130841 0, /* xUpdate - write data */
130842 0, /* xBegin - begin transaction */
130843 0, /* xSync - sync transaction */
130844 0, /* xCommit - commit transaction */
130845 0, /* xRollback - rollback transaction */
130846 0, /* xFindFunction - function overloading */
130847 0, /* xRename - rename the table */
130850 CHROMIUM_SQLITE_API
130851 int recoverVtableInit(sqlite3 *db){
130852 return sqlite3_create_module_v2(db, "recover", &recoverModule, NULL, 0);
130855 /* This section of code is for parsing the create input and
130856 * initializing the module.
130859 /* Find the next word in zText and place the endpoints in pzWord*.
130860 * Returns true if the word is non-empty. "Word" is defined as
130861 * ASCII alphanumeric plus '_' at this time.
130863 static int findWord(const char *zText,
130864 const char **pzWordStart, const char **pzWordEnd){
130865 int r;
130866 while( ascii_isspace(*zText) ){
130867 zText++;
130869 *pzWordStart = zText;
130870 while( ascii_isalnum(*zText) || *zText=='_' ){
130871 zText++;
130873 r = zText>*pzWordStart; /* In case pzWordStart==pzWordEnd */
130874 *pzWordEnd = zText;
130875 return r;
130878 /* Return true if the next word in zText is zWord, also setting
130879 * *pzContinue to the character after the word.
130881 static int expectWord(const char *zText, const char *zWord,
130882 const char **pzContinue){
130883 const char *zWordStart, *zWordEnd;
130884 if( findWord(zText, &zWordStart, &zWordEnd) &&
130885 ascii_strncasecmp(zWord, zWordStart, zWordEnd - zWordStart)==0 ){
130886 *pzContinue = zWordEnd;
130887 return 1;
130889 return 0;
130892 /* Parse the name and type information out of parameter. In case of
130893 * success, *pzNameStart/End contain the name of the column,
130894 * *pzTypeStart/End contain the top-level type, and *pTypeMask has the
130895 * type mask to use for the column.
130897 static int findNameAndType(const char *parameter,
130898 const char **pzNameStart, const char **pzNameEnd,
130899 const char **pzTypeStart, const char **pzTypeEnd,
130900 unsigned char *pTypeMask){
130901 unsigned nNameLen; /* Length of found name. */
130902 const char *zEnd; /* Current end of parsed column information. */
130903 int bNotNull; /* Non-zero if NULL is not allowed for name. */
130904 int bStrict; /* Non-zero if column requires exact type match. */
130905 const char *zDummy; /* Dummy parameter, result unused. */
130906 unsigned i;
130908 /* strictMask is used for STRICT, strictMask|otherMask if STRICT is
130909 * not supplied. zReplace provides an alternate type to expose to
130910 * the caller.
130912 static struct {
130913 const char *zName;
130914 unsigned char strictMask;
130915 unsigned char otherMask;
130916 const char *zReplace;
130917 } kTypeInfo[] = {
130918 { "ANY",
130919 MASK_INTEGER | MASK_FLOAT | MASK_BLOB | MASK_TEXT | MASK_NULL,
130920 0, "",
130922 { "ROWID", MASK_INTEGER | MASK_ROWID, 0, "INTEGER", },
130923 { "INTEGER", MASK_INTEGER | MASK_NULL, 0, NULL, },
130924 { "FLOAT", MASK_FLOAT | MASK_NULL, MASK_INTEGER, NULL, },
130925 { "NUMERIC", MASK_INTEGER | MASK_FLOAT | MASK_NULL, MASK_TEXT, NULL, },
130926 { "TEXT", MASK_TEXT | MASK_NULL, MASK_BLOB, NULL, },
130927 { "BLOB", MASK_BLOB | MASK_NULL, 0, NULL, },
130930 if( !findWord(parameter, pzNameStart, pzNameEnd) ){
130931 return SQLITE_MISUSE;
130934 /* Manifest typing, accept any storage type. */
130935 if( !findWord(*pzNameEnd, pzTypeStart, pzTypeEnd) ){
130936 *pzTypeEnd = *pzTypeStart = "";
130937 *pTypeMask = MASK_INTEGER | MASK_FLOAT | MASK_BLOB | MASK_TEXT | MASK_NULL;
130938 return SQLITE_OK;
130941 nNameLen = *pzTypeEnd - *pzTypeStart;
130942 for( i=0; i<ArraySize(kTypeInfo); ++i ){
130943 if( ascii_strncasecmp(kTypeInfo[i].zName, *pzTypeStart, nNameLen)==0 ){
130944 break;
130947 if( i==ArraySize(kTypeInfo) ){
130948 return SQLITE_MISUSE;
130951 zEnd = *pzTypeEnd;
130952 bStrict = 0;
130953 if( expectWord(zEnd, "STRICT", &zEnd) ){
130954 /* TODO(shess): Ick. But I don't want another single-purpose
130955 * flag, either.
130957 if( kTypeInfo[i].zReplace && !kTypeInfo[i].zReplace[0] ){
130958 return SQLITE_MISUSE;
130960 bStrict = 1;
130963 bNotNull = 0;
130964 if( expectWord(zEnd, "NOT", &zEnd) ){
130965 if( expectWord(zEnd, "NULL", &zEnd) ){
130966 bNotNull = 1;
130967 }else{
130968 /* Anything other than NULL after NOT is an error. */
130969 return SQLITE_MISUSE;
130973 /* Anything else is an error. */
130974 if( findWord(zEnd, &zDummy, &zDummy) ){
130975 return SQLITE_MISUSE;
130978 *pTypeMask = kTypeInfo[i].strictMask;
130979 if( !bStrict ){
130980 *pTypeMask |= kTypeInfo[i].otherMask;
130982 if( bNotNull ){
130983 *pTypeMask &= ~MASK_NULL;
130985 if( kTypeInfo[i].zReplace ){
130986 *pzTypeStart = kTypeInfo[i].zReplace;
130987 *pzTypeEnd = *pzTypeStart + strlen(*pzTypeStart);
130989 return SQLITE_OK;
130992 /* Parse the arguments, placing type masks in *pTypes and the exposed
130993 * schema in *pzCreateSql (for sqlite3_declare_vtab).
130995 static int ParseColumnsAndGenerateCreate(unsigned nCols,
130996 const char *const *pCols,
130997 char **pzCreateSql,
130998 unsigned char *pTypes,
130999 char **pzErr){
131000 unsigned i;
131001 char *zCreateSql = sqlite3_mprintf("CREATE TABLE x(");
131002 if( !zCreateSql ){
131003 return SQLITE_NOMEM;
131006 for( i=0; i<nCols; i++ ){
131007 const char *zSep = (i < nCols - 1 ? ", " : ")");
131008 const char *zNotNull = "";
131009 const char *zNameStart, *zNameEnd;
131010 const char *zTypeStart, *zTypeEnd;
131011 int rc = findNameAndType(pCols[i],
131012 &zNameStart, &zNameEnd,
131013 &zTypeStart, &zTypeEnd,
131014 &pTypes[i]);
131015 if( rc!=SQLITE_OK ){
131016 *pzErr = sqlite3_mprintf("unable to parse column %d", i);
131017 sqlite3_free(zCreateSql);
131018 return rc;
131021 if( !(pTypes[i]&MASK_NULL) ){
131022 zNotNull = " NOT NULL";
131025 /* Add name and type to the create statement. */
131026 zCreateSql = sqlite3_mprintf("%z%.*s %.*s%s%s",
131027 zCreateSql,
131028 zNameEnd - zNameStart, zNameStart,
131029 zTypeEnd - zTypeStart, zTypeStart,
131030 zNotNull, zSep);
131031 if( !zCreateSql ){
131032 return SQLITE_NOMEM;
131036 *pzCreateSql = zCreateSql;
131037 return SQLITE_OK;
131040 /* Helper function for initializing the module. */
131041 /* argv[0] module name
131042 * argv[1] db name for virtual table
131043 * argv[2] virtual table name
131044 * argv[3] backing table name
131045 * argv[4] columns
131047 /* TODO(shess): Since connect isn't supported, could inline into
131048 * recoverCreate().
131050 /* TODO(shess): Explore cases where it would make sense to set *pzErr. */
131051 static int recoverInit(
131052 sqlite3 *db, /* Database connection */
131053 void *pAux, /* unused */
131054 int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
131055 sqlite3_vtab **ppVtab, /* OUT: New virtual table */
131056 char **pzErr /* OUT: Error message, if any */
131058 const int kTypeCol = 4; /* First argument with column type info. */
131059 Recover *pRecover; /* Virtual table structure being created. */
131060 char *zDot; /* Any dot found in "db.table" backing. */
131061 u32 iRootPage; /* Root page of backing table. */
131062 char *zCreateSql; /* Schema of created virtual table. */
131063 int rc;
131065 /* Require to be in the temp database. */
131066 if( ascii_strcasecmp(argv[1], "temp")!=0 ){
131067 *pzErr = sqlite3_mprintf("recover table must be in temp database");
131068 return SQLITE_MISUSE;
131071 /* Need the backing table and at least one column. */
131072 if( argc<=kTypeCol ){
131073 *pzErr = sqlite3_mprintf("no columns specified");
131074 return SQLITE_MISUSE;
131077 pRecover = sqlite3_malloc(sizeof(Recover));
131078 if( !pRecover ){
131079 return SQLITE_NOMEM;
131081 memset(pRecover, 0, sizeof(*pRecover));
131082 pRecover->base.pModule = &recoverModule;
131083 pRecover->db = db;
131085 /* Parse out db.table, assuming main if no dot. */
131086 zDot = strchr(argv[3], '.');
131087 if( !zDot ){
131088 pRecover->zDb = sqlite3_strdup(db->aDb[0].zName);
131089 pRecover->zTable = sqlite3_strdup(argv[3]);
131090 }else if( zDot>argv[3] && zDot[1]!='\0' ){
131091 pRecover->zDb = sqlite3_strndup(argv[3], zDot - argv[3]);
131092 pRecover->zTable = sqlite3_strdup(zDot + 1);
131093 }else{
131094 /* ".table" or "db." not allowed. */
131095 *pzErr = sqlite3_mprintf("ill-formed table specifier");
131096 recoverRelease(pRecover);
131097 return SQLITE_ERROR;
131100 pRecover->nCols = argc - kTypeCol;
131101 pRecover->pTypes = sqlite3_malloc(pRecover->nCols);
131102 if( !pRecover->zDb || !pRecover->zTable || !pRecover->pTypes ){
131103 recoverRelease(pRecover);
131104 return SQLITE_NOMEM;
131107 /* Require the backing table to exist. */
131108 /* TODO(shess): Be more pedantic about the form of the descriptor
131109 * string. This already fails for poorly-formed strings, simply
131110 * because there won't be a root page, but it would make more sense
131111 * to be explicit.
131113 rc = getRootPage(pRecover->db, pRecover->zDb, pRecover->zTable, &iRootPage);
131114 if( rc!=SQLITE_OK ){
131115 *pzErr = sqlite3_mprintf("unable to find backing table");
131116 recoverRelease(pRecover);
131117 return rc;
131120 /* Parse the column definitions. */
131121 rc = ParseColumnsAndGenerateCreate(pRecover->nCols, argv + kTypeCol,
131122 &zCreateSql, pRecover->pTypes, pzErr);
131123 if( rc!=SQLITE_OK ){
131124 recoverRelease(pRecover);
131125 return rc;
131128 rc = sqlite3_declare_vtab(db, zCreateSql);
131129 sqlite3_free(zCreateSql);
131130 if( rc!=SQLITE_OK ){
131131 recoverRelease(pRecover);
131132 return rc;
131135 *ppVtab = (sqlite3_vtab *)pRecover;
131136 return SQLITE_OK;
131139 /************** End of recover.c *********************************************/
131140 /************** Begin file fts3.c ********************************************/
131142 ** 2006 Oct 10
131144 ** The author disclaims copyright to this source code. In place of
131145 ** a legal notice, here is a blessing:
131147 ** May you do good and not evil.
131148 ** May you find forgiveness for yourself and forgive others.
131149 ** May you share freely, never taking more than you give.
131151 ******************************************************************************
131153 ** This is an SQLite module implementing full-text search.
131157 ** The code in this file is only compiled if:
131159 ** * The FTS3 module is being built as an extension
131160 ** (in which case SQLITE_CORE is not defined), or
131162 ** * The FTS3 module is being built into the core of
131163 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
131166 /* The full-text index is stored in a series of b+tree (-like)
131167 ** structures called segments which map terms to doclists. The
131168 ** structures are like b+trees in layout, but are constructed from the
131169 ** bottom up in optimal fashion and are not updatable. Since trees
131170 ** are built from the bottom up, things will be described from the
131171 ** bottom up.
131174 **** Varints ****
131175 ** The basic unit of encoding is a variable-length integer called a
131176 ** varint. We encode variable-length integers in little-endian order
131177 ** using seven bits * per byte as follows:
131179 ** KEY:
131180 ** A = 0xxxxxxx 7 bits of data and one flag bit
131181 ** B = 1xxxxxxx 7 bits of data and one flag bit
131183 ** 7 bits - A
131184 ** 14 bits - BA
131185 ** 21 bits - BBA
131186 ** and so on.
131188 ** This is similar in concept to how sqlite encodes "varints" but
131189 ** the encoding is not the same. SQLite varints are big-endian
131190 ** are are limited to 9 bytes in length whereas FTS3 varints are
131191 ** little-endian and can be up to 10 bytes in length (in theory).
131193 ** Example encodings:
131195 ** 1: 0x01
131196 ** 127: 0x7f
131197 ** 128: 0x81 0x00
131200 **** Document lists ****
131201 ** A doclist (document list) holds a docid-sorted list of hits for a
131202 ** given term. Doclists hold docids and associated token positions.
131203 ** A docid is the unique integer identifier for a single document.
131204 ** A position is the index of a word within the document. The first
131205 ** word of the document has a position of 0.
131207 ** FTS3 used to optionally store character offsets using a compile-time
131208 ** option. But that functionality is no longer supported.
131210 ** A doclist is stored like this:
131212 ** array {
131213 ** varint docid; (delta from previous doclist)
131214 ** array { (position list for column 0)
131215 ** varint position; (2 more than the delta from previous position)
131217 ** array {
131218 ** varint POS_COLUMN; (marks start of position list for new column)
131219 ** varint column; (index of new column)
131220 ** array {
131221 ** varint position; (2 more than the delta from previous position)
131224 ** varint POS_END; (marks end of positions for this document.
131227 ** Here, array { X } means zero or more occurrences of X, adjacent in
131228 ** memory. A "position" is an index of a token in the token stream
131229 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
131230 ** in the same logical place as the position element, and act as sentinals
131231 ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
131232 ** The positions numbers are not stored literally but rather as two more
131233 ** than the difference from the prior position, or the just the position plus
131234 ** 2 for the first position. Example:
131236 ** label: A B C D E F G H I J K
131237 ** value: 123 5 9 1 1 14 35 0 234 72 0
131239 ** The 123 value is the first docid. For column zero in this document
131240 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
131241 ** at D signals the start of a new column; the 1 at E indicates that the
131242 ** new column is column number 1. There are two positions at 12 and 45
131243 ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
131244 ** 234 at I is the delta to next docid (357). It has one position 70
131245 ** (72-2) and then terminates with the 0 at K.
131247 ** A "position-list" is the list of positions for multiple columns for
131248 ** a single docid. A "column-list" is the set of positions for a single
131249 ** column. Hence, a position-list consists of one or more column-lists,
131250 ** a document record consists of a docid followed by a position-list and
131251 ** a doclist consists of one or more document records.
131253 ** A bare doclist omits the position information, becoming an
131254 ** array of varint-encoded docids.
131256 **** Segment leaf nodes ****
131257 ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
131258 ** nodes are written using LeafWriter, and read using LeafReader (to
131259 ** iterate through a single leaf node's data) and LeavesReader (to
131260 ** iterate through a segment's entire leaf layer). Leaf nodes have
131261 ** the format:
131263 ** varint iHeight; (height from leaf level, always 0)
131264 ** varint nTerm; (length of first term)
131265 ** char pTerm[nTerm]; (content of first term)
131266 ** varint nDoclist; (length of term's associated doclist)
131267 ** char pDoclist[nDoclist]; (content of doclist)
131268 ** array {
131269 ** (further terms are delta-encoded)
131270 ** varint nPrefix; (length of prefix shared with previous term)
131271 ** varint nSuffix; (length of unshared suffix)
131272 ** char pTermSuffix[nSuffix];(unshared suffix of next term)
131273 ** varint nDoclist; (length of term's associated doclist)
131274 ** char pDoclist[nDoclist]; (content of doclist)
131277 ** Here, array { X } means zero or more occurrences of X, adjacent in
131278 ** memory.
131280 ** Leaf nodes are broken into blocks which are stored contiguously in
131281 ** the %_segments table in sorted order. This means that when the end
131282 ** of a node is reached, the next term is in the node with the next
131283 ** greater node id.
131285 ** New data is spilled to a new leaf node when the current node
131286 ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
131287 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
131288 ** node (a leaf node with a single term and doclist). The goal of
131289 ** these settings is to pack together groups of small doclists while
131290 ** making it efficient to directly access large doclists. The
131291 ** assumption is that large doclists represent terms which are more
131292 ** likely to be query targets.
131294 ** TODO(shess) It may be useful for blocking decisions to be more
131295 ** dynamic. For instance, it may make more sense to have a 2.5k leaf
131296 ** node rather than splitting into 2k and .5k nodes. My intuition is
131297 ** that this might extend through 2x or 4x the pagesize.
131300 **** Segment interior nodes ****
131301 ** Segment interior nodes store blockids for subtree nodes and terms
131302 ** to describe what data is stored by the each subtree. Interior
131303 ** nodes are written using InteriorWriter, and read using
131304 ** InteriorReader. InteriorWriters are created as needed when
131305 ** SegmentWriter creates new leaf nodes, or when an interior node
131306 ** itself grows too big and must be split. The format of interior
131307 ** nodes:
131309 ** varint iHeight; (height from leaf level, always >0)
131310 ** varint iBlockid; (block id of node's leftmost subtree)
131311 ** optional {
131312 ** varint nTerm; (length of first term)
131313 ** char pTerm[nTerm]; (content of first term)
131314 ** array {
131315 ** (further terms are delta-encoded)
131316 ** varint nPrefix; (length of shared prefix with previous term)
131317 ** varint nSuffix; (length of unshared suffix)
131318 ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
131322 ** Here, optional { X } means an optional element, while array { X }
131323 ** means zero or more occurrences of X, adjacent in memory.
131325 ** An interior node encodes n terms separating n+1 subtrees. The
131326 ** subtree blocks are contiguous, so only the first subtree's blockid
131327 ** is encoded. The subtree at iBlockid will contain all terms less
131328 ** than the first term encoded (or all terms if no term is encoded).
131329 ** Otherwise, for terms greater than or equal to pTerm[i] but less
131330 ** than pTerm[i+1], the subtree for that term will be rooted at
131331 ** iBlockid+i. Interior nodes only store enough term data to
131332 ** distinguish adjacent children (if the rightmost term of the left
131333 ** child is "something", and the leftmost term of the right child is
131334 ** "wicked", only "w" is stored).
131336 ** New data is spilled to a new interior node at the same height when
131337 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
131338 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
131339 ** interior nodes and making the tree too skinny. The interior nodes
131340 ** at a given height are naturally tracked by interior nodes at
131341 ** height+1, and so on.
131344 **** Segment directory ****
131345 ** The segment directory in table %_segdir stores meta-information for
131346 ** merging and deleting segments, and also the root node of the
131347 ** segment's tree.
131349 ** The root node is the top node of the segment's tree after encoding
131350 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
131351 ** This could be either a leaf node or an interior node. If the top
131352 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
131353 ** and a new root interior node is generated (which should always fit
131354 ** within ROOT_MAX because it only needs space for 2 varints, the
131355 ** height and the blockid of the previous root).
131357 ** The meta-information in the segment directory is:
131358 ** level - segment level (see below)
131359 ** idx - index within level
131360 ** - (level,idx uniquely identify a segment)
131361 ** start_block - first leaf node
131362 ** leaves_end_block - last leaf node
131363 ** end_block - last block (including interior nodes)
131364 ** root - contents of root node
131366 ** If the root node is a leaf node, then start_block,
131367 ** leaves_end_block, and end_block are all 0.
131370 **** Segment merging ****
131371 ** To amortize update costs, segments are grouped into levels and
131372 ** merged in batches. Each increase in level represents exponentially
131373 ** more documents.
131375 ** New documents (actually, document updates) are tokenized and
131376 ** written individually (using LeafWriter) to a level 0 segment, with
131377 ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
131378 ** level 0 segments are merged into a single level 1 segment. Level 1
131379 ** is populated like level 0, and eventually MERGE_COUNT level 1
131380 ** segments are merged to a single level 2 segment (representing
131381 ** MERGE_COUNT^2 updates), and so on.
131383 ** A segment merge traverses all segments at a given level in
131384 ** parallel, performing a straightforward sorted merge. Since segment
131385 ** leaf nodes are written in to the %_segments table in order, this
131386 ** merge traverses the underlying sqlite disk structures efficiently.
131387 ** After the merge, all segment blocks from the merged level are
131388 ** deleted.
131390 ** MERGE_COUNT controls how often we merge segments. 16 seems to be
131391 ** somewhat of a sweet spot for insertion performance. 32 and 64 show
131392 ** very similar performance numbers to 16 on insertion, though they're
131393 ** a tiny bit slower (perhaps due to more overhead in merge-time
131394 ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
131395 ** 16, 2 about 66% slower than 16.
131397 ** At query time, high MERGE_COUNT increases the number of segments
131398 ** which need to be scanned and merged. For instance, with 100k docs
131399 ** inserted:
131401 ** MERGE_COUNT segments
131402 ** 16 25
131403 ** 8 12
131404 ** 4 10
131405 ** 2 6
131407 ** This appears to have only a moderate impact on queries for very
131408 ** frequent terms (which are somewhat dominated by segment merge
131409 ** costs), and infrequent and non-existent terms still seem to be fast
131410 ** even with many segments.
131412 ** TODO(shess) That said, it would be nice to have a better query-side
131413 ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
131414 ** optimizations to things like doclist merging will swing the sweet
131415 ** spot around.
131419 **** Handling of deletions and updates ****
131420 ** Since we're using a segmented structure, with no docid-oriented
131421 ** index into the term index, we clearly cannot simply update the term
131422 ** index when a document is deleted or updated. For deletions, we
131423 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
131424 ** we simply write the new doclist. Segment merges overwrite older
131425 ** data for a particular docid with newer data, so deletes or updates
131426 ** will eventually overtake the earlier data and knock it out. The
131427 ** query logic likewise merges doclists so that newer data knocks out
131428 ** older data.
131430 #define CHROMIUM_FTS3_CHANGES 1
131432 /************** Include fts3Int.h in the middle of fts3.c ********************/
131433 /************** Begin file fts3Int.h *****************************************/
131435 ** 2009 Nov 12
131437 ** The author disclaims copyright to this source code. In place of
131438 ** a legal notice, here is a blessing:
131440 ** May you do good and not evil.
131441 ** May you find forgiveness for yourself and forgive others.
131442 ** May you share freely, never taking more than you give.
131444 ******************************************************************************
131447 #ifndef _FTSINT_H
131448 #define _FTSINT_H
131450 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
131451 # define NDEBUG 1
131452 #endif
131455 ** FTS4 is really an extension for FTS3. It is enabled using the
131456 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
131457 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
131459 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
131460 # define SQLITE_ENABLE_FTS3
131461 #endif
131463 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
131465 /* If not building as part of the core, include sqlite3ext.h. */
131466 #ifndef SQLITE_CORE
131467 SQLITE_EXTENSION_INIT3
131468 #endif
131470 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
131471 /************** Begin file fts3_tokenizer.h **********************************/
131473 ** 2006 July 10
131475 ** The author disclaims copyright to this source code.
131477 *************************************************************************
131478 ** Defines the interface to tokenizers used by fulltext-search. There
131479 ** are three basic components:
131481 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
131482 ** interface functions. This is essentially the class structure for
131483 ** tokenizers.
131485 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
131486 ** including customization information defined at creation time.
131488 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
131489 ** tokens from a particular input.
131491 #ifndef _FTS3_TOKENIZER_H_
131492 #define _FTS3_TOKENIZER_H_
131494 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
131495 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
131496 ** we will need a way to register the API consistently.
131500 ** Structures used by the tokenizer interface. When a new tokenizer
131501 ** implementation is registered, the caller provides a pointer to
131502 ** an sqlite3_tokenizer_module containing pointers to the callback
131503 ** functions that make up an implementation.
131505 ** When an fts3 table is created, it passes any arguments passed to
131506 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
131507 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
131508 ** implementation. The xCreate() function in turn returns an
131509 ** sqlite3_tokenizer structure representing the specific tokenizer to
131510 ** be used for the fts3 table (customized by the tokenizer clause arguments).
131512 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
131513 ** method is called. It returns an sqlite3_tokenizer_cursor object
131514 ** that may be used to tokenize a specific input buffer based on
131515 ** the tokenization rules supplied by a specific sqlite3_tokenizer
131516 ** object.
131518 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
131519 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
131520 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
131522 struct sqlite3_tokenizer_module {
131525 ** Structure version. Should always be set to 0 or 1.
131527 int iVersion;
131530 ** Create a new tokenizer. The values in the argv[] array are the
131531 ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
131532 ** TABLE statement that created the fts3 table. For example, if
131533 ** the following SQL is executed:
131535 ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
131537 ** then argc is set to 2, and the argv[] array contains pointers
131538 ** to the strings "arg1" and "arg2".
131540 ** This method should return either SQLITE_OK (0), or an SQLite error
131541 ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
131542 ** to point at the newly created tokenizer structure. The generic
131543 ** sqlite3_tokenizer.pModule variable should not be initialized by
131544 ** this callback. The caller will do so.
131546 int (*xCreate)(
131547 int argc, /* Size of argv array */
131548 const char *const*argv, /* Tokenizer argument strings */
131549 sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
131553 ** Destroy an existing tokenizer. The fts3 module calls this method
131554 ** exactly once for each successful call to xCreate().
131556 int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
131559 ** Create a tokenizer cursor to tokenize an input buffer. The caller
131560 ** is responsible for ensuring that the input buffer remains valid
131561 ** until the cursor is closed (using the xClose() method).
131563 int (*xOpen)(
131564 sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
131565 const char *pInput, int nBytes, /* Input buffer */
131566 sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
131570 ** Destroy an existing tokenizer cursor. The fts3 module calls this
131571 ** method exactly once for each successful call to xOpen().
131573 int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
131576 ** Retrieve the next token from the tokenizer cursor pCursor. This
131577 ** method should either return SQLITE_OK and set the values of the
131578 ** "OUT" variables identified below, or SQLITE_DONE to indicate that
131579 ** the end of the buffer has been reached, or an SQLite error code.
131581 ** *ppToken should be set to point at a buffer containing the
131582 ** normalized version of the token (i.e. after any case-folding and/or
131583 ** stemming has been performed). *pnBytes should be set to the length
131584 ** of this buffer in bytes. The input text that generated the token is
131585 ** identified by the byte offsets returned in *piStartOffset and
131586 ** *piEndOffset. *piStartOffset should be set to the index of the first
131587 ** byte of the token in the input buffer. *piEndOffset should be set
131588 ** to the index of the first byte just past the end of the token in
131589 ** the input buffer.
131591 ** The buffer *ppToken is set to point at is managed by the tokenizer
131592 ** implementation. It is only required to be valid until the next call
131593 ** to xNext() or xClose().
131595 /* TODO(shess) current implementation requires pInput to be
131596 ** nul-terminated. This should either be fixed, or pInput/nBytes
131597 ** should be converted to zInput.
131599 int (*xNext)(
131600 sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
131601 const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
131602 int *piStartOffset, /* OUT: Byte offset of token in input buffer */
131603 int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
131604 int *piPosition /* OUT: Number of tokens returned before this one */
131607 /***********************************************************************
131608 ** Methods below this point are only available if iVersion>=1.
131612 ** Configure the language id of a tokenizer cursor.
131614 int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
131617 struct sqlite3_tokenizer {
131618 const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
131619 /* Tokenizer implementations will typically add additional fields */
131622 struct sqlite3_tokenizer_cursor {
131623 sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
131624 /* Tokenizer implementations will typically add additional fields */
131627 int fts3_global_term_cnt(int iTerm, int iCol);
131628 int fts3_term_cnt(int iTerm, int iCol);
131631 #endif /* _FTS3_TOKENIZER_H_ */
131633 /************** End of fts3_tokenizer.h **************************************/
131634 /************** Continuing where we left off in fts3Int.h ********************/
131635 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
131636 /************** Begin file fts3_hash.h ***************************************/
131638 ** 2001 September 22
131640 ** The author disclaims copyright to this source code. In place of
131641 ** a legal notice, here is a blessing:
131643 ** May you do good and not evil.
131644 ** May you find forgiveness for yourself and forgive others.
131645 ** May you share freely, never taking more than you give.
131647 *************************************************************************
131648 ** This is the header file for the generic hash-table implementation
131649 ** used in SQLite. We've modified it slightly to serve as a standalone
131650 ** hash table implementation for the full-text indexing module.
131653 #ifndef _FTS3_HASH_H_
131654 #define _FTS3_HASH_H_
131656 /* Forward declarations of structures. */
131657 typedef struct Fts3Hash Fts3Hash;
131658 typedef struct Fts3HashElem Fts3HashElem;
131660 /* A complete hash table is an instance of the following structure.
131661 ** The internals of this structure are intended to be opaque -- client
131662 ** code should not attempt to access or modify the fields of this structure
131663 ** directly. Change this structure only by using the routines below.
131664 ** However, many of the "procedures" and "functions" for modifying and
131665 ** accessing this structure are really macros, so we can't really make
131666 ** this structure opaque.
131668 struct Fts3Hash {
131669 char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
131670 char copyKey; /* True if copy of key made on insert */
131671 int count; /* Number of entries in this table */
131672 Fts3HashElem *first; /* The first element of the array */
131673 int htsize; /* Number of buckets in the hash table */
131674 struct _fts3ht { /* the hash table */
131675 int count; /* Number of entries with this hash */
131676 Fts3HashElem *chain; /* Pointer to first entry with this hash */
131677 } *ht;
131680 /* Each element in the hash table is an instance of the following
131681 ** structure. All elements are stored on a single doubly-linked list.
131683 ** Again, this structure is intended to be opaque, but it can't really
131684 ** be opaque because it is used by macros.
131686 struct Fts3HashElem {
131687 Fts3HashElem *next, *prev; /* Next and previous elements in the table */
131688 void *data; /* Data associated with this element */
131689 void *pKey; int nKey; /* Key associated with this element */
131693 ** There are 2 different modes of operation for a hash table:
131695 ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
131696 ** (including the null-terminator, if any). Case
131697 ** is respected in comparisons.
131699 ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
131700 ** memcmp() is used to compare keys.
131702 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
131704 #define FTS3_HASH_STRING 1
131705 #define FTS3_HASH_BINARY 2
131708 ** Access routines. To delete, insert a NULL pointer.
131710 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
131711 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
131712 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
131713 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
131714 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
131717 ** Shorthand for the functions above
131719 #define fts3HashInit sqlite3Fts3HashInit
131720 #define fts3HashInsert sqlite3Fts3HashInsert
131721 #define fts3HashFind sqlite3Fts3HashFind
131722 #define fts3HashClear sqlite3Fts3HashClear
131723 #define fts3HashFindElem sqlite3Fts3HashFindElem
131726 ** Macros for looping over all elements of a hash table. The idiom is
131727 ** like this:
131729 ** Fts3Hash h;
131730 ** Fts3HashElem *p;
131731 ** ...
131732 ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
131733 ** SomeStructure *pData = fts3HashData(p);
131734 ** // do something with pData
131737 #define fts3HashFirst(H) ((H)->first)
131738 #define fts3HashNext(E) ((E)->next)
131739 #define fts3HashData(E) ((E)->data)
131740 #define fts3HashKey(E) ((E)->pKey)
131741 #define fts3HashKeysize(E) ((E)->nKey)
131744 ** Number of entries in a hash table
131746 #define fts3HashCount(H) ((H)->count)
131748 #endif /* _FTS3_HASH_H_ */
131750 /************** End of fts3_hash.h *******************************************/
131751 /************** Continuing where we left off in fts3Int.h ********************/
131754 ** This constant determines the maximum depth of an FTS expression tree
131755 ** that the library will create and use. FTS uses recursion to perform
131756 ** various operations on the query tree, so the disadvantage of a large
131757 ** limit is that it may allow very large queries to use large amounts
131758 ** of stack space (perhaps causing a stack overflow).
131760 #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
131761 # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
131762 #endif
131766 ** This constant controls how often segments are merged. Once there are
131767 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
131768 ** segment of level N+1.
131770 #define FTS3_MERGE_COUNT 16
131773 ** This is the maximum amount of data (in bytes) to store in the
131774 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
131775 ** populated as documents are inserted/updated/deleted in a transaction
131776 ** and used to create a new segment when the transaction is committed.
131777 ** However if this limit is reached midway through a transaction, a new
131778 ** segment is created and the hash table cleared immediately.
131780 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
131783 ** Macro to return the number of elements in an array. SQLite has a
131784 ** similar macro called ArraySize(). Use a different name to avoid
131785 ** a collision when building an amalgamation with built-in FTS3.
131787 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
131790 #ifndef MIN
131791 # define MIN(x,y) ((x)<(y)?(x):(y))
131792 #endif
131793 #ifndef MAX
131794 # define MAX(x,y) ((x)>(y)?(x):(y))
131795 #endif
131798 ** Maximum length of a varint encoded integer. The varint format is different
131799 ** from that used by SQLite, so the maximum length is 10, not 9.
131801 #define FTS3_VARINT_MAX 10
131804 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
131805 ** in the document set and zero or more prefix indexes. All indexes are stored
131806 ** as one or more b+-trees in the %_segments and %_segdir tables.
131808 ** It is possible to determine which index a b+-tree belongs to based on the
131809 ** value stored in the "%_segdir.level" column. Given this value L, the index
131810 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
131811 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
131812 ** between 1024 and 2047 to index 1, and so on.
131814 ** It is considered impossible for an index to use more than 1024 levels. In
131815 ** theory though this may happen, but only after at least
131816 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
131818 #define FTS3_SEGDIR_MAXLEVEL 1024
131819 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
131822 ** The testcase() macro is only used by the amalgamation. If undefined,
131823 ** make it a no-op.
131825 #ifndef testcase
131826 # define testcase(X)
131827 #endif
131830 ** Terminator values for position-lists and column-lists.
131832 #define POS_COLUMN (1) /* Column-list terminator */
131833 #define POS_END (0) /* Position-list terminator */
131836 ** This section provides definitions to allow the
131837 ** FTS3 extension to be compiled outside of the
131838 ** amalgamation.
131840 #ifndef SQLITE_AMALGAMATION
131842 ** Macros indicating that conditional expressions are always true or
131843 ** false.
131845 #ifdef SQLITE_COVERAGE_TEST
131846 # define ALWAYS(x) (1)
131847 # define NEVER(X) (0)
131848 #else
131849 # define ALWAYS(x) (x)
131850 # define NEVER(x) (x)
131851 #endif
131854 ** Internal types used by SQLite.
131856 typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
131857 typedef short int i16; /* 2-byte (or larger) signed integer */
131858 typedef unsigned int u32; /* 4-byte unsigned integer */
131859 typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
131860 typedef sqlite3_int64 i64; /* 8-byte signed integer */
131863 ** Macro used to suppress compiler warnings for unused parameters.
131865 #define UNUSED_PARAMETER(x) (void)(x)
131868 ** Activate assert() only if SQLITE_TEST is enabled.
131870 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
131871 # define NDEBUG 1
131872 #endif
131875 ** The TESTONLY macro is used to enclose variable declarations or
131876 ** other bits of code that are needed to support the arguments
131877 ** within testcase() and assert() macros.
131879 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
131880 # define TESTONLY(X) X
131881 #else
131882 # define TESTONLY(X)
131883 #endif
131885 #endif /* SQLITE_AMALGAMATION */
131887 #ifdef SQLITE_DEBUG
131888 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
131889 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
131890 #else
131891 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
131892 #endif
131894 typedef struct Fts3Table Fts3Table;
131895 typedef struct Fts3Cursor Fts3Cursor;
131896 typedef struct Fts3Expr Fts3Expr;
131897 typedef struct Fts3Phrase Fts3Phrase;
131898 typedef struct Fts3PhraseToken Fts3PhraseToken;
131900 typedef struct Fts3Doclist Fts3Doclist;
131901 typedef struct Fts3SegFilter Fts3SegFilter;
131902 typedef struct Fts3DeferredToken Fts3DeferredToken;
131903 typedef struct Fts3SegReader Fts3SegReader;
131904 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
131907 ** A connection to a fulltext index is an instance of the following
131908 ** structure. The xCreate and xConnect methods create an instance
131909 ** of this structure and xDestroy and xDisconnect free that instance.
131910 ** All other methods receive a pointer to the structure as one of their
131911 ** arguments.
131913 struct Fts3Table {
131914 sqlite3_vtab base; /* Base class used by SQLite core */
131915 sqlite3 *db; /* The database connection */
131916 const char *zDb; /* logical database name */
131917 const char *zName; /* virtual table name */
131918 int nColumn; /* number of named columns in virtual table */
131919 char **azColumn; /* column names. malloced */
131920 u8 *abNotindexed; /* True for 'notindexed' columns */
131921 sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
131922 char *zContentTbl; /* content=xxx option, or NULL */
131923 char *zLanguageid; /* languageid=xxx option, or NULL */
131924 int nAutoincrmerge; /* Value configured by 'automerge' */
131925 u32 nLeafAdd; /* Number of leaf blocks added this trans */
131927 /* Precompiled statements used by the implementation. Each of these
131928 ** statements is run and reset within a single virtual table API call.
131930 sqlite3_stmt *aStmt[40];
131932 char *zReadExprlist;
131933 char *zWriteExprlist;
131935 int nNodeSize; /* Soft limit for node size */
131936 u8 bFts4; /* True for FTS4, false for FTS3 */
131937 u8 bHasStat; /* True if %_stat table exists (2==unknown) */
131938 u8 bHasDocsize; /* True if %_docsize table exists */
131939 u8 bDescIdx; /* True if doclists are in reverse order */
131940 u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
131941 int nPgsz; /* Page size for host database */
131942 char *zSegmentsTbl; /* Name of %_segments table */
131943 sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
131946 ** The following array of hash tables is used to buffer pending index
131947 ** updates during transactions. All pending updates buffered at any one
131948 ** time must share a common language-id (see the FTS4 langid= feature).
131949 ** The current language id is stored in variable iPrevLangid.
131951 ** A single FTS4 table may have multiple full-text indexes. For each index
131952 ** there is an entry in the aIndex[] array. Index 0 is an index of all the
131953 ** terms that appear in the document set. Each subsequent index in aIndex[]
131954 ** is an index of prefixes of a specific length.
131956 ** Variable nPendingData contains an estimate the memory consumed by the
131957 ** pending data structures, including hash table overhead, but not including
131958 ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
131959 ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
131960 ** recently inserted record.
131962 int nIndex; /* Size of aIndex[] */
131963 struct Fts3Index {
131964 int nPrefix; /* Prefix length (0 for main terms index) */
131965 Fts3Hash hPending; /* Pending terms table for this index */
131966 } *aIndex;
131967 int nMaxPendingData; /* Max pending data before flush to disk */
131968 int nPendingData; /* Current bytes of pending data */
131969 sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
131970 int iPrevLangid; /* Langid of recently inserted document */
131972 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
131973 /* State variables used for validating that the transaction control
131974 ** methods of the virtual table are called at appropriate times. These
131975 ** values do not contribute to FTS functionality; they are used for
131976 ** verifying the operation of the SQLite core.
131978 int inTransaction; /* True after xBegin but before xCommit/xRollback */
131979 int mxSavepoint; /* Largest valid xSavepoint integer */
131980 #endif
131982 #ifdef SQLITE_TEST
131983 /* True to disable the incremental doclist optimization. This is controled
131984 ** by special insert command 'test-no-incr-doclist'. */
131985 int bNoIncrDoclist;
131986 #endif
131990 ** When the core wants to read from the virtual table, it creates a
131991 ** virtual table cursor (an instance of the following structure) using
131992 ** the xOpen method. Cursors are destroyed using the xClose method.
131994 struct Fts3Cursor {
131995 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
131996 i16 eSearch; /* Search strategy (see below) */
131997 u8 isEof; /* True if at End Of Results */
131998 u8 isRequireSeek; /* True if must seek pStmt to %_content row */
131999 sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
132000 Fts3Expr *pExpr; /* Parsed MATCH query string */
132001 int iLangid; /* Language being queried for */
132002 int nPhrase; /* Number of matchable phrases in query */
132003 Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
132004 sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
132005 char *pNextId; /* Pointer into the body of aDoclist */
132006 char *aDoclist; /* List of docids for full-text queries */
132007 int nDoclist; /* Size of buffer at aDoclist */
132008 u8 bDesc; /* True to sort in descending order */
132009 int eEvalmode; /* An FTS3_EVAL_XX constant */
132010 int nRowAvg; /* Average size of database rows, in pages */
132011 sqlite3_int64 nDoc; /* Documents in table */
132012 i64 iMinDocid; /* Minimum docid to return */
132013 i64 iMaxDocid; /* Maximum docid to return */
132014 int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
132015 u32 *aMatchinfo; /* Information about most recent match */
132016 int nMatchinfo; /* Number of elements in aMatchinfo[] */
132017 char *zMatchinfo; /* Matchinfo specification */
132020 #define FTS3_EVAL_FILTER 0
132021 #define FTS3_EVAL_NEXT 1
132022 #define FTS3_EVAL_MATCHINFO 2
132025 ** The Fts3Cursor.eSearch member is always set to one of the following.
132026 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
132027 ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
132028 ** of the column to be searched. For example, in
132030 ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
132031 ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
132033 ** Because the LHS of the MATCH operator is 2nd column "b",
132034 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
132035 ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
132036 ** indicating that all columns should be searched,
132037 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
132039 #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
132040 #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
132041 #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
132044 ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
132045 ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
132046 ** above. The upper 16-bits contain a combination of the following
132047 ** bits, used to describe extra constraints on full-text searches.
132049 #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
132050 #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
132051 #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
132053 struct Fts3Doclist {
132054 char *aAll; /* Array containing doclist (or NULL) */
132055 int nAll; /* Size of a[] in bytes */
132056 char *pNextDocid; /* Pointer to next docid */
132058 sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
132059 int bFreeList; /* True if pList should be sqlite3_free()d */
132060 char *pList; /* Pointer to position list following iDocid */
132061 int nList; /* Length of position list */
132065 ** A "phrase" is a sequence of one or more tokens that must match in
132066 ** sequence. A single token is the base case and the most common case.
132067 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
132068 ** nToken will be the number of tokens in the string.
132070 struct Fts3PhraseToken {
132071 char *z; /* Text of the token */
132072 int n; /* Number of bytes in buffer z */
132073 int isPrefix; /* True if token ends with a "*" character */
132074 int bFirst; /* True if token must appear at position 0 */
132076 /* Variables above this point are populated when the expression is
132077 ** parsed (by code in fts3_expr.c). Below this point the variables are
132078 ** used when evaluating the expression. */
132079 Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
132080 Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
132083 struct Fts3Phrase {
132084 /* Cache of doclist for this phrase. */
132085 Fts3Doclist doclist;
132086 int bIncr; /* True if doclist is loaded incrementally */
132087 int iDoclistToken;
132089 /* Variables below this point are populated by fts3_expr.c when parsing
132090 ** a MATCH expression. Everything above is part of the evaluation phase.
132092 int nToken; /* Number of tokens in the phrase */
132093 int iColumn; /* Index of column this phrase must match */
132094 Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
132098 ** A tree of these objects forms the RHS of a MATCH operator.
132100 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
132101 ** points to a malloced buffer, size nDoclist bytes, containing the results
132102 ** of this phrase query in FTS3 doclist format. As usual, the initial
132103 ** "Length" field found in doclists stored on disk is omitted from this
132104 ** buffer.
132106 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
132107 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
132108 ** where nCol is the number of columns in the queried FTS table. The array
132109 ** is populated as follows:
132111 ** aMI[iCol*3 + 0] = Undefined
132112 ** aMI[iCol*3 + 1] = Number of occurrences
132113 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
132115 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
132116 ** when the expression node is.
132118 struct Fts3Expr {
132119 int eType; /* One of the FTSQUERY_XXX values defined below */
132120 int nNear; /* Valid if eType==FTSQUERY_NEAR */
132121 Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
132122 Fts3Expr *pLeft; /* Left operand */
132123 Fts3Expr *pRight; /* Right operand */
132124 Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
132126 /* The following are used by the fts3_eval.c module. */
132127 sqlite3_int64 iDocid; /* Current docid */
132128 u8 bEof; /* True this expression is at EOF already */
132129 u8 bStart; /* True if iDocid is valid */
132130 u8 bDeferred; /* True if this expression is entirely deferred */
132132 u32 *aMI;
132136 ** Candidate values for Fts3Query.eType. Note that the order of the first
132137 ** four values is in order of precedence when parsing expressions. For
132138 ** example, the following:
132140 ** "a OR b AND c NOT d NEAR e"
132142 ** is equivalent to:
132144 ** "a OR (b AND (c NOT (d NEAR e)))"
132146 #define FTSQUERY_NEAR 1
132147 #define FTSQUERY_NOT 2
132148 #define FTSQUERY_AND 3
132149 #define FTSQUERY_OR 4
132150 #define FTSQUERY_PHRASE 5
132153 /* fts3_write.c */
132154 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
132155 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
132156 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
132157 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
132158 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
132159 sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
132160 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
132161 Fts3Table*,int,const char*,int,int,Fts3SegReader**);
132162 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
132163 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
132164 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
132166 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
132167 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
132169 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
132170 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
132171 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
132172 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
132173 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
132174 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
132175 #else
132176 # define sqlite3Fts3FreeDeferredTokens(x)
132177 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
132178 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
132179 # define sqlite3Fts3FreeDeferredDoclists(x)
132180 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
132181 #endif
132183 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
132184 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
132186 /* Special values interpreted by sqlite3SegReaderCursor() */
132187 #define FTS3_SEGCURSOR_PENDING -1
132188 #define FTS3_SEGCURSOR_ALL -2
132190 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
132191 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
132192 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
132194 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
132195 int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
132197 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
132198 #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
132199 #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
132200 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
132201 #define FTS3_SEGMENT_PREFIX 0x00000008
132202 #define FTS3_SEGMENT_SCAN 0x00000010
132203 #define FTS3_SEGMENT_FIRST 0x00000020
132205 /* Type passed as 4th argument to SegmentReaderIterate() */
132206 struct Fts3SegFilter {
132207 const char *zTerm;
132208 int nTerm;
132209 int iCol;
132210 int flags;
132213 struct Fts3MultiSegReader {
132214 /* Used internally by sqlite3Fts3SegReaderXXX() calls */
132215 Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
132216 int nSegment; /* Size of apSegment array */
132217 int nAdvance; /* How many seg-readers to advance */
132218 Fts3SegFilter *pFilter; /* Pointer to filter object */
132219 char *aBuffer; /* Buffer to merge doclists in */
132220 int nBuffer; /* Allocated size of aBuffer[] in bytes */
132222 int iColFilter; /* If >=0, filter for this column */
132223 int bRestart;
132225 /* Used by fts3.c only. */
132226 int nCost; /* Cost of running iterator */
132227 int bLookup; /* True if a lookup of a single entry. */
132229 /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
132230 char *zTerm; /* Pointer to term buffer */
132231 int nTerm; /* Size of zTerm in bytes */
132232 char *aDoclist; /* Pointer to doclist buffer */
132233 int nDoclist; /* Size of aDoclist[] in bytes */
132236 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
132238 #define fts3GetVarint32(p, piVal) ( \
132239 (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
132242 /* fts3.c */
132243 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
132244 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
132245 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
132246 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
132247 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
132248 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
132249 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
132250 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
132251 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
132253 /* fts3_tokenizer.c */
132254 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
132255 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
132256 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
132257 sqlite3_tokenizer **, char **
132259 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
132261 /* fts3_snippet.c */
132262 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
132263 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
132264 const char *, const char *, int, int
132266 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
132268 /* fts3_expr.c */
132269 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
132270 char **, int, int, int, const char *, int, Fts3Expr **, char **
132272 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
132273 #ifdef SQLITE_TEST
132274 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
132275 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
132276 #endif
132278 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
132279 sqlite3_tokenizer_cursor **
132282 /* fts3_aux.c */
132283 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
132285 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
132287 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
132288 Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
132289 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
132290 Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
132291 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
132292 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
132293 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
132295 /* fts3_tokenize_vtab.c */
132296 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
132298 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
132299 #ifndef SQLITE_DISABLE_FTS3_UNICODE
132300 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
132301 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
132302 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
132303 #endif
132305 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
132306 #endif /* _FTSINT_H */
132308 /************** End of fts3Int.h *********************************************/
132309 /************** Continuing where we left off in fts3.c ***********************/
132310 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
132312 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
132313 # define SQLITE_CORE 1
132314 #endif
132316 /* #include <assert.h> */
132317 /* #include <stdlib.h> */
132318 /* #include <stddef.h> */
132319 /* #include <stdio.h> */
132320 /* #include <string.h> */
132321 /* #include <stdarg.h> */
132323 #ifndef SQLITE_CORE
132324 SQLITE_EXTENSION_INIT1
132325 #endif
132327 static int fts3EvalNext(Fts3Cursor *pCsr);
132328 static int fts3EvalStart(Fts3Cursor *pCsr);
132329 static int fts3TermSegReaderCursor(
132330 Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
132333 ** Write a 64-bit variable-length integer to memory starting at p[0].
132334 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
132335 ** The number of bytes written is returned.
132337 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
132338 unsigned char *q = (unsigned char *) p;
132339 sqlite_uint64 vu = v;
132341 *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
132342 vu >>= 7;
132343 }while( vu!=0 );
132344 q[-1] &= 0x7f; /* turn off high bit in final byte */
132345 assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
132346 return (int) (q - (unsigned char *)p);
132349 #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
132350 v = (v & mask1) | ( (*ptr++) << shift ); \
132351 if( (v & mask2)==0 ){ var = v; return ret; }
132352 #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
132353 v = (*ptr++); \
132354 if( (v & mask2)==0 ){ var = v; return ret; }
132357 ** Read a 64-bit variable-length integer from memory starting at p[0].
132358 ** Return the number of bytes read, or 0 on error.
132359 ** The value is stored in *v.
132361 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
132362 const char *pStart = p;
132363 u32 a;
132364 u64 b;
132365 int shift;
132367 GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
132368 GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
132369 GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
132370 GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
132371 b = (a & 0x0FFFFFFF );
132373 for(shift=28; shift<=63; shift+=7){
132374 u64 c = *p++;
132375 b += (c&0x7F) << shift;
132376 if( (c & 0x80)==0 ) break;
132378 *v = b;
132379 return (int)(p - pStart);
132383 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
132384 ** 32-bit integer before it is returned.
132386 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
132387 u32 a;
132389 #ifndef fts3GetVarint32
132390 GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
132391 #else
132392 a = (*p++);
132393 assert( a & 0x80 );
132394 #endif
132396 GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
132397 GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
132398 GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
132399 a = (a & 0x0FFFFFFF );
132400 *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
132401 return 5;
132405 ** Return the number of bytes required to encode v as a varint
132407 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
132408 int i = 0;
132411 v >>= 7;
132412 }while( v!=0 );
132413 return i;
132417 ** Convert an SQL-style quoted string into a normal string by removing
132418 ** the quote characters. The conversion is done in-place. If the
132419 ** input does not begin with a quote character, then this routine
132420 ** is a no-op.
132422 ** Examples:
132424 ** "abc" becomes abc
132425 ** 'xyz' becomes xyz
132426 ** [pqr] becomes pqr
132427 ** `mno` becomes mno
132430 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
132431 char quote; /* Quote character (if any ) */
132433 quote = z[0];
132434 if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
132435 int iIn = 1; /* Index of next byte to read from input */
132436 int iOut = 0; /* Index of next byte to write to output */
132438 /* If the first byte was a '[', then the close-quote character is a ']' */
132439 if( quote=='[' ) quote = ']';
132441 while( ALWAYS(z[iIn]) ){
132442 if( z[iIn]==quote ){
132443 if( z[iIn+1]!=quote ) break;
132444 z[iOut++] = quote;
132445 iIn += 2;
132446 }else{
132447 z[iOut++] = z[iIn++];
132450 z[iOut] = '\0';
132455 ** Read a single varint from the doclist at *pp and advance *pp to point
132456 ** to the first byte past the end of the varint. Add the value of the varint
132457 ** to *pVal.
132459 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
132460 sqlite3_int64 iVal;
132461 *pp += sqlite3Fts3GetVarint(*pp, &iVal);
132462 *pVal += iVal;
132466 ** When this function is called, *pp points to the first byte following a
132467 ** varint that is part of a doclist (or position-list, or any other list
132468 ** of varints). This function moves *pp to point to the start of that varint,
132469 ** and sets *pVal by the varint value.
132471 ** Argument pStart points to the first byte of the doclist that the
132472 ** varint is part of.
132474 static void fts3GetReverseVarint(
132475 char **pp,
132476 char *pStart,
132477 sqlite3_int64 *pVal
132479 sqlite3_int64 iVal;
132480 char *p;
132482 /* Pointer p now points at the first byte past the varint we are
132483 ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
132484 ** clear on character p[-1]. */
132485 for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
132487 *pp = p;
132489 sqlite3Fts3GetVarint(p, &iVal);
132490 *pVal = iVal;
132494 ** The xDisconnect() virtual table method.
132496 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
132497 Fts3Table *p = (Fts3Table *)pVtab;
132498 int i;
132500 assert( p->nPendingData==0 );
132501 assert( p->pSegments==0 );
132503 /* Free any prepared statements held */
132504 for(i=0; i<SizeofArray(p->aStmt); i++){
132505 sqlite3_finalize(p->aStmt[i]);
132507 sqlite3_free(p->zSegmentsTbl);
132508 sqlite3_free(p->zReadExprlist);
132509 sqlite3_free(p->zWriteExprlist);
132510 sqlite3_free(p->zContentTbl);
132511 sqlite3_free(p->zLanguageid);
132513 /* Invoke the tokenizer destructor to free the tokenizer. */
132514 p->pTokenizer->pModule->xDestroy(p->pTokenizer);
132516 sqlite3_free(p);
132517 return SQLITE_OK;
132521 ** Construct one or more SQL statements from the format string given
132522 ** and then evaluate those statements. The success code is written
132523 ** into *pRc.
132525 ** If *pRc is initially non-zero then this routine is a no-op.
132527 static void fts3DbExec(
132528 int *pRc, /* Success code */
132529 sqlite3 *db, /* Database in which to run SQL */
132530 const char *zFormat, /* Format string for SQL */
132531 ... /* Arguments to the format string */
132533 va_list ap;
132534 char *zSql;
132535 if( *pRc ) return;
132536 va_start(ap, zFormat);
132537 zSql = sqlite3_vmprintf(zFormat, ap);
132538 va_end(ap);
132539 if( zSql==0 ){
132540 *pRc = SQLITE_NOMEM;
132541 }else{
132542 *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
132543 sqlite3_free(zSql);
132548 ** The xDestroy() virtual table method.
132550 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
132551 Fts3Table *p = (Fts3Table *)pVtab;
132552 int rc = SQLITE_OK; /* Return code */
132553 const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
132554 sqlite3 *db = p->db; /* Database handle */
132556 /* Drop the shadow tables */
132557 if( p->zContentTbl==0 ){
132558 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
132560 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
132561 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
132562 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
132563 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
132565 /* If everything has worked, invoke fts3DisconnectMethod() to free the
132566 ** memory associated with the Fts3Table structure and return SQLITE_OK.
132567 ** Otherwise, return an SQLite error code.
132569 return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
132574 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
132575 ** passed as the first argument. This is done as part of the xConnect()
132576 ** and xCreate() methods.
132578 ** If *pRc is non-zero when this function is called, it is a no-op.
132579 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
132580 ** before returning.
132582 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
132583 if( *pRc==SQLITE_OK ){
132584 int i; /* Iterator variable */
132585 int rc; /* Return code */
132586 char *zSql; /* SQL statement passed to declare_vtab() */
132587 char *zCols; /* List of user defined columns */
132588 const char *zLanguageid;
132590 zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
132591 sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
132593 /* Create a list of user columns for the virtual table */
132594 zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
132595 for(i=1; zCols && i<p->nColumn; i++){
132596 zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
132599 /* Create the whole "CREATE TABLE" statement to pass to SQLite */
132600 zSql = sqlite3_mprintf(
132601 "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
132602 zCols, p->zName, zLanguageid
132604 if( !zCols || !zSql ){
132605 rc = SQLITE_NOMEM;
132606 }else{
132607 rc = sqlite3_declare_vtab(p->db, zSql);
132610 sqlite3_free(zSql);
132611 sqlite3_free(zCols);
132612 *pRc = rc;
132617 ** Create the %_stat table if it does not already exist.
132619 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
132620 fts3DbExec(pRc, p->db,
132621 "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
132622 "(id INTEGER PRIMARY KEY, value BLOB);",
132623 p->zDb, p->zName
132625 if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
132629 ** Create the backing store tables (%_content, %_segments and %_segdir)
132630 ** required by the FTS3 table passed as the only argument. This is done
132631 ** as part of the vtab xCreate() method.
132633 ** If the p->bHasDocsize boolean is true (indicating that this is an
132634 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
132635 ** %_stat tables required by FTS4.
132637 static int fts3CreateTables(Fts3Table *p){
132638 int rc = SQLITE_OK; /* Return code */
132639 int i; /* Iterator variable */
132640 sqlite3 *db = p->db; /* The database connection */
132642 if( p->zContentTbl==0 ){
132643 const char *zLanguageid = p->zLanguageid;
132644 char *zContentCols; /* Columns of %_content table */
132646 /* Create a list of user columns for the content table */
132647 zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
132648 for(i=0; zContentCols && i<p->nColumn; i++){
132649 char *z = p->azColumn[i];
132650 zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
132652 if( zLanguageid && zContentCols ){
132653 zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
132655 if( zContentCols==0 ) rc = SQLITE_NOMEM;
132657 /* Create the content table */
132658 fts3DbExec(&rc, db,
132659 "CREATE TABLE %Q.'%q_content'(%s)",
132660 p->zDb, p->zName, zContentCols
132662 sqlite3_free(zContentCols);
132665 /* Create other tables */
132666 fts3DbExec(&rc, db,
132667 "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
132668 p->zDb, p->zName
132670 fts3DbExec(&rc, db,
132671 "CREATE TABLE %Q.'%q_segdir'("
132672 "level INTEGER,"
132673 "idx INTEGER,"
132674 "start_block INTEGER,"
132675 "leaves_end_block INTEGER,"
132676 "end_block INTEGER,"
132677 "root BLOB,"
132678 "PRIMARY KEY(level, idx)"
132679 ");",
132680 p->zDb, p->zName
132682 if( p->bHasDocsize ){
132683 fts3DbExec(&rc, db,
132684 "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
132685 p->zDb, p->zName
132688 assert( p->bHasStat==p->bFts4 );
132689 if( p->bHasStat ){
132690 sqlite3Fts3CreateStatTable(&rc, p);
132692 return rc;
132696 ** Store the current database page-size in bytes in p->nPgsz.
132698 ** If *pRc is non-zero when this function is called, it is a no-op.
132699 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
132700 ** before returning.
132702 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
132703 if( *pRc==SQLITE_OK ){
132704 int rc; /* Return code */
132705 char *zSql; /* SQL text "PRAGMA %Q.page_size" */
132706 sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
132708 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
132709 if( !zSql ){
132710 rc = SQLITE_NOMEM;
132711 }else{
132712 rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
132713 if( rc==SQLITE_OK ){
132714 sqlite3_step(pStmt);
132715 p->nPgsz = sqlite3_column_int(pStmt, 0);
132716 rc = sqlite3_finalize(pStmt);
132717 }else if( rc==SQLITE_AUTH ){
132718 p->nPgsz = 1024;
132719 rc = SQLITE_OK;
132722 assert( p->nPgsz>0 || rc!=SQLITE_OK );
132723 sqlite3_free(zSql);
132724 *pRc = rc;
132729 ** "Special" FTS4 arguments are column specifications of the following form:
132731 ** <key> = <value>
132733 ** There may not be whitespace surrounding the "=" character. The <value>
132734 ** term may be quoted, but the <key> may not.
132736 static int fts3IsSpecialColumn(
132737 const char *z,
132738 int *pnKey,
132739 char **pzValue
132741 char *zValue;
132742 const char *zCsr = z;
132744 while( *zCsr!='=' ){
132745 if( *zCsr=='\0' ) return 0;
132746 zCsr++;
132749 *pnKey = (int)(zCsr-z);
132750 zValue = sqlite3_mprintf("%s", &zCsr[1]);
132751 if( zValue ){
132752 sqlite3Fts3Dequote(zValue);
132754 *pzValue = zValue;
132755 return 1;
132759 ** Append the output of a printf() style formatting to an existing string.
132761 static void fts3Appendf(
132762 int *pRc, /* IN/OUT: Error code */
132763 char **pz, /* IN/OUT: Pointer to string buffer */
132764 const char *zFormat, /* Printf format string to append */
132765 ... /* Arguments for printf format string */
132767 if( *pRc==SQLITE_OK ){
132768 va_list ap;
132769 char *z;
132770 va_start(ap, zFormat);
132771 z = sqlite3_vmprintf(zFormat, ap);
132772 va_end(ap);
132773 if( z && *pz ){
132774 char *z2 = sqlite3_mprintf("%s%s", *pz, z);
132775 sqlite3_free(z);
132776 z = z2;
132778 if( z==0 ) *pRc = SQLITE_NOMEM;
132779 sqlite3_free(*pz);
132780 *pz = z;
132785 ** Return a copy of input string zInput enclosed in double-quotes (") and
132786 ** with all double quote characters escaped. For example:
132788 ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
132790 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
132791 ** is the callers responsibility to call sqlite3_free() to release this
132792 ** memory.
132794 static char *fts3QuoteId(char const *zInput){
132795 int nRet;
132796 char *zRet;
132797 nRet = 2 + (int)strlen(zInput)*2 + 1;
132798 zRet = sqlite3_malloc(nRet);
132799 if( zRet ){
132800 int i;
132801 char *z = zRet;
132802 *(z++) = '"';
132803 for(i=0; zInput[i]; i++){
132804 if( zInput[i]=='"' ) *(z++) = '"';
132805 *(z++) = zInput[i];
132807 *(z++) = '"';
132808 *(z++) = '\0';
132810 return zRet;
132814 ** Return a list of comma separated SQL expressions and a FROM clause that
132815 ** could be used in a SELECT statement such as the following:
132817 ** SELECT <list of expressions> FROM %_content AS x ...
132819 ** to return the docid, followed by each column of text data in order
132820 ** from left to write. If parameter zFunc is not NULL, then instead of
132821 ** being returned directly each column of text data is passed to an SQL
132822 ** function named zFunc first. For example, if zFunc is "unzip" and the
132823 ** table has the three user-defined columns "a", "b", and "c", the following
132824 ** string is returned:
132826 ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
132828 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
132829 ** is the responsibility of the caller to eventually free it.
132831 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
132832 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
132833 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
132834 ** no error occurs, *pRc is left unmodified.
132836 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
132837 char *zRet = 0;
132838 char *zFree = 0;
132839 char *zFunction;
132840 int i;
132842 if( p->zContentTbl==0 ){
132843 if( !zFunc ){
132844 zFunction = "";
132845 }else{
132846 zFree = zFunction = fts3QuoteId(zFunc);
132848 fts3Appendf(pRc, &zRet, "docid");
132849 for(i=0; i<p->nColumn; i++){
132850 fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
132852 if( p->zLanguageid ){
132853 fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
132855 sqlite3_free(zFree);
132856 }else{
132857 fts3Appendf(pRc, &zRet, "rowid");
132858 for(i=0; i<p->nColumn; i++){
132859 fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
132861 if( p->zLanguageid ){
132862 fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
132865 fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
132866 p->zDb,
132867 (p->zContentTbl ? p->zContentTbl : p->zName),
132868 (p->zContentTbl ? "" : "_content")
132870 return zRet;
132874 ** Return a list of N comma separated question marks, where N is the number
132875 ** of columns in the %_content table (one for the docid plus one for each
132876 ** user-defined text column).
132878 ** If argument zFunc is not NULL, then all but the first question mark
132879 ** is preceded by zFunc and an open bracket, and followed by a closed
132880 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
132881 ** user-defined text columns, the following string is returned:
132883 ** "?, zip(?), zip(?), zip(?)"
132885 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
132886 ** is the responsibility of the caller to eventually free it.
132888 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
132889 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
132890 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
132891 ** no error occurs, *pRc is left unmodified.
132893 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
132894 char *zRet = 0;
132895 char *zFree = 0;
132896 char *zFunction;
132897 int i;
132899 if( !zFunc ){
132900 zFunction = "";
132901 }else{
132902 zFree = zFunction = fts3QuoteId(zFunc);
132904 fts3Appendf(pRc, &zRet, "?");
132905 for(i=0; i<p->nColumn; i++){
132906 fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
132908 if( p->zLanguageid ){
132909 fts3Appendf(pRc, &zRet, ", ?");
132911 sqlite3_free(zFree);
132912 return zRet;
132916 ** This function interprets the string at (*pp) as a non-negative integer
132917 ** value. It reads the integer and sets *pnOut to the value read, then
132918 ** sets *pp to point to the byte immediately following the last byte of
132919 ** the integer value.
132921 ** Only decimal digits ('0'..'9') may be part of an integer value.
132923 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
132924 ** the output value undefined. Otherwise SQLITE_OK is returned.
132926 ** This function is used when parsing the "prefix=" FTS4 parameter.
132928 static int fts3GobbleInt(const char **pp, int *pnOut){
132929 const char *p; /* Iterator pointer */
132930 int nInt = 0; /* Output value */
132932 for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
132933 nInt = nInt * 10 + (p[0] - '0');
132935 if( p==*pp ) return SQLITE_ERROR;
132936 *pnOut = nInt;
132937 *pp = p;
132938 return SQLITE_OK;
132942 ** This function is called to allocate an array of Fts3Index structures
132943 ** representing the indexes maintained by the current FTS table. FTS tables
132944 ** always maintain the main "terms" index, but may also maintain one or
132945 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
132946 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
132948 ** Argument zParam is passed the value of the "prefix=" option if one was
132949 ** specified, or NULL otherwise.
132951 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
132952 ** the allocated array. *pnIndex is set to the number of elements in the
132953 ** array. If an error does occur, an SQLite error code is returned.
132955 ** Regardless of whether or not an error is returned, it is the responsibility
132956 ** of the caller to call sqlite3_free() on the output array to free it.
132958 static int fts3PrefixParameter(
132959 const char *zParam, /* ABC in prefix=ABC parameter to parse */
132960 int *pnIndex, /* OUT: size of *apIndex[] array */
132961 struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
132963 struct Fts3Index *aIndex; /* Allocated array */
132964 int nIndex = 1; /* Number of entries in array */
132966 if( zParam && zParam[0] ){
132967 const char *p;
132968 nIndex++;
132969 for(p=zParam; *p; p++){
132970 if( *p==',' ) nIndex++;
132974 aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
132975 *apIndex = aIndex;
132976 *pnIndex = nIndex;
132977 if( !aIndex ){
132978 return SQLITE_NOMEM;
132981 memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
132982 if( zParam ){
132983 const char *p = zParam;
132984 int i;
132985 for(i=1; i<nIndex; i++){
132986 int nPrefix;
132987 if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
132988 aIndex[i].nPrefix = nPrefix;
132993 return SQLITE_OK;
132997 ** This function is called when initializing an FTS4 table that uses the
132998 ** content=xxx option. It determines the number of and names of the columns
132999 ** of the new FTS4 table.
133001 ** The third argument passed to this function is the value passed to the
133002 ** config=xxx option (i.e. "xxx"). This function queries the database for
133003 ** a table of that name. If found, the output variables are populated
133004 ** as follows:
133006 ** *pnCol: Set to the number of columns table xxx has,
133008 ** *pnStr: Set to the total amount of space required to store a copy
133009 ** of each columns name, including the nul-terminator.
133011 ** *pazCol: Set to point to an array of *pnCol strings. Each string is
133012 ** the name of the corresponding column in table xxx. The array
133013 ** and its contents are allocated using a single allocation. It
133014 ** is the responsibility of the caller to free this allocation
133015 ** by eventually passing the *pazCol value to sqlite3_free().
133017 ** If the table cannot be found, an error code is returned and the output
133018 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
133019 ** returned (and the output variables are undefined).
133021 static int fts3ContentColumns(
133022 sqlite3 *db, /* Database handle */
133023 const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
133024 const char *zTbl, /* Name of content table */
133025 const char ***pazCol, /* OUT: Malloc'd array of column names */
133026 int *pnCol, /* OUT: Size of array *pazCol */
133027 int *pnStr /* OUT: Bytes of string content */
133029 int rc = SQLITE_OK; /* Return code */
133030 char *zSql; /* "SELECT *" statement on zTbl */
133031 sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
133033 zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
133034 if( !zSql ){
133035 rc = SQLITE_NOMEM;
133036 }else{
133037 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
133039 sqlite3_free(zSql);
133041 if( rc==SQLITE_OK ){
133042 const char **azCol; /* Output array */
133043 int nStr = 0; /* Size of all column names (incl. 0x00) */
133044 int nCol; /* Number of table columns */
133045 int i; /* Used to iterate through columns */
133047 /* Loop through the returned columns. Set nStr to the number of bytes of
133048 ** space required to store a copy of each column name, including the
133049 ** nul-terminator byte. */
133050 nCol = sqlite3_column_count(pStmt);
133051 for(i=0; i<nCol; i++){
133052 const char *zCol = sqlite3_column_name(pStmt, i);
133053 nStr += (int)strlen(zCol) + 1;
133056 /* Allocate and populate the array to return. */
133057 azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
133058 if( azCol==0 ){
133059 rc = SQLITE_NOMEM;
133060 }else{
133061 char *p = (char *)&azCol[nCol];
133062 for(i=0; i<nCol; i++){
133063 const char *zCol = sqlite3_column_name(pStmt, i);
133064 int n = (int)strlen(zCol)+1;
133065 memcpy(p, zCol, n);
133066 azCol[i] = p;
133067 p += n;
133070 sqlite3_finalize(pStmt);
133072 /* Set the output variables. */
133073 *pnCol = nCol;
133074 *pnStr = nStr;
133075 *pazCol = azCol;
133078 return rc;
133082 ** This function is the implementation of both the xConnect and xCreate
133083 ** methods of the FTS3 virtual table.
133085 ** The argv[] array contains the following:
133087 ** argv[0] -> module name ("fts3" or "fts4")
133088 ** argv[1] -> database name
133089 ** argv[2] -> table name
133090 ** argv[...] -> "column name" and other module argument fields.
133092 static int fts3InitVtab(
133093 int isCreate, /* True for xCreate, false for xConnect */
133094 sqlite3 *db, /* The SQLite database connection */
133095 void *pAux, /* Hash table containing tokenizers */
133096 int argc, /* Number of elements in argv array */
133097 const char * const *argv, /* xCreate/xConnect argument array */
133098 sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
133099 char **pzErr /* Write any error message here */
133101 Fts3Hash *pHash = (Fts3Hash *)pAux;
133102 Fts3Table *p = 0; /* Pointer to allocated vtab */
133103 int rc = SQLITE_OK; /* Return code */
133104 int i; /* Iterator variable */
133105 int nByte; /* Size of allocation used for *p */
133106 int iCol; /* Column index */
133107 int nString = 0; /* Bytes required to hold all column names */
133108 int nCol = 0; /* Number of columns in the FTS table */
133109 char *zCsr; /* Space for holding column names */
133110 int nDb; /* Bytes required to hold database name */
133111 int nName; /* Bytes required to hold table name */
133112 int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
133113 const char **aCol; /* Array of column names */
133114 sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
133116 int nIndex; /* Size of aIndex[] array */
133117 struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
133119 /* The results of parsing supported FTS4 key=value options: */
133120 int bNoDocsize = 0; /* True to omit %_docsize table */
133121 int bDescIdx = 0; /* True to store descending indexes */
133122 char *zPrefix = 0; /* Prefix parameter value (or NULL) */
133123 char *zCompress = 0; /* compress=? parameter (or NULL) */
133124 char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
133125 char *zContent = 0; /* content=? parameter (or NULL) */
133126 char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
133127 char **azNotindexed = 0; /* The set of notindexed= columns */
133128 int nNotindexed = 0; /* Size of azNotindexed[] array */
133130 assert( strlen(argv[0])==4 );
133131 assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
133132 || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
133135 nDb = (int)strlen(argv[1]) + 1;
133136 nName = (int)strlen(argv[2]) + 1;
133138 nByte = sizeof(const char *) * (argc-2);
133139 aCol = (const char **)sqlite3_malloc(nByte);
133140 if( aCol ){
133141 memset((void*)aCol, 0, nByte);
133142 azNotindexed = (char **)sqlite3_malloc(nByte);
133144 if( azNotindexed ){
133145 memset(azNotindexed, 0, nByte);
133147 if( !aCol || !azNotindexed ){
133148 rc = SQLITE_NOMEM;
133149 goto fts3_init_out;
133152 /* Loop through all of the arguments passed by the user to the FTS3/4
133153 ** module (i.e. all the column names and special arguments). This loop
133154 ** does the following:
133156 ** + Figures out the number of columns the FTSX table will have, and
133157 ** the number of bytes of space that must be allocated to store copies
133158 ** of the column names.
133160 ** + If there is a tokenizer specification included in the arguments,
133161 ** initializes the tokenizer pTokenizer.
133163 for(i=3; rc==SQLITE_OK && i<argc; i++){
133164 char const *z = argv[i];
133165 int nKey;
133166 char *zVal;
133168 /* Check if this is a tokenizer specification */
133169 if( !pTokenizer
133170 && strlen(z)>8
133171 && 0==sqlite3_strnicmp(z, "tokenize", 8)
133172 && 0==sqlite3Fts3IsIdChar(z[8])
133174 rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
133177 /* Check if it is an FTS4 special argument. */
133178 else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
133179 struct Fts4Option {
133180 const char *zOpt;
133181 int nOpt;
133182 } aFts4Opt[] = {
133183 { "matchinfo", 9 }, /* 0 -> MATCHINFO */
133184 { "prefix", 6 }, /* 1 -> PREFIX */
133185 { "compress", 8 }, /* 2 -> COMPRESS */
133186 { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
133187 { "order", 5 }, /* 4 -> ORDER */
133188 { "content", 7 }, /* 5 -> CONTENT */
133189 { "languageid", 10 }, /* 6 -> LANGUAGEID */
133190 { "notindexed", 10 } /* 7 -> NOTINDEXED */
133193 int iOpt;
133194 if( !zVal ){
133195 rc = SQLITE_NOMEM;
133196 }else{
133197 for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
133198 struct Fts4Option *pOp = &aFts4Opt[iOpt];
133199 if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
133200 break;
133203 if( iOpt==SizeofArray(aFts4Opt) ){
133204 *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
133205 rc = SQLITE_ERROR;
133206 }else{
133207 switch( iOpt ){
133208 case 0: /* MATCHINFO */
133209 if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
133210 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
133211 rc = SQLITE_ERROR;
133213 bNoDocsize = 1;
133214 break;
133216 case 1: /* PREFIX */
133217 sqlite3_free(zPrefix);
133218 zPrefix = zVal;
133219 zVal = 0;
133220 break;
133222 case 2: /* COMPRESS */
133223 sqlite3_free(zCompress);
133224 zCompress = zVal;
133225 zVal = 0;
133226 break;
133228 case 3: /* UNCOMPRESS */
133229 sqlite3_free(zUncompress);
133230 zUncompress = zVal;
133231 zVal = 0;
133232 break;
133234 case 4: /* ORDER */
133235 if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
133236 && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
133238 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
133239 rc = SQLITE_ERROR;
133241 bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
133242 break;
133244 case 5: /* CONTENT */
133245 sqlite3_free(zContent);
133246 zContent = zVal;
133247 zVal = 0;
133248 break;
133250 case 6: /* LANGUAGEID */
133251 assert( iOpt==6 );
133252 sqlite3_free(zLanguageid);
133253 zLanguageid = zVal;
133254 zVal = 0;
133255 break;
133257 case 7: /* NOTINDEXED */
133258 azNotindexed[nNotindexed++] = zVal;
133259 zVal = 0;
133260 break;
133263 sqlite3_free(zVal);
133267 /* Otherwise, the argument is a column name. */
133268 else {
133269 nString += (int)(strlen(z) + 1);
133270 aCol[nCol++] = z;
133274 /* If a content=xxx option was specified, the following:
133276 ** 1. Ignore any compress= and uncompress= options.
133278 ** 2. If no column names were specified as part of the CREATE VIRTUAL
133279 ** TABLE statement, use all columns from the content table.
133281 if( rc==SQLITE_OK && zContent ){
133282 sqlite3_free(zCompress);
133283 sqlite3_free(zUncompress);
133284 zCompress = 0;
133285 zUncompress = 0;
133286 if( nCol==0 ){
133287 sqlite3_free((void*)aCol);
133288 aCol = 0;
133289 rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
133291 /* If a languageid= option was specified, remove the language id
133292 ** column from the aCol[] array. */
133293 if( rc==SQLITE_OK && zLanguageid ){
133294 int j;
133295 for(j=0; j<nCol; j++){
133296 if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
133297 int k;
133298 for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
133299 nCol--;
133300 break;
133306 if( rc!=SQLITE_OK ) goto fts3_init_out;
133308 if( nCol==0 ){
133309 assert( nString==0 );
133310 aCol[0] = "content";
133311 nString = 8;
133312 nCol = 1;
133315 if( pTokenizer==0 ){
133316 rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
133317 if( rc!=SQLITE_OK ) goto fts3_init_out;
133319 assert( pTokenizer );
133321 rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
133322 if( rc==SQLITE_ERROR ){
133323 assert( zPrefix );
133324 *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
133326 if( rc!=SQLITE_OK ) goto fts3_init_out;
133328 /* Allocate and populate the Fts3Table structure. */
133329 nByte = sizeof(Fts3Table) + /* Fts3Table */
133330 nCol * sizeof(char *) + /* azColumn */
133331 nIndex * sizeof(struct Fts3Index) + /* aIndex */
133332 nCol * sizeof(u8) + /* abNotindexed */
133333 nName + /* zName */
133334 nDb + /* zDb */
133335 nString; /* Space for azColumn strings */
133336 p = (Fts3Table*)sqlite3_malloc(nByte);
133337 if( p==0 ){
133338 rc = SQLITE_NOMEM;
133339 goto fts3_init_out;
133341 memset(p, 0, nByte);
133342 p->db = db;
133343 p->nColumn = nCol;
133344 p->nPendingData = 0;
133345 p->azColumn = (char **)&p[1];
133346 p->pTokenizer = pTokenizer;
133347 p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
133348 p->bHasDocsize = (isFts4 && bNoDocsize==0);
133349 p->bHasStat = isFts4;
133350 p->bFts4 = isFts4;
133351 p->bDescIdx = bDescIdx;
133352 p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
133353 p->zContentTbl = zContent;
133354 p->zLanguageid = zLanguageid;
133355 zContent = 0;
133356 zLanguageid = 0;
133357 TESTONLY( p->inTransaction = -1 );
133358 TESTONLY( p->mxSavepoint = -1 );
133360 p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
133361 memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
133362 p->nIndex = nIndex;
133363 for(i=0; i<nIndex; i++){
133364 fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
133366 p->abNotindexed = (u8 *)&p->aIndex[nIndex];
133368 /* Fill in the zName and zDb fields of the vtab structure. */
133369 zCsr = (char *)&p->abNotindexed[nCol];
133370 p->zName = zCsr;
133371 memcpy(zCsr, argv[2], nName);
133372 zCsr += nName;
133373 p->zDb = zCsr;
133374 memcpy(zCsr, argv[1], nDb);
133375 zCsr += nDb;
133377 /* Fill in the azColumn array */
133378 for(iCol=0; iCol<nCol; iCol++){
133379 char *z;
133380 int n = 0;
133381 z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
133382 memcpy(zCsr, z, n);
133383 zCsr[n] = '\0';
133384 sqlite3Fts3Dequote(zCsr);
133385 p->azColumn[iCol] = zCsr;
133386 zCsr += n+1;
133387 assert( zCsr <= &((char *)p)[nByte] );
133390 /* Fill in the abNotindexed array */
133391 for(iCol=0; iCol<nCol; iCol++){
133392 int n = (int)strlen(p->azColumn[iCol]);
133393 for(i=0; i<nNotindexed; i++){
133394 char *zNot = azNotindexed[i];
133395 if( zNot && n==(int)strlen(zNot)
133396 && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
133398 p->abNotindexed[iCol] = 1;
133399 sqlite3_free(zNot);
133400 azNotindexed[i] = 0;
133404 for(i=0; i<nNotindexed; i++){
133405 if( azNotindexed[i] ){
133406 *pzErr = sqlite3_mprintf("no such column: %s", azNotindexed[i]);
133407 rc = SQLITE_ERROR;
133411 if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
133412 char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
133413 rc = SQLITE_ERROR;
133414 *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
133416 p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
133417 p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
133418 if( rc!=SQLITE_OK ) goto fts3_init_out;
133420 /* If this is an xCreate call, create the underlying tables in the
133421 ** database. TODO: For xConnect(), it could verify that said tables exist.
133423 if( isCreate ){
133424 rc = fts3CreateTables(p);
133427 /* Check to see if a legacy fts3 table has been "upgraded" by the
133428 ** addition of a %_stat table so that it can use incremental merge.
133430 if( !isFts4 && !isCreate ){
133431 p->bHasStat = 2;
133434 /* Figure out the page-size for the database. This is required in order to
133435 ** estimate the cost of loading large doclists from the database. */
133436 fts3DatabasePageSize(&rc, p);
133437 p->nNodeSize = p->nPgsz-35;
133439 /* Declare the table schema to SQLite. */
133440 fts3DeclareVtab(&rc, p);
133442 fts3_init_out:
133443 sqlite3_free(zPrefix);
133444 sqlite3_free(aIndex);
133445 sqlite3_free(zCompress);
133446 sqlite3_free(zUncompress);
133447 sqlite3_free(zContent);
133448 sqlite3_free(zLanguageid);
133449 for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
133450 sqlite3_free((void *)aCol);
133451 sqlite3_free((void *)azNotindexed);
133452 if( rc!=SQLITE_OK ){
133453 if( p ){
133454 fts3DisconnectMethod((sqlite3_vtab *)p);
133455 }else if( pTokenizer ){
133456 pTokenizer->pModule->xDestroy(pTokenizer);
133458 }else{
133459 assert( p->pSegments==0 );
133460 *ppVTab = &p->base;
133462 return rc;
133466 ** The xConnect() and xCreate() methods for the virtual table. All the
133467 ** work is done in function fts3InitVtab().
133469 static int fts3ConnectMethod(
133470 sqlite3 *db, /* Database connection */
133471 void *pAux, /* Pointer to tokenizer hash table */
133472 int argc, /* Number of elements in argv array */
133473 const char * const *argv, /* xCreate/xConnect argument array */
133474 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
133475 char **pzErr /* OUT: sqlite3_malloc'd error message */
133477 return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
133479 static int fts3CreateMethod(
133480 sqlite3 *db, /* Database connection */
133481 void *pAux, /* Pointer to tokenizer hash table */
133482 int argc, /* Number of elements in argv array */
133483 const char * const *argv, /* xCreate/xConnect argument array */
133484 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
133485 char **pzErr /* OUT: sqlite3_malloc'd error message */
133487 return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
133491 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
133492 ** extension is currently being used by a version of SQLite too old to
133493 ** support estimatedRows. In that case this function is a no-op.
133495 static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
133496 #if SQLITE_VERSION_NUMBER>=3008002
133497 if( sqlite3_libversion_number()>=3008002 ){
133498 pIdxInfo->estimatedRows = nRow;
133500 #endif
133504 ** Implementation of the xBestIndex method for FTS3 tables. There
133505 ** are three possible strategies, in order of preference:
133507 ** 1. Direct lookup by rowid or docid.
133508 ** 2. Full-text search using a MATCH operator on a non-docid column.
133509 ** 3. Linear scan of %_content table.
133511 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
133512 Fts3Table *p = (Fts3Table *)pVTab;
133513 int i; /* Iterator variable */
133514 int iCons = -1; /* Index of constraint to use */
133516 int iLangidCons = -1; /* Index of langid=x constraint, if present */
133517 int iDocidGe = -1; /* Index of docid>=x constraint, if present */
133518 int iDocidLe = -1; /* Index of docid<=x constraint, if present */
133519 int iIdx;
133521 /* By default use a full table scan. This is an expensive option,
133522 ** so search through the constraints to see if a more efficient
133523 ** strategy is possible.
133525 pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
133526 pInfo->estimatedCost = 5000000;
133527 for(i=0; i<pInfo->nConstraint; i++){
133528 int bDocid; /* True if this constraint is on docid */
133529 struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
133530 if( pCons->usable==0 ){
133531 if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
133532 /* There exists an unusable MATCH constraint. This means that if
133533 ** the planner does elect to use the results of this call as part
133534 ** of the overall query plan the user will see an "unable to use
133535 ** function MATCH in the requested context" error. To discourage
133536 ** this, return a very high cost here. */
133537 pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
133538 pInfo->estimatedCost = 1e50;
133539 fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
133540 return SQLITE_OK;
133542 continue;
133545 bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
133547 /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
133548 if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
133549 pInfo->idxNum = FTS3_DOCID_SEARCH;
133550 pInfo->estimatedCost = 1.0;
133551 iCons = i;
133554 /* A MATCH constraint. Use a full-text search.
133556 ** If there is more than one MATCH constraint available, use the first
133557 ** one encountered. If there is both a MATCH constraint and a direct
133558 ** rowid/docid lookup, prefer the MATCH strategy. This is done even
133559 ** though the rowid/docid lookup is faster than a MATCH query, selecting
133560 ** it would lead to an "unable to use function MATCH in the requested
133561 ** context" error.
133563 if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
133564 && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
133566 pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
133567 pInfo->estimatedCost = 2.0;
133568 iCons = i;
133571 /* Equality constraint on the langid column */
133572 if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
133573 && pCons->iColumn==p->nColumn + 2
133575 iLangidCons = i;
133578 if( bDocid ){
133579 switch( pCons->op ){
133580 case SQLITE_INDEX_CONSTRAINT_GE:
133581 case SQLITE_INDEX_CONSTRAINT_GT:
133582 iDocidGe = i;
133583 break;
133585 case SQLITE_INDEX_CONSTRAINT_LE:
133586 case SQLITE_INDEX_CONSTRAINT_LT:
133587 iDocidLe = i;
133588 break;
133593 iIdx = 1;
133594 if( iCons>=0 ){
133595 pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
133596 pInfo->aConstraintUsage[iCons].omit = 1;
133598 if( iLangidCons>=0 ){
133599 pInfo->idxNum |= FTS3_HAVE_LANGID;
133600 pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
133602 if( iDocidGe>=0 ){
133603 pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
133604 pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
133606 if( iDocidLe>=0 ){
133607 pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
133608 pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
133611 /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
133612 ** docid) order. Both ascending and descending are possible.
133614 if( pInfo->nOrderBy==1 ){
133615 struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
133616 if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
133617 if( pOrder->desc ){
133618 pInfo->idxStr = "DESC";
133619 }else{
133620 pInfo->idxStr = "ASC";
133622 pInfo->orderByConsumed = 1;
133626 assert( p->pSegments==0 );
133627 return SQLITE_OK;
133631 ** Implementation of xOpen method.
133633 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
133634 sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
133636 UNUSED_PARAMETER(pVTab);
133638 /* Allocate a buffer large enough for an Fts3Cursor structure. If the
133639 ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
133640 ** if the allocation fails, return SQLITE_NOMEM.
133642 *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
133643 if( !pCsr ){
133644 return SQLITE_NOMEM;
133646 memset(pCsr, 0, sizeof(Fts3Cursor));
133647 return SQLITE_OK;
133651 ** Close the cursor. For additional information see the documentation
133652 ** on the xClose method of the virtual table interface.
133654 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
133655 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
133656 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
133657 sqlite3_finalize(pCsr->pStmt);
133658 sqlite3Fts3ExprFree(pCsr->pExpr);
133659 sqlite3Fts3FreeDeferredTokens(pCsr);
133660 sqlite3_free(pCsr->aDoclist);
133661 sqlite3_free(pCsr->aMatchinfo);
133662 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
133663 sqlite3_free(pCsr);
133664 return SQLITE_OK;
133668 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
133669 ** compose and prepare an SQL statement of the form:
133671 ** "SELECT <columns> FROM %_content WHERE rowid = ?"
133673 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
133674 ** it. If an error occurs, return an SQLite error code.
133676 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
133678 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
133679 int rc = SQLITE_OK;
133680 if( pCsr->pStmt==0 ){
133681 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
133682 char *zSql;
133683 zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
133684 if( !zSql ) return SQLITE_NOMEM;
133685 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
133686 sqlite3_free(zSql);
133688 *ppStmt = pCsr->pStmt;
133689 return rc;
133693 ** Position the pCsr->pStmt statement so that it is on the row
133694 ** of the %_content table that contains the last match. Return
133695 ** SQLITE_OK on success.
133697 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
133698 int rc = SQLITE_OK;
133699 if( pCsr->isRequireSeek ){
133700 sqlite3_stmt *pStmt = 0;
133702 rc = fts3CursorSeekStmt(pCsr, &pStmt);
133703 if( rc==SQLITE_OK ){
133704 sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
133705 pCsr->isRequireSeek = 0;
133706 if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
133707 return SQLITE_OK;
133708 }else{
133709 rc = sqlite3_reset(pCsr->pStmt);
133710 if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
133711 /* If no row was found and no error has occurred, then the %_content
133712 ** table is missing a row that is present in the full-text index.
133713 ** The data structures are corrupt. */
133714 rc = FTS_CORRUPT_VTAB;
133715 pCsr->isEof = 1;
133721 if( rc!=SQLITE_OK && pContext ){
133722 sqlite3_result_error_code(pContext, rc);
133724 return rc;
133728 ** This function is used to process a single interior node when searching
133729 ** a b-tree for a term or term prefix. The node data is passed to this
133730 ** function via the zNode/nNode parameters. The term to search for is
133731 ** passed in zTerm/nTerm.
133733 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
133734 ** of the child node that heads the sub-tree that may contain the term.
133736 ** If piLast is not NULL, then *piLast is set to the right-most child node
133737 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
133738 ** a prefix.
133740 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
133742 static int fts3ScanInteriorNode(
133743 const char *zTerm, /* Term to select leaves for */
133744 int nTerm, /* Size of term zTerm in bytes */
133745 const char *zNode, /* Buffer containing segment interior node */
133746 int nNode, /* Size of buffer at zNode */
133747 sqlite3_int64 *piFirst, /* OUT: Selected child node */
133748 sqlite3_int64 *piLast /* OUT: Selected child node */
133750 int rc = SQLITE_OK; /* Return code */
133751 const char *zCsr = zNode; /* Cursor to iterate through node */
133752 const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
133753 char *zBuffer = 0; /* Buffer to load terms into */
133754 int nAlloc = 0; /* Size of allocated buffer */
133755 int isFirstTerm = 1; /* True when processing first term on page */
133756 sqlite3_int64 iChild; /* Block id of child node to descend to */
133758 /* Skip over the 'height' varint that occurs at the start of every
133759 ** interior node. Then load the blockid of the left-child of the b-tree
133760 ** node into variable iChild.
133762 ** Even if the data structure on disk is corrupted, this (reading two
133763 ** varints from the buffer) does not risk an overread. If zNode is a
133764 ** root node, then the buffer comes from a SELECT statement. SQLite does
133765 ** not make this guarantee explicitly, but in practice there are always
133766 ** either more than 20 bytes of allocated space following the nNode bytes of
133767 ** contents, or two zero bytes. Or, if the node is read from the %_segments
133768 ** table, then there are always 20 bytes of zeroed padding following the
133769 ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
133771 zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
133772 zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
133773 if( zCsr>zEnd ){
133774 return FTS_CORRUPT_VTAB;
133777 while( zCsr<zEnd && (piFirst || piLast) ){
133778 int cmp; /* memcmp() result */
133779 int nSuffix; /* Size of term suffix */
133780 int nPrefix = 0; /* Size of term prefix */
133781 int nBuffer; /* Total term size */
133783 /* Load the next term on the node into zBuffer. Use realloc() to expand
133784 ** the size of zBuffer if required. */
133785 if( !isFirstTerm ){
133786 zCsr += fts3GetVarint32(zCsr, &nPrefix);
133788 isFirstTerm = 0;
133789 zCsr += fts3GetVarint32(zCsr, &nSuffix);
133791 /* NOTE(shess): Previous code checked for negative nPrefix and
133792 ** nSuffix and suffix overrunning zEnd. Additionally corrupt if
133793 ** the prefix is longer than the previous term, or if the suffix
133794 ** causes overflow.
133796 if( nPrefix<0 || nSuffix<0 /* || nPrefix>nBuffer */
133797 || &zCsr[nSuffix]<zCsr || &zCsr[nSuffix]>zEnd ){
133798 rc = SQLITE_CORRUPT;
133799 goto finish_scan;
133801 if( nPrefix+nSuffix>nAlloc ){
133802 char *zNew;
133803 nAlloc = (nPrefix+nSuffix) * 2;
133804 zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
133805 if( !zNew ){
133806 rc = SQLITE_NOMEM;
133807 goto finish_scan;
133809 zBuffer = zNew;
133811 assert( zBuffer );
133812 memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
133813 nBuffer = nPrefix + nSuffix;
133814 zCsr += nSuffix;
133816 /* Compare the term we are searching for with the term just loaded from
133817 ** the interior node. If the specified term is greater than or equal
133818 ** to the term from the interior node, then all terms on the sub-tree
133819 ** headed by node iChild are smaller than zTerm. No need to search
133820 ** iChild.
133822 ** If the interior node term is larger than the specified term, then
133823 ** the tree headed by iChild may contain the specified term.
133825 cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
133826 if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
133827 *piFirst = iChild;
133828 piFirst = 0;
133831 if( piLast && cmp<0 ){
133832 *piLast = iChild;
133833 piLast = 0;
133836 iChild++;
133839 if( piFirst ) *piFirst = iChild;
133840 if( piLast ) *piLast = iChild;
133842 finish_scan:
133843 sqlite3_free(zBuffer);
133844 return rc;
133849 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
133850 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
133851 ** contains a term. This function searches the sub-tree headed by the zNode
133852 ** node for the range of leaf nodes that may contain the specified term
133853 ** or terms for which the specified term is a prefix.
133855 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
133856 ** left-most leaf node in the tree that may contain the specified term.
133857 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
133858 ** right-most leaf node that may contain a term for which the specified
133859 ** term is a prefix.
133861 ** It is possible that the range of returned leaf nodes does not contain
133862 ** the specified term or any terms for which it is a prefix. However, if the
133863 ** segment does contain any such terms, they are stored within the identified
133864 ** range. Because this function only inspects interior segment nodes (and
133865 ** never loads leaf nodes into memory), it is not possible to be sure.
133867 ** If an error occurs, an error code other than SQLITE_OK is returned.
133869 static int fts3SelectLeaf(
133870 Fts3Table *p, /* Virtual table handle */
133871 const char *zTerm, /* Term to select leaves for */
133872 int nTerm, /* Size of term zTerm in bytes */
133873 const char *zNode, /* Buffer containing segment interior node */
133874 int nNode, /* Size of buffer at zNode */
133875 sqlite3_int64 *piLeaf, /* Selected leaf node */
133876 sqlite3_int64 *piLeaf2 /* Selected leaf node */
133878 int rc; /* Return code */
133879 int iHeight; /* Height of this node in tree */
133881 assert( piLeaf || piLeaf2 );
133883 fts3GetVarint32(zNode, &iHeight);
133884 rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
133885 assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
133887 if( rc==SQLITE_OK && iHeight>1 ){
133888 char *zBlob = 0; /* Blob read from %_segments table */
133889 int nBlob; /* Size of zBlob in bytes */
133891 if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
133892 rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
133893 if( rc==SQLITE_OK ){
133894 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
133896 sqlite3_free(zBlob);
133897 piLeaf = 0;
133898 zBlob = 0;
133901 if( rc==SQLITE_OK ){
133902 rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
133904 if( rc==SQLITE_OK ){
133905 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
133907 sqlite3_free(zBlob);
133910 return rc;
133914 ** This function is used to create delta-encoded serialized lists of FTS3
133915 ** varints. Each call to this function appends a single varint to a list.
133917 static void fts3PutDeltaVarint(
133918 char **pp, /* IN/OUT: Output pointer */
133919 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
133920 sqlite3_int64 iVal /* Write this value to the list */
133922 assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
133923 *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
133924 *piPrev = iVal;
133928 ** When this function is called, *ppPoslist is assumed to point to the
133929 ** start of a position-list. After it returns, *ppPoslist points to the
133930 ** first byte after the position-list.
133932 ** A position list is list of positions (delta encoded) and columns for
133933 ** a single document record of a doclist. So, in other words, this
133934 ** routine advances *ppPoslist so that it points to the next docid in
133935 ** the doclist, or to the first byte past the end of the doclist.
133937 ** If pp is not NULL, then the contents of the position list are copied
133938 ** to *pp. *pp is set to point to the first byte past the last byte copied
133939 ** before this function returns.
133941 static void fts3PoslistCopy(char **pp, char **ppPoslist){
133942 char *pEnd = *ppPoslist;
133943 char c = 0;
133945 /* The end of a position list is marked by a zero encoded as an FTS3
133946 ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
133947 ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
133948 ** of some other, multi-byte, value.
133950 ** The following while-loop moves pEnd to point to the first byte that is not
133951 ** immediately preceded by a byte with the 0x80 bit set. Then increments
133952 ** pEnd once more so that it points to the byte immediately following the
133953 ** last byte in the position-list.
133955 while( *pEnd | c ){
133956 c = *pEnd++ & 0x80;
133957 testcase( c!=0 && (*pEnd)==0 );
133959 pEnd++; /* Advance past the POS_END terminator byte */
133961 if( pp ){
133962 int n = (int)(pEnd - *ppPoslist);
133963 char *p = *pp;
133964 memcpy(p, *ppPoslist, n);
133965 p += n;
133966 *pp = p;
133968 *ppPoslist = pEnd;
133972 ** When this function is called, *ppPoslist is assumed to point to the
133973 ** start of a column-list. After it returns, *ppPoslist points to the
133974 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
133976 ** A column-list is list of delta-encoded positions for a single column
133977 ** within a single document within a doclist.
133979 ** The column-list is terminated either by a POS_COLUMN varint (1) or
133980 ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
133981 ** the POS_COLUMN or POS_END that terminates the column-list.
133983 ** If pp is not NULL, then the contents of the column-list are copied
133984 ** to *pp. *pp is set to point to the first byte past the last byte copied
133985 ** before this function returns. The POS_COLUMN or POS_END terminator
133986 ** is not copied into *pp.
133988 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
133989 char *pEnd = *ppPoslist;
133990 char c = 0;
133992 /* A column-list is terminated by either a 0x01 or 0x00 byte that is
133993 ** not part of a multi-byte varint.
133995 while( 0xFE & (*pEnd | c) ){
133996 c = *pEnd++ & 0x80;
133997 testcase( c!=0 && ((*pEnd)&0xfe)==0 );
133999 if( pp ){
134000 int n = (int)(pEnd - *ppPoslist);
134001 char *p = *pp;
134002 memcpy(p, *ppPoslist, n);
134003 p += n;
134004 *pp = p;
134006 *ppPoslist = pEnd;
134010 ** Value used to signify the end of an position-list. This is safe because
134011 ** it is not possible to have a document with 2^31 terms.
134013 #define POSITION_LIST_END 0x7fffffff
134016 ** This function is used to help parse position-lists. When this function is
134017 ** called, *pp may point to the start of the next varint in the position-list
134018 ** being parsed, or it may point to 1 byte past the end of the position-list
134019 ** (in which case **pp will be a terminator bytes POS_END (0) or
134020 ** (1)).
134022 ** If *pp points past the end of the current position-list, set *pi to
134023 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
134024 ** increment the current value of *pi by the value read, and set *pp to
134025 ** point to the next value before returning.
134027 ** Before calling this routine *pi must be initialized to the value of
134028 ** the previous position, or zero if we are reading the first position
134029 ** in the position-list. Because positions are delta-encoded, the value
134030 ** of the previous position is needed in order to compute the value of
134031 ** the next position.
134033 static void fts3ReadNextPos(
134034 char **pp, /* IN/OUT: Pointer into position-list buffer */
134035 sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
134037 if( (**pp)&0xFE ){
134038 fts3GetDeltaVarint(pp, pi);
134039 *pi -= 2;
134040 }else{
134041 *pi = POSITION_LIST_END;
134046 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
134047 ** the value of iCol encoded as a varint to *pp. This will start a new
134048 ** column list.
134050 ** Set *pp to point to the byte just after the last byte written before
134051 ** returning (do not modify it if iCol==0). Return the total number of bytes
134052 ** written (0 if iCol==0).
134054 static int fts3PutColNumber(char **pp, int iCol){
134055 int n = 0; /* Number of bytes written */
134056 if( iCol ){
134057 char *p = *pp; /* Output pointer */
134058 n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
134059 *p = 0x01;
134060 *pp = &p[n];
134062 return n;
134066 ** Compute the union of two position lists. The output written
134067 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
134068 ** order and with any duplicates removed. All pointers are
134069 ** updated appropriately. The caller is responsible for insuring
134070 ** that there is enough space in *pp to hold the complete output.
134072 static void fts3PoslistMerge(
134073 char **pp, /* Output buffer */
134074 char **pp1, /* Left input list */
134075 char **pp2 /* Right input list */
134077 char *p = *pp;
134078 char *p1 = *pp1;
134079 char *p2 = *pp2;
134081 while( *p1 || *p2 ){
134082 int iCol1; /* The current column index in pp1 */
134083 int iCol2; /* The current column index in pp2 */
134085 if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
134086 else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
134087 else iCol1 = 0;
134089 if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
134090 else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
134091 else iCol2 = 0;
134093 if( iCol1==iCol2 ){
134094 sqlite3_int64 i1 = 0; /* Last position from pp1 */
134095 sqlite3_int64 i2 = 0; /* Last position from pp2 */
134096 sqlite3_int64 iPrev = 0;
134097 int n = fts3PutColNumber(&p, iCol1);
134098 p1 += n;
134099 p2 += n;
134101 /* At this point, both p1 and p2 point to the start of column-lists
134102 ** for the same column (the column with index iCol1 and iCol2).
134103 ** A column-list is a list of non-negative delta-encoded varints, each
134104 ** incremented by 2 before being stored. Each list is terminated by a
134105 ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
134106 ** and writes the results to buffer p. p is left pointing to the byte
134107 ** after the list written. No terminator (POS_END or POS_COLUMN) is
134108 ** written to the output.
134110 fts3GetDeltaVarint(&p1, &i1);
134111 fts3GetDeltaVarint(&p2, &i2);
134113 fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
134114 iPrev -= 2;
134115 if( i1==i2 ){
134116 fts3ReadNextPos(&p1, &i1);
134117 fts3ReadNextPos(&p2, &i2);
134118 }else if( i1<i2 ){
134119 fts3ReadNextPos(&p1, &i1);
134120 }else{
134121 fts3ReadNextPos(&p2, &i2);
134123 }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
134124 }else if( iCol1<iCol2 ){
134125 p1 += fts3PutColNumber(&p, iCol1);
134126 fts3ColumnlistCopy(&p, &p1);
134127 }else{
134128 p2 += fts3PutColNumber(&p, iCol2);
134129 fts3ColumnlistCopy(&p, &p2);
134133 *p++ = POS_END;
134134 *pp = p;
134135 *pp1 = p1 + 1;
134136 *pp2 = p2 + 1;
134140 ** This function is used to merge two position lists into one. When it is
134141 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
134142 ** the part of a doclist that follows each document id. For example, if a row
134143 ** contains:
134145 ** 'a b c'|'x y z'|'a b b a'
134147 ** Then the position list for this row for token 'b' would consist of:
134149 ** 0x02 0x01 0x02 0x03 0x03 0x00
134151 ** When this function returns, both *pp1 and *pp2 are left pointing to the
134152 ** byte following the 0x00 terminator of their respective position lists.
134154 ** If isSaveLeft is 0, an entry is added to the output position list for
134155 ** each position in *pp2 for which there exists one or more positions in
134156 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
134157 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
134158 ** slots before it.
134160 ** e.g. nToken==1 searches for adjacent positions.
134162 static int fts3PoslistPhraseMerge(
134163 char **pp, /* IN/OUT: Preallocated output buffer */
134164 int nToken, /* Maximum difference in token positions */
134165 int isSaveLeft, /* Save the left position */
134166 int isExact, /* If *pp1 is exactly nTokens before *pp2 */
134167 char **pp1, /* IN/OUT: Left input list */
134168 char **pp2 /* IN/OUT: Right input list */
134170 char *p = *pp;
134171 char *p1 = *pp1;
134172 char *p2 = *pp2;
134173 int iCol1 = 0;
134174 int iCol2 = 0;
134176 /* Never set both isSaveLeft and isExact for the same invocation. */
134177 assert( isSaveLeft==0 || isExact==0 );
134179 assert( p!=0 && *p1!=0 && *p2!=0 );
134180 if( *p1==POS_COLUMN ){
134181 p1++;
134182 p1 += fts3GetVarint32(p1, &iCol1);
134184 if( *p2==POS_COLUMN ){
134185 p2++;
134186 p2 += fts3GetVarint32(p2, &iCol2);
134189 while( 1 ){
134190 if( iCol1==iCol2 ){
134191 char *pSave = p;
134192 sqlite3_int64 iPrev = 0;
134193 sqlite3_int64 iPos1 = 0;
134194 sqlite3_int64 iPos2 = 0;
134196 if( iCol1 ){
134197 *p++ = POS_COLUMN;
134198 p += sqlite3Fts3PutVarint(p, iCol1);
134201 assert( *p1!=POS_END && *p1!=POS_COLUMN );
134202 assert( *p2!=POS_END && *p2!=POS_COLUMN );
134203 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
134204 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
134206 while( 1 ){
134207 if( iPos2==iPos1+nToken
134208 || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
134210 sqlite3_int64 iSave;
134211 iSave = isSaveLeft ? iPos1 : iPos2;
134212 fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
134213 pSave = 0;
134214 assert( p );
134216 if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
134217 if( (*p2&0xFE)==0 ) break;
134218 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
134219 }else{
134220 if( (*p1&0xFE)==0 ) break;
134221 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
134225 if( pSave ){
134226 assert( pp && p );
134227 p = pSave;
134230 fts3ColumnlistCopy(0, &p1);
134231 fts3ColumnlistCopy(0, &p2);
134232 assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
134233 if( 0==*p1 || 0==*p2 ) break;
134235 p1++;
134236 p1 += fts3GetVarint32(p1, &iCol1);
134237 p2++;
134238 p2 += fts3GetVarint32(p2, &iCol2);
134241 /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
134242 ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
134243 ** end of the position list, or the 0x01 that precedes the next
134244 ** column-number in the position list.
134246 else if( iCol1<iCol2 ){
134247 fts3ColumnlistCopy(0, &p1);
134248 if( 0==*p1 ) break;
134249 p1++;
134250 p1 += fts3GetVarint32(p1, &iCol1);
134251 }else{
134252 fts3ColumnlistCopy(0, &p2);
134253 if( 0==*p2 ) break;
134254 p2++;
134255 p2 += fts3GetVarint32(p2, &iCol2);
134259 fts3PoslistCopy(0, &p2);
134260 fts3PoslistCopy(0, &p1);
134261 *pp1 = p1;
134262 *pp2 = p2;
134263 if( *pp==p ){
134264 return 0;
134266 *p++ = 0x00;
134267 *pp = p;
134268 return 1;
134272 ** Merge two position-lists as required by the NEAR operator. The argument
134273 ** position lists correspond to the left and right phrases of an expression
134274 ** like:
134276 ** "phrase 1" NEAR "phrase number 2"
134278 ** Position list *pp1 corresponds to the left-hand side of the NEAR
134279 ** expression and *pp2 to the right. As usual, the indexes in the position
134280 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
134281 ** in the example above).
134283 ** The output position list - written to *pp - is a copy of *pp2 with those
134284 ** entries that are not sufficiently NEAR entries in *pp1 removed.
134286 static int fts3PoslistNearMerge(
134287 char **pp, /* Output buffer */
134288 char *aTmp, /* Temporary buffer space */
134289 int nRight, /* Maximum difference in token positions */
134290 int nLeft, /* Maximum difference in token positions */
134291 char **pp1, /* IN/OUT: Left input list */
134292 char **pp2 /* IN/OUT: Right input list */
134294 char *p1 = *pp1;
134295 char *p2 = *pp2;
134297 char *pTmp1 = aTmp;
134298 char *pTmp2;
134299 char *aTmp2;
134300 int res = 1;
134302 fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
134303 aTmp2 = pTmp2 = pTmp1;
134304 *pp1 = p1;
134305 *pp2 = p2;
134306 fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
134307 if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
134308 fts3PoslistMerge(pp, &aTmp, &aTmp2);
134309 }else if( pTmp1!=aTmp ){
134310 fts3PoslistCopy(pp, &aTmp);
134311 }else if( pTmp2!=aTmp2 ){
134312 fts3PoslistCopy(pp, &aTmp2);
134313 }else{
134314 res = 0;
134317 return res;
134321 ** An instance of this function is used to merge together the (potentially
134322 ** large number of) doclists for each term that matches a prefix query.
134323 ** See function fts3TermSelectMerge() for details.
134325 typedef struct TermSelect TermSelect;
134326 struct TermSelect {
134327 char *aaOutput[16]; /* Malloc'd output buffers */
134328 int anOutput[16]; /* Size each output buffer in bytes */
134332 ** This function is used to read a single varint from a buffer. Parameter
134333 ** pEnd points 1 byte past the end of the buffer. When this function is
134334 ** called, if *pp points to pEnd or greater, then the end of the buffer
134335 ** has been reached. In this case *pp is set to 0 and the function returns.
134337 ** If *pp does not point to or past pEnd, then a single varint is read
134338 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
134340 ** If bDescIdx is false, the value read is added to *pVal before returning.
134341 ** If it is true, the value read is subtracted from *pVal before this
134342 ** function returns.
134344 static void fts3GetDeltaVarint3(
134345 char **pp, /* IN/OUT: Point to read varint from */
134346 char *pEnd, /* End of buffer */
134347 int bDescIdx, /* True if docids are descending */
134348 sqlite3_int64 *pVal /* IN/OUT: Integer value */
134350 if( *pp>=pEnd ){
134351 *pp = 0;
134352 }else{
134353 sqlite3_int64 iVal;
134354 *pp += sqlite3Fts3GetVarint(*pp, &iVal);
134355 if( bDescIdx ){
134356 *pVal -= iVal;
134357 }else{
134358 *pVal += iVal;
134364 ** This function is used to write a single varint to a buffer. The varint
134365 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
134366 ** end of the value written.
134368 ** If *pbFirst is zero when this function is called, the value written to
134369 ** the buffer is that of parameter iVal.
134371 ** If *pbFirst is non-zero when this function is called, then the value
134372 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
134373 ** (if bDescIdx is non-zero).
134375 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
134376 ** to the value of parameter iVal.
134378 static void fts3PutDeltaVarint3(
134379 char **pp, /* IN/OUT: Output pointer */
134380 int bDescIdx, /* True for descending docids */
134381 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
134382 int *pbFirst, /* IN/OUT: True after first int written */
134383 sqlite3_int64 iVal /* Write this value to the list */
134385 sqlite3_int64 iWrite;
134386 if( bDescIdx==0 || *pbFirst==0 ){
134387 iWrite = iVal - *piPrev;
134388 }else{
134389 iWrite = *piPrev - iVal;
134391 assert( *pbFirst || *piPrev==0 );
134392 assert( *pbFirst==0 || iWrite>0 );
134393 *pp += sqlite3Fts3PutVarint(*pp, iWrite);
134394 *piPrev = iVal;
134395 *pbFirst = 1;
134400 ** This macro is used by various functions that merge doclists. The two
134401 ** arguments are 64-bit docid values. If the value of the stack variable
134402 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
134403 ** Otherwise, (i2-i1).
134405 ** Using this makes it easier to write code that can merge doclists that are
134406 ** sorted in either ascending or descending order.
134408 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
134411 ** This function does an "OR" merge of two doclists (output contains all
134412 ** positions contained in either argument doclist). If the docids in the
134413 ** input doclists are sorted in ascending order, parameter bDescDoclist
134414 ** should be false. If they are sorted in ascending order, it should be
134415 ** passed a non-zero value.
134417 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
134418 ** containing the output doclist and SQLITE_OK is returned. In this case
134419 ** *pnOut is set to the number of bytes in the output doclist.
134421 ** If an error occurs, an SQLite error code is returned. The output values
134422 ** are undefined in this case.
134424 static int fts3DoclistOrMerge(
134425 int bDescDoclist, /* True if arguments are desc */
134426 char *a1, int n1, /* First doclist */
134427 char *a2, int n2, /* Second doclist */
134428 char **paOut, int *pnOut /* OUT: Malloc'd doclist */
134430 sqlite3_int64 i1 = 0;
134431 sqlite3_int64 i2 = 0;
134432 sqlite3_int64 iPrev = 0;
134433 char *pEnd1 = &a1[n1];
134434 char *pEnd2 = &a2[n2];
134435 char *p1 = a1;
134436 char *p2 = a2;
134437 char *p;
134438 char *aOut;
134439 int bFirstOut = 0;
134441 *paOut = 0;
134442 *pnOut = 0;
134444 /* Allocate space for the output. Both the input and output doclists
134445 ** are delta encoded. If they are in ascending order (bDescDoclist==0),
134446 ** then the first docid in each list is simply encoded as a varint. For
134447 ** each subsequent docid, the varint stored is the difference between the
134448 ** current and previous docid (a positive number - since the list is in
134449 ** ascending order).
134451 ** The first docid written to the output is therefore encoded using the
134452 ** same number of bytes as it is in whichever of the input lists it is
134453 ** read from. And each subsequent docid read from the same input list
134454 ** consumes either the same or less bytes as it did in the input (since
134455 ** the difference between it and the previous value in the output must
134456 ** be a positive value less than or equal to the delta value read from
134457 ** the input list). The same argument applies to all but the first docid
134458 ** read from the 'other' list. And to the contents of all position lists
134459 ** that will be copied and merged from the input to the output.
134461 ** However, if the first docid copied to the output is a negative number,
134462 ** then the encoding of the first docid from the 'other' input list may
134463 ** be larger in the output than it was in the input (since the delta value
134464 ** may be a larger positive integer than the actual docid).
134466 ** The space required to store the output is therefore the sum of the
134467 ** sizes of the two inputs, plus enough space for exactly one of the input
134468 ** docids to grow.
134470 ** A symetric argument may be made if the doclists are in descending
134471 ** order.
134473 aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
134474 if( !aOut ) return SQLITE_NOMEM;
134476 p = aOut;
134477 fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
134478 fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
134479 while( p1 || p2 ){
134480 sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
134482 if( p2 && p1 && iDiff==0 ){
134483 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
134484 fts3PoslistMerge(&p, &p1, &p2);
134485 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
134486 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
134487 }else if( !p2 || (p1 && iDiff<0) ){
134488 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
134489 fts3PoslistCopy(&p, &p1);
134490 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
134491 }else{
134492 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
134493 fts3PoslistCopy(&p, &p2);
134494 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
134498 *paOut = aOut;
134499 *pnOut = (int)(p-aOut);
134500 assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
134501 return SQLITE_OK;
134505 ** This function does a "phrase" merge of two doclists. In a phrase merge,
134506 ** the output contains a copy of each position from the right-hand input
134507 ** doclist for which there is a position in the left-hand input doclist
134508 ** exactly nDist tokens before it.
134510 ** If the docids in the input doclists are sorted in ascending order,
134511 ** parameter bDescDoclist should be false. If they are sorted in ascending
134512 ** order, it should be passed a non-zero value.
134514 ** The right-hand input doclist is overwritten by this function.
134516 static void fts3DoclistPhraseMerge(
134517 int bDescDoclist, /* True if arguments are desc */
134518 int nDist, /* Distance from left to right (1=adjacent) */
134519 char *aLeft, int nLeft, /* Left doclist */
134520 char *aRight, int *pnRight /* IN/OUT: Right/output doclist */
134522 sqlite3_int64 i1 = 0;
134523 sqlite3_int64 i2 = 0;
134524 sqlite3_int64 iPrev = 0;
134525 char *pEnd1 = &aLeft[nLeft];
134526 char *pEnd2 = &aRight[*pnRight];
134527 char *p1 = aLeft;
134528 char *p2 = aRight;
134529 char *p;
134530 int bFirstOut = 0;
134531 char *aOut = aRight;
134533 assert( nDist>0 );
134535 p = aOut;
134536 fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
134537 fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
134539 while( p1 && p2 ){
134540 sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
134541 if( iDiff==0 ){
134542 char *pSave = p;
134543 sqlite3_int64 iPrevSave = iPrev;
134544 int bFirstOutSave = bFirstOut;
134546 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
134547 if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
134548 p = pSave;
134549 iPrev = iPrevSave;
134550 bFirstOut = bFirstOutSave;
134552 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
134553 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
134554 }else if( iDiff<0 ){
134555 fts3PoslistCopy(0, &p1);
134556 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
134557 }else{
134558 fts3PoslistCopy(0, &p2);
134559 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
134563 *pnRight = (int)(p - aOut);
134567 ** Argument pList points to a position list nList bytes in size. This
134568 ** function checks to see if the position list contains any entries for
134569 ** a token in position 0 (of any column). If so, it writes argument iDelta
134570 ** to the output buffer pOut, followed by a position list consisting only
134571 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
134572 ** The value returned is the number of bytes written to pOut (if any).
134574 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
134575 sqlite3_int64 iDelta, /* Varint that may be written to pOut */
134576 char *pList, /* Position list (no 0x00 term) */
134577 int nList, /* Size of pList in bytes */
134578 char *pOut /* Write output here */
134580 int nOut = 0;
134581 int bWritten = 0; /* True once iDelta has been written */
134582 char *p = pList;
134583 char *pEnd = &pList[nList];
134585 if( *p!=0x01 ){
134586 if( *p==0x02 ){
134587 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
134588 pOut[nOut++] = 0x02;
134589 bWritten = 1;
134591 fts3ColumnlistCopy(0, &p);
134594 while( p<pEnd && *p==0x01 ){
134595 sqlite3_int64 iCol;
134597 p += sqlite3Fts3GetVarint(p, &iCol);
134598 if( *p==0x02 ){
134599 if( bWritten==0 ){
134600 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
134601 bWritten = 1;
134603 pOut[nOut++] = 0x01;
134604 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
134605 pOut[nOut++] = 0x02;
134607 fts3ColumnlistCopy(0, &p);
134609 if( bWritten ){
134610 pOut[nOut++] = 0x00;
134613 return nOut;
134618 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
134619 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
134620 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
134622 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
134623 ** the responsibility of the caller to free any doclists left in the
134624 ** TermSelect.aaOutput[] array.
134626 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
134627 char *aOut = 0;
134628 int nOut = 0;
134629 int i;
134631 /* Loop through the doclists in the aaOutput[] array. Merge them all
134632 ** into a single doclist.
134634 for(i=0; i<SizeofArray(pTS->aaOutput); i++){
134635 if( pTS->aaOutput[i] ){
134636 if( !aOut ){
134637 aOut = pTS->aaOutput[i];
134638 nOut = pTS->anOutput[i];
134639 pTS->aaOutput[i] = 0;
134640 }else{
134641 int nNew;
134642 char *aNew;
134644 int rc = fts3DoclistOrMerge(p->bDescIdx,
134645 pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
134647 if( rc!=SQLITE_OK ){
134648 sqlite3_free(aOut);
134649 return rc;
134652 sqlite3_free(pTS->aaOutput[i]);
134653 sqlite3_free(aOut);
134654 pTS->aaOutput[i] = 0;
134655 aOut = aNew;
134656 nOut = nNew;
134661 pTS->aaOutput[0] = aOut;
134662 pTS->anOutput[0] = nOut;
134663 return SQLITE_OK;
134667 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
134668 ** as the first argument. The merge is an "OR" merge (see function
134669 ** fts3DoclistOrMerge() for details).
134671 ** This function is called with the doclist for each term that matches
134672 ** a queried prefix. It merges all these doclists into one, the doclist
134673 ** for the specified prefix. Since there can be a very large number of
134674 ** doclists to merge, the merging is done pair-wise using the TermSelect
134675 ** object.
134677 ** This function returns SQLITE_OK if the merge is successful, or an
134678 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
134680 static int fts3TermSelectMerge(
134681 Fts3Table *p, /* FTS table handle */
134682 TermSelect *pTS, /* TermSelect object to merge into */
134683 char *aDoclist, /* Pointer to doclist */
134684 int nDoclist /* Size of aDoclist in bytes */
134686 if( pTS->aaOutput[0]==0 ){
134687 /* If this is the first term selected, copy the doclist to the output
134688 ** buffer using memcpy(). */
134689 pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
134690 pTS->anOutput[0] = nDoclist;
134691 if( pTS->aaOutput[0] ){
134692 memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
134693 }else{
134694 return SQLITE_NOMEM;
134696 }else{
134697 char *aMerge = aDoclist;
134698 int nMerge = nDoclist;
134699 int iOut;
134701 for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
134702 if( pTS->aaOutput[iOut]==0 ){
134703 assert( iOut>0 );
134704 pTS->aaOutput[iOut] = aMerge;
134705 pTS->anOutput[iOut] = nMerge;
134706 break;
134707 }else{
134708 char *aNew;
134709 int nNew;
134711 int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
134712 pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
134714 if( rc!=SQLITE_OK ){
134715 if( aMerge!=aDoclist ) sqlite3_free(aMerge);
134716 return rc;
134719 if( aMerge!=aDoclist ) sqlite3_free(aMerge);
134720 sqlite3_free(pTS->aaOutput[iOut]);
134721 pTS->aaOutput[iOut] = 0;
134723 aMerge = aNew;
134724 nMerge = nNew;
134725 if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
134726 pTS->aaOutput[iOut] = aMerge;
134727 pTS->anOutput[iOut] = nMerge;
134732 return SQLITE_OK;
134736 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
134738 static int fts3SegReaderCursorAppend(
134739 Fts3MultiSegReader *pCsr,
134740 Fts3SegReader *pNew
134742 if( (pCsr->nSegment%16)==0 ){
134743 Fts3SegReader **apNew;
134744 int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
134745 apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
134746 if( !apNew ){
134747 sqlite3Fts3SegReaderFree(pNew);
134748 return SQLITE_NOMEM;
134750 pCsr->apSegment = apNew;
134752 pCsr->apSegment[pCsr->nSegment++] = pNew;
134753 return SQLITE_OK;
134757 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
134758 ** 8th argument.
134760 ** This function returns SQLITE_OK if successful, or an SQLite error code
134761 ** otherwise.
134763 static int fts3SegReaderCursor(
134764 Fts3Table *p, /* FTS3 table handle */
134765 int iLangid, /* Language id */
134766 int iIndex, /* Index to search (from 0 to p->nIndex-1) */
134767 int iLevel, /* Level of segments to scan */
134768 const char *zTerm, /* Term to query for */
134769 int nTerm, /* Size of zTerm in bytes */
134770 int isPrefix, /* True for a prefix search */
134771 int isScan, /* True to scan from zTerm to EOF */
134772 Fts3MultiSegReader *pCsr /* Cursor object to populate */
134774 int rc = SQLITE_OK; /* Error code */
134775 sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
134776 int rc2; /* Result of sqlite3_reset() */
134778 /* If iLevel is less than 0 and this is not a scan, include a seg-reader
134779 ** for the pending-terms. If this is a scan, then this call must be being
134780 ** made by an fts4aux module, not an FTS table. In this case calling
134781 ** Fts3SegReaderPending might segfault, as the data structures used by
134782 ** fts4aux are not completely populated. So it's easiest to filter these
134783 ** calls out here. */
134784 if( iLevel<0 && p->aIndex ){
134785 Fts3SegReader *pSeg = 0;
134786 rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
134787 if( rc==SQLITE_OK && pSeg ){
134788 rc = fts3SegReaderCursorAppend(pCsr, pSeg);
134792 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
134793 if( rc==SQLITE_OK ){
134794 rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
134797 while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
134798 Fts3SegReader *pSeg = 0;
134800 /* Read the values returned by the SELECT into local variables. */
134801 sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
134802 sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
134803 sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
134804 int nRoot = sqlite3_column_bytes(pStmt, 4);
134805 char const *zRoot = sqlite3_column_blob(pStmt, 4);
134807 /* If zTerm is not NULL, and this segment is not stored entirely on its
134808 ** root node, the range of leaves scanned can be reduced. Do this. */
134809 if( iStartBlock && zTerm ){
134810 sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
134811 rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
134812 if( rc!=SQLITE_OK ) goto finished;
134813 if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
134816 rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
134817 (isPrefix==0 && isScan==0),
134818 iStartBlock, iLeavesEndBlock,
134819 iEndBlock, zRoot, nRoot, &pSeg
134821 if( rc!=SQLITE_OK ) goto finished;
134822 rc = fts3SegReaderCursorAppend(pCsr, pSeg);
134826 finished:
134827 rc2 = sqlite3_reset(pStmt);
134828 if( rc==SQLITE_DONE ) rc = rc2;
134830 return rc;
134834 ** Set up a cursor object for iterating through a full-text index or a
134835 ** single level therein.
134837 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
134838 Fts3Table *p, /* FTS3 table handle */
134839 int iLangid, /* Language-id to search */
134840 int iIndex, /* Index to search (from 0 to p->nIndex-1) */
134841 int iLevel, /* Level of segments to scan */
134842 const char *zTerm, /* Term to query for */
134843 int nTerm, /* Size of zTerm in bytes */
134844 int isPrefix, /* True for a prefix search */
134845 int isScan, /* True to scan from zTerm to EOF */
134846 Fts3MultiSegReader *pCsr /* Cursor object to populate */
134848 assert( iIndex>=0 && iIndex<p->nIndex );
134849 assert( iLevel==FTS3_SEGCURSOR_ALL
134850 || iLevel==FTS3_SEGCURSOR_PENDING
134851 || iLevel>=0
134853 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
134854 assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
134855 assert( isPrefix==0 || isScan==0 );
134857 memset(pCsr, 0, sizeof(Fts3MultiSegReader));
134858 return fts3SegReaderCursor(
134859 p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
134864 ** In addition to its current configuration, have the Fts3MultiSegReader
134865 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
134867 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
134869 static int fts3SegReaderCursorAddZero(
134870 Fts3Table *p, /* FTS virtual table handle */
134871 int iLangid,
134872 const char *zTerm, /* Term to scan doclist of */
134873 int nTerm, /* Number of bytes in zTerm */
134874 Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
134876 return fts3SegReaderCursor(p,
134877 iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
134882 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
134883 ** if isPrefix is true, to scan the doclist for all terms for which
134884 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
134885 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
134886 ** an SQLite error code.
134888 ** It is the responsibility of the caller to free this object by eventually
134889 ** passing it to fts3SegReaderCursorFree()
134891 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
134892 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
134894 static int fts3TermSegReaderCursor(
134895 Fts3Cursor *pCsr, /* Virtual table cursor handle */
134896 const char *zTerm, /* Term to query for */
134897 int nTerm, /* Size of zTerm in bytes */
134898 int isPrefix, /* True for a prefix search */
134899 Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
134901 Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
134902 int rc = SQLITE_NOMEM; /* Return code */
134904 pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
134905 if( pSegcsr ){
134906 int i;
134907 int bFound = 0; /* True once an index has been found */
134908 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
134910 if( isPrefix ){
134911 for(i=1; bFound==0 && i<p->nIndex; i++){
134912 if( p->aIndex[i].nPrefix==nTerm ){
134913 bFound = 1;
134914 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
134915 i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
134917 pSegcsr->bLookup = 1;
134921 for(i=1; bFound==0 && i<p->nIndex; i++){
134922 if( p->aIndex[i].nPrefix==nTerm+1 ){
134923 bFound = 1;
134924 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
134925 i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
134927 if( rc==SQLITE_OK ){
134928 rc = fts3SegReaderCursorAddZero(
134929 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
134936 if( bFound==0 ){
134937 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
134938 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
134940 pSegcsr->bLookup = !isPrefix;
134944 *ppSegcsr = pSegcsr;
134945 return rc;
134949 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
134951 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
134952 sqlite3Fts3SegReaderFinish(pSegcsr);
134953 sqlite3_free(pSegcsr);
134957 ** This function retrieves the doclist for the specified term (or term
134958 ** prefix) from the database.
134960 static int fts3TermSelect(
134961 Fts3Table *p, /* Virtual table handle */
134962 Fts3PhraseToken *pTok, /* Token to query for */
134963 int iColumn, /* Column to query (or -ve for all columns) */
134964 int *pnOut, /* OUT: Size of buffer at *ppOut */
134965 char **ppOut /* OUT: Malloced result buffer */
134967 int rc; /* Return code */
134968 Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
134969 TermSelect tsc; /* Object for pair-wise doclist merging */
134970 Fts3SegFilter filter; /* Segment term filter configuration */
134972 pSegcsr = pTok->pSegcsr;
134973 memset(&tsc, 0, sizeof(TermSelect));
134975 filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
134976 | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
134977 | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
134978 | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
134979 filter.iCol = iColumn;
134980 filter.zTerm = pTok->z;
134981 filter.nTerm = pTok->n;
134983 rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
134984 while( SQLITE_OK==rc
134985 && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
134987 rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
134990 if( rc==SQLITE_OK ){
134991 rc = fts3TermSelectFinishMerge(p, &tsc);
134993 if( rc==SQLITE_OK ){
134994 *ppOut = tsc.aaOutput[0];
134995 *pnOut = tsc.anOutput[0];
134996 }else{
134997 int i;
134998 for(i=0; i<SizeofArray(tsc.aaOutput); i++){
134999 sqlite3_free(tsc.aaOutput[i]);
135003 fts3SegReaderCursorFree(pSegcsr);
135004 pTok->pSegcsr = 0;
135005 return rc;
135009 ** This function counts the total number of docids in the doclist stored
135010 ** in buffer aList[], size nList bytes.
135012 ** If the isPoslist argument is true, then it is assumed that the doclist
135013 ** contains a position-list following each docid. Otherwise, it is assumed
135014 ** that the doclist is simply a list of docids stored as delta encoded
135015 ** varints.
135017 static int fts3DoclistCountDocids(char *aList, int nList){
135018 int nDoc = 0; /* Return value */
135019 if( aList ){
135020 char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
135021 char *p = aList; /* Cursor */
135022 while( p<aEnd ){
135023 nDoc++;
135024 while( (*p++)&0x80 ); /* Skip docid varint */
135025 fts3PoslistCopy(0, &p); /* Skip over position list */
135029 return nDoc;
135033 ** Advance the cursor to the next row in the %_content table that
135034 ** matches the search criteria. For a MATCH search, this will be
135035 ** the next row that matches. For a full-table scan, this will be
135036 ** simply the next row in the %_content table. For a docid lookup,
135037 ** this routine simply sets the EOF flag.
135039 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
135040 ** even if we reach end-of-file. The fts3EofMethod() will be called
135041 ** subsequently to determine whether or not an EOF was hit.
135043 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
135044 int rc;
135045 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
135046 if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
135047 if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
135048 pCsr->isEof = 1;
135049 rc = sqlite3_reset(pCsr->pStmt);
135050 }else{
135051 pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
135052 rc = SQLITE_OK;
135054 }else{
135055 rc = fts3EvalNext((Fts3Cursor *)pCursor);
135057 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
135058 return rc;
135062 ** The following are copied from sqliteInt.h.
135064 ** Constants for the largest and smallest possible 64-bit signed integers.
135065 ** These macros are designed to work correctly on both 32-bit and 64-bit
135066 ** compilers.
135068 #ifndef SQLITE_AMALGAMATION
135069 # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
135070 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
135071 #endif
135074 ** If the numeric type of argument pVal is "integer", then return it
135075 ** converted to a 64-bit signed integer. Otherwise, return a copy of
135076 ** the second parameter, iDefault.
135078 static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
135079 if( pVal ){
135080 int eType = sqlite3_value_numeric_type(pVal);
135081 if( eType==SQLITE_INTEGER ){
135082 return sqlite3_value_int64(pVal);
135085 return iDefault;
135089 ** This is the xFilter interface for the virtual table. See
135090 ** the virtual table xFilter method documentation for additional
135091 ** information.
135093 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
135094 ** the %_content table.
135096 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
135097 ** in the %_content table.
135099 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
135100 ** column on the left-hand side of the MATCH operator is column
135101 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
135102 ** side of the MATCH operator.
135104 static int fts3FilterMethod(
135105 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
135106 int idxNum, /* Strategy index */
135107 const char *idxStr, /* Unused */
135108 int nVal, /* Number of elements in apVal */
135109 sqlite3_value **apVal /* Arguments for the indexing scheme */
135111 int rc;
135112 char *zSql; /* SQL statement used to access %_content */
135113 int eSearch;
135114 Fts3Table *p = (Fts3Table *)pCursor->pVtab;
135115 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
135117 sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
135118 sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
135119 sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
135120 sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
135121 int iIdx;
135123 UNUSED_PARAMETER(idxStr);
135124 UNUSED_PARAMETER(nVal);
135126 eSearch = (idxNum & 0x0000FFFF);
135127 assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
135128 assert( p->pSegments==0 );
135130 /* Collect arguments into local variables */
135131 iIdx = 0;
135132 if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
135133 if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
135134 if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
135135 if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
135136 assert( iIdx==nVal );
135138 /* In case the cursor has been used before, clear it now. */
135139 sqlite3_finalize(pCsr->pStmt);
135140 sqlite3_free(pCsr->aDoclist);
135141 sqlite3_free(pCsr->aMatchinfo);
135142 sqlite3Fts3ExprFree(pCsr->pExpr);
135143 memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
135145 /* Set the lower and upper bounds on docids to return */
135146 pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
135147 pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
135149 if( idxStr ){
135150 pCsr->bDesc = (idxStr[0]=='D');
135151 }else{
135152 pCsr->bDesc = p->bDescIdx;
135154 pCsr->eSearch = (i16)eSearch;
135156 if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
135157 int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
135158 const char *zQuery = (const char *)sqlite3_value_text(pCons);
135160 if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
135161 return SQLITE_NOMEM;
135164 pCsr->iLangid = 0;
135165 if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
135167 assert( p->base.zErrMsg==0 );
135168 rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
135169 p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
135170 &p->base.zErrMsg
135172 if( rc!=SQLITE_OK ){
135173 return rc;
135176 rc = fts3EvalStart(pCsr);
135177 sqlite3Fts3SegmentsClose(p);
135178 if( rc!=SQLITE_OK ) return rc;
135179 pCsr->pNextId = pCsr->aDoclist;
135180 pCsr->iPrevId = 0;
135183 /* Compile a SELECT statement for this cursor. For a full-table-scan, the
135184 ** statement loops through all rows of the %_content table. For a
135185 ** full-text query or docid lookup, the statement retrieves a single
135186 ** row by docid.
135188 if( eSearch==FTS3_FULLSCAN_SEARCH ){
135189 zSql = sqlite3_mprintf(
135190 "SELECT %s ORDER BY rowid %s",
135191 p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
135193 if( zSql ){
135194 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
135195 sqlite3_free(zSql);
135196 }else{
135197 rc = SQLITE_NOMEM;
135199 }else if( eSearch==FTS3_DOCID_SEARCH ){
135200 rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
135201 if( rc==SQLITE_OK ){
135202 rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
135205 if( rc!=SQLITE_OK ) return rc;
135207 return fts3NextMethod(pCursor);
135211 ** This is the xEof method of the virtual table. SQLite calls this
135212 ** routine to find out if it has reached the end of a result set.
135214 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
135215 return ((Fts3Cursor *)pCursor)->isEof;
135219 ** This is the xRowid method. The SQLite core calls this routine to
135220 ** retrieve the rowid for the current row of the result set. fts3
135221 ** exposes %_content.docid as the rowid for the virtual table. The
135222 ** rowid should be written to *pRowid.
135224 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
135225 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
135226 *pRowid = pCsr->iPrevId;
135227 return SQLITE_OK;
135231 ** This is the xColumn method, called by SQLite to request a value from
135232 ** the row that the supplied cursor currently points to.
135234 ** If:
135236 ** (iCol < p->nColumn) -> The value of the iCol'th user column.
135237 ** (iCol == p->nColumn) -> Magic column with the same name as the table.
135238 ** (iCol == p->nColumn+1) -> Docid column
135239 ** (iCol == p->nColumn+2) -> Langid column
135241 static int fts3ColumnMethod(
135242 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
135243 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
135244 int iCol /* Index of column to read value from */
135246 int rc = SQLITE_OK; /* Return Code */
135247 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
135248 Fts3Table *p = (Fts3Table *)pCursor->pVtab;
135250 /* The column value supplied by SQLite must be in range. */
135251 assert( iCol>=0 && iCol<=p->nColumn+2 );
135253 if( iCol==p->nColumn+1 ){
135254 /* This call is a request for the "docid" column. Since "docid" is an
135255 ** alias for "rowid", use the xRowid() method to obtain the value.
135257 sqlite3_result_int64(pCtx, pCsr->iPrevId);
135258 }else if( iCol==p->nColumn ){
135259 /* The extra column whose name is the same as the table.
135260 ** Return a blob which is a pointer to the cursor. */
135261 sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
135262 }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
135263 sqlite3_result_int64(pCtx, pCsr->iLangid);
135264 }else{
135265 /* The requested column is either a user column (one that contains
135266 ** indexed data), or the language-id column. */
135267 rc = fts3CursorSeek(0, pCsr);
135269 if( rc==SQLITE_OK ){
135270 if( iCol==p->nColumn+2 ){
135271 int iLangid = 0;
135272 if( p->zLanguageid ){
135273 iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
135275 sqlite3_result_int(pCtx, iLangid);
135276 }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
135277 sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
135282 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
135283 return rc;
135287 ** This function is the implementation of the xUpdate callback used by
135288 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
135289 ** inserted, updated or deleted.
135291 static int fts3UpdateMethod(
135292 sqlite3_vtab *pVtab, /* Virtual table handle */
135293 int nArg, /* Size of argument array */
135294 sqlite3_value **apVal, /* Array of arguments */
135295 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
135297 return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
135301 ** Implementation of xSync() method. Flush the contents of the pending-terms
135302 ** hash-table to the database.
135304 static int fts3SyncMethod(sqlite3_vtab *pVtab){
135306 /* Following an incremental-merge operation, assuming that the input
135307 ** segments are not completely consumed (the usual case), they are updated
135308 ** in place to remove the entries that have already been merged. This
135309 ** involves updating the leaf block that contains the smallest unmerged
135310 ** entry and each block (if any) between the leaf and the root node. So
135311 ** if the height of the input segment b-trees is N, and input segments
135312 ** are merged eight at a time, updating the input segments at the end
135313 ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
135314 ** small - often between 0 and 2. So the overhead of the incremental
135315 ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
135316 ** dwarfing the actual productive work accomplished, the incremental merge
135317 ** is only attempted if it will write at least 64 leaf blocks. Hence
135318 ** nMinMerge.
135320 ** Of course, updating the input segments also involves deleting a bunch
135321 ** of blocks from the segments table. But this is not considered overhead
135322 ** as it would also be required by a crisis-merge that used the same input
135323 ** segments.
135325 const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
135327 Fts3Table *p = (Fts3Table*)pVtab;
135328 int rc = sqlite3Fts3PendingTermsFlush(p);
135330 if( rc==SQLITE_OK
135331 && p->nLeafAdd>(nMinMerge/16)
135332 && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
135334 int mxLevel = 0; /* Maximum relative level value in db */
135335 int A; /* Incr-merge parameter A */
135337 rc = sqlite3Fts3MaxLevel(p, &mxLevel);
135338 assert( rc==SQLITE_OK || mxLevel==0 );
135339 A = p->nLeafAdd * mxLevel;
135340 A += (A/2);
135341 if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
135343 sqlite3Fts3SegmentsClose(p);
135344 return rc;
135348 ** If it is currently unknown whether or not the FTS table has an %_stat
135349 ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
135350 ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
135351 ** if an error occurs.
135353 static int fts3SetHasStat(Fts3Table *p){
135354 int rc = SQLITE_OK;
135355 if( p->bHasStat==2 ){
135356 const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
135357 char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
135358 if( zSql ){
135359 sqlite3_stmt *pStmt = 0;
135360 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
135361 if( rc==SQLITE_OK ){
135362 int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
135363 rc = sqlite3_finalize(pStmt);
135364 if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
135366 sqlite3_free(zSql);
135367 }else{
135368 rc = SQLITE_NOMEM;
135371 return rc;
135375 ** Implementation of xBegin() method.
135377 static int fts3BeginMethod(sqlite3_vtab *pVtab){
135378 Fts3Table *p = (Fts3Table*)pVtab;
135379 UNUSED_PARAMETER(pVtab);
135380 assert( p->pSegments==0 );
135381 assert( p->nPendingData==0 );
135382 assert( p->inTransaction!=1 );
135383 TESTONLY( p->inTransaction = 1 );
135384 TESTONLY( p->mxSavepoint = -1; );
135385 p->nLeafAdd = 0;
135386 return fts3SetHasStat(p);
135390 ** Implementation of xCommit() method. This is a no-op. The contents of
135391 ** the pending-terms hash-table have already been flushed into the database
135392 ** by fts3SyncMethod().
135394 static int fts3CommitMethod(sqlite3_vtab *pVtab){
135395 TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
135396 UNUSED_PARAMETER(pVtab);
135397 assert( p->nPendingData==0 );
135398 assert( p->inTransaction!=0 );
135399 assert( p->pSegments==0 );
135400 TESTONLY( p->inTransaction = 0 );
135401 TESTONLY( p->mxSavepoint = -1; );
135402 return SQLITE_OK;
135406 ** Implementation of xRollback(). Discard the contents of the pending-terms
135407 ** hash-table. Any changes made to the database are reverted by SQLite.
135409 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
135410 Fts3Table *p = (Fts3Table*)pVtab;
135411 sqlite3Fts3PendingTermsClear(p);
135412 assert( p->inTransaction!=0 );
135413 TESTONLY( p->inTransaction = 0 );
135414 TESTONLY( p->mxSavepoint = -1; );
135415 return SQLITE_OK;
135419 ** When called, *ppPoslist must point to the byte immediately following the
135420 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
135421 ** moves *ppPoslist so that it instead points to the first byte of the
135422 ** same position list.
135424 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
135425 char *p = &(*ppPoslist)[-2];
135426 char c = 0;
135428 while( p>pStart && (c=*p--)==0 );
135429 while( p>pStart && (*p & 0x80) | c ){
135430 c = *p--;
135432 if( p>pStart ){ p = &p[2]; }
135433 while( *p++&0x80 );
135434 *ppPoslist = p;
135438 ** Helper function used by the implementation of the overloaded snippet(),
135439 ** offsets() and optimize() SQL functions.
135441 ** If the value passed as the third argument is a blob of size
135442 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
135443 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
135444 ** message is written to context pContext and SQLITE_ERROR returned. The
135445 ** string passed via zFunc is used as part of the error message.
135447 static int fts3FunctionArg(
135448 sqlite3_context *pContext, /* SQL function call context */
135449 const char *zFunc, /* Function name */
135450 sqlite3_value *pVal, /* argv[0] passed to function */
135451 Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
135453 Fts3Cursor *pRet;
135454 if( sqlite3_value_type(pVal)!=SQLITE_BLOB
135455 || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
135457 char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
135458 sqlite3_result_error(pContext, zErr, -1);
135459 sqlite3_free(zErr);
135460 return SQLITE_ERROR;
135462 memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
135463 *ppCsr = pRet;
135464 return SQLITE_OK;
135468 ** Implementation of the snippet() function for FTS3
135470 static void fts3SnippetFunc(
135471 sqlite3_context *pContext, /* SQLite function call context */
135472 int nVal, /* Size of apVal[] array */
135473 sqlite3_value **apVal /* Array of arguments */
135475 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
135476 const char *zStart = "<b>";
135477 const char *zEnd = "</b>";
135478 const char *zEllipsis = "<b>...</b>";
135479 int iCol = -1;
135480 int nToken = 15; /* Default number of tokens in snippet */
135482 /* There must be at least one argument passed to this function (otherwise
135483 ** the non-overloaded version would have been called instead of this one).
135485 assert( nVal>=1 );
135487 if( nVal>6 ){
135488 sqlite3_result_error(pContext,
135489 "wrong number of arguments to function snippet()", -1);
135490 return;
135492 if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
135494 switch( nVal ){
135495 case 6: nToken = sqlite3_value_int(apVal[5]);
135496 case 5: iCol = sqlite3_value_int(apVal[4]);
135497 case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
135498 case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
135499 case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
135501 if( !zEllipsis || !zEnd || !zStart ){
135502 sqlite3_result_error_nomem(pContext);
135503 }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
135504 sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
135509 ** Implementation of the offsets() function for FTS3
135511 static void fts3OffsetsFunc(
135512 sqlite3_context *pContext, /* SQLite function call context */
135513 int nVal, /* Size of argument array */
135514 sqlite3_value **apVal /* Array of arguments */
135516 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
135518 UNUSED_PARAMETER(nVal);
135520 assert( nVal==1 );
135521 if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
135522 assert( pCsr );
135523 if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
135524 sqlite3Fts3Offsets(pContext, pCsr);
135529 ** Implementation of the special optimize() function for FTS3. This
135530 ** function merges all segments in the database to a single segment.
135531 ** Example usage is:
135533 ** SELECT optimize(t) FROM t LIMIT 1;
135535 ** where 't' is the name of an FTS3 table.
135537 static void fts3OptimizeFunc(
135538 sqlite3_context *pContext, /* SQLite function call context */
135539 int nVal, /* Size of argument array */
135540 sqlite3_value **apVal /* Array of arguments */
135542 int rc; /* Return code */
135543 Fts3Table *p; /* Virtual table handle */
135544 Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
135546 UNUSED_PARAMETER(nVal);
135548 assert( nVal==1 );
135549 if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
135550 p = (Fts3Table *)pCursor->base.pVtab;
135551 assert( p );
135553 rc = sqlite3Fts3Optimize(p);
135555 switch( rc ){
135556 case SQLITE_OK:
135557 sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
135558 break;
135559 case SQLITE_DONE:
135560 sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
135561 break;
135562 default:
135563 sqlite3_result_error_code(pContext, rc);
135564 break;
135569 ** Implementation of the matchinfo() function for FTS3
135571 static void fts3MatchinfoFunc(
135572 sqlite3_context *pContext, /* SQLite function call context */
135573 int nVal, /* Size of argument array */
135574 sqlite3_value **apVal /* Array of arguments */
135576 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
135577 assert( nVal==1 || nVal==2 );
135578 if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
135579 const char *zArg = 0;
135580 if( nVal>1 ){
135581 zArg = (const char *)sqlite3_value_text(apVal[1]);
135583 sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
135588 ** This routine implements the xFindFunction method for the FTS3
135589 ** virtual table.
135591 static int fts3FindFunctionMethod(
135592 sqlite3_vtab *pVtab, /* Virtual table handle */
135593 int nArg, /* Number of SQL function arguments */
135594 const char *zName, /* Name of SQL function */
135595 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
135596 void **ppArg /* Unused */
135598 struct Overloaded {
135599 const char *zName;
135600 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
135601 } aOverload[] = {
135602 { "snippet", fts3SnippetFunc },
135603 { "offsets", fts3OffsetsFunc },
135604 { "optimize", fts3OptimizeFunc },
135605 { "matchinfo", fts3MatchinfoFunc },
135607 int i; /* Iterator variable */
135609 UNUSED_PARAMETER(pVtab);
135610 UNUSED_PARAMETER(nArg);
135611 UNUSED_PARAMETER(ppArg);
135613 for(i=0; i<SizeofArray(aOverload); i++){
135614 if( strcmp(zName, aOverload[i].zName)==0 ){
135615 *pxFunc = aOverload[i].xFunc;
135616 return 1;
135620 /* No function of the specified name was found. Return 0. */
135621 return 0;
135625 ** Implementation of FTS3 xRename method. Rename an fts3 table.
135627 static int fts3RenameMethod(
135628 sqlite3_vtab *pVtab, /* Virtual table handle */
135629 const char *zName /* New name of table */
135631 Fts3Table *p = (Fts3Table *)pVtab;
135632 sqlite3 *db = p->db; /* Database connection */
135633 int rc; /* Return Code */
135635 /* At this point it must be known if the %_stat table exists or not.
135636 ** So bHasStat may not be 2. */
135637 rc = fts3SetHasStat(p);
135639 /* As it happens, the pending terms table is always empty here. This is
135640 ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
135641 ** always opens a savepoint transaction. And the xSavepoint() method
135642 ** flushes the pending terms table. But leave the (no-op) call to
135643 ** PendingTermsFlush() in in case that changes.
135645 assert( p->nPendingData==0 );
135646 if( rc==SQLITE_OK ){
135647 rc = sqlite3Fts3PendingTermsFlush(p);
135650 if( p->zContentTbl==0 ){
135651 fts3DbExec(&rc, db,
135652 "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
135653 p->zDb, p->zName, zName
135657 if( p->bHasDocsize ){
135658 fts3DbExec(&rc, db,
135659 "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
135660 p->zDb, p->zName, zName
135663 if( p->bHasStat ){
135664 fts3DbExec(&rc, db,
135665 "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
135666 p->zDb, p->zName, zName
135669 fts3DbExec(&rc, db,
135670 "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
135671 p->zDb, p->zName, zName
135673 fts3DbExec(&rc, db,
135674 "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
135675 p->zDb, p->zName, zName
135677 return rc;
135681 ** The xSavepoint() method.
135683 ** Flush the contents of the pending-terms table to disk.
135685 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
135686 int rc = SQLITE_OK;
135687 UNUSED_PARAMETER(iSavepoint);
135688 assert( ((Fts3Table *)pVtab)->inTransaction );
135689 assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
135690 TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
135691 if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
135692 rc = fts3SyncMethod(pVtab);
135694 return rc;
135698 ** The xRelease() method.
135700 ** This is a no-op.
135702 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
135703 TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
135704 UNUSED_PARAMETER(iSavepoint);
135705 UNUSED_PARAMETER(pVtab);
135706 assert( p->inTransaction );
135707 assert( p->mxSavepoint >= iSavepoint );
135708 TESTONLY( p->mxSavepoint = iSavepoint-1 );
135709 return SQLITE_OK;
135713 ** The xRollbackTo() method.
135715 ** Discard the contents of the pending terms table.
135717 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
135718 Fts3Table *p = (Fts3Table*)pVtab;
135719 UNUSED_PARAMETER(iSavepoint);
135720 assert( p->inTransaction );
135721 assert( p->mxSavepoint >= iSavepoint );
135722 TESTONLY( p->mxSavepoint = iSavepoint );
135723 sqlite3Fts3PendingTermsClear(p);
135724 return SQLITE_OK;
135727 static const sqlite3_module fts3Module = {
135728 /* iVersion */ 2,
135729 /* xCreate */ fts3CreateMethod,
135730 /* xConnect */ fts3ConnectMethod,
135731 /* xBestIndex */ fts3BestIndexMethod,
135732 /* xDisconnect */ fts3DisconnectMethod,
135733 /* xDestroy */ fts3DestroyMethod,
135734 /* xOpen */ fts3OpenMethod,
135735 /* xClose */ fts3CloseMethod,
135736 /* xFilter */ fts3FilterMethod,
135737 /* xNext */ fts3NextMethod,
135738 /* xEof */ fts3EofMethod,
135739 /* xColumn */ fts3ColumnMethod,
135740 /* xRowid */ fts3RowidMethod,
135741 /* xUpdate */ fts3UpdateMethod,
135742 /* xBegin */ fts3BeginMethod,
135743 /* xSync */ fts3SyncMethod,
135744 /* xCommit */ fts3CommitMethod,
135745 /* xRollback */ fts3RollbackMethod,
135746 /* xFindFunction */ fts3FindFunctionMethod,
135747 /* xRename */ fts3RenameMethod,
135748 /* xSavepoint */ fts3SavepointMethod,
135749 /* xRelease */ fts3ReleaseMethod,
135750 /* xRollbackTo */ fts3RollbackToMethod,
135754 ** This function is registered as the module destructor (called when an
135755 ** FTS3 enabled database connection is closed). It frees the memory
135756 ** allocated for the tokenizer hash table.
135758 static void hashDestroy(void *p){
135759 Fts3Hash *pHash = (Fts3Hash *)p;
135760 sqlite3Fts3HashClear(pHash);
135761 sqlite3_free(pHash);
135765 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
135766 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
135767 ** respectively. The following three forward declarations are for functions
135768 ** declared in these files used to retrieve the respective implementations.
135770 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
135771 ** to by the argument to point to the "simple" tokenizer implementation.
135772 ** And so on.
135774 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
135775 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
135776 #ifndef SQLITE_DISABLE_FTS3_UNICODE
135777 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
135778 #endif
135779 #ifdef SQLITE_ENABLE_ICU
135780 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
135781 #endif
135784 ** Initialize the fts3 extension. If this extension is built as part
135785 ** of the sqlite library, then this function is called directly by
135786 ** SQLite. If fts3 is built as a dynamically loadable extension, this
135787 ** function is called by the sqlite3_extension_init() entry point.
135789 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
135790 int rc = SQLITE_OK;
135791 Fts3Hash *pHash = 0;
135792 const sqlite3_tokenizer_module *pSimple = 0;
135793 const sqlite3_tokenizer_module *pPorter = 0;
135794 #ifndef SQLITE_DISABLE_FTS3_UNICODE
135795 const sqlite3_tokenizer_module *pUnicode = 0;
135796 #endif
135798 #ifdef SQLITE_ENABLE_ICU
135799 const sqlite3_tokenizer_module *pIcu = 0;
135800 sqlite3Fts3IcuTokenizerModule(&pIcu);
135801 #endif
135803 #ifndef SQLITE_DISABLE_FTS3_UNICODE
135804 sqlite3Fts3UnicodeTokenizer(&pUnicode);
135805 #endif
135807 #ifdef SQLITE_TEST
135808 rc = sqlite3Fts3InitTerm(db);
135809 if( rc!=SQLITE_OK ) return rc;
135810 #endif
135812 rc = sqlite3Fts3InitAux(db);
135813 if( rc!=SQLITE_OK ) return rc;
135815 sqlite3Fts3SimpleTokenizerModule(&pSimple);
135816 sqlite3Fts3PorterTokenizerModule(&pPorter);
135818 /* Allocate and initialize the hash-table used to store tokenizers. */
135819 pHash = sqlite3_malloc(sizeof(Fts3Hash));
135820 if( !pHash ){
135821 rc = SQLITE_NOMEM;
135822 }else{
135823 sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
135826 /* Load the built-in tokenizers into the hash table */
135827 if( rc==SQLITE_OK ){
135828 if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
135829 || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
135831 #ifndef SQLITE_DISABLE_FTS3_UNICODE
135832 || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
135833 #endif
135834 #ifdef SQLITE_ENABLE_ICU
135835 || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
135836 #endif
135838 rc = SQLITE_NOMEM;
135842 #ifdef SQLITE_TEST
135843 if( rc==SQLITE_OK ){
135844 rc = sqlite3Fts3ExprInitTestInterface(db);
135846 #endif
135848 /* Create the virtual table wrapper around the hash-table and overload
135849 ** the two scalar functions. If this is successful, register the
135850 ** module with sqlite.
135852 if( SQLITE_OK==rc
135853 #if CHROMIUM_FTS3_CHANGES && !SQLITE_TEST
135854 /* fts3_tokenizer() disabled for security reasons. */
135855 #else
135856 && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
135857 #endif
135858 && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
135859 && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
135860 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
135861 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
135862 && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
135864 rc = sqlite3_create_module_v2(
135865 db, "fts3", &fts3Module, (void *)pHash, hashDestroy
135867 #if CHROMIUM_FTS3_CHANGES && !SQLITE_TEST
135868 /* Disable fts4 and tokenizer vtab pending review. */
135869 #else
135870 if( rc==SQLITE_OK ){
135871 rc = sqlite3_create_module_v2(
135872 db, "fts4", &fts3Module, (void *)pHash, 0
135875 if( rc==SQLITE_OK ){
135876 rc = sqlite3Fts3InitTok(db, (void *)pHash);
135878 #endif
135879 return rc;
135883 /* An error has occurred. Delete the hash table and return the error code. */
135884 assert( rc!=SQLITE_OK );
135885 if( pHash ){
135886 sqlite3Fts3HashClear(pHash);
135887 sqlite3_free(pHash);
135889 return rc;
135893 ** Allocate an Fts3MultiSegReader for each token in the expression headed
135894 ** by pExpr.
135896 ** An Fts3SegReader object is a cursor that can seek or scan a range of
135897 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
135898 ** Fts3SegReader objects internally to provide an interface to seek or scan
135899 ** within the union of all segments of a b-tree. Hence the name.
135901 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
135902 ** segment b-tree (if the term is not a prefix or it is a prefix for which
135903 ** there exists prefix b-tree of the right length) then it may be traversed
135904 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
135905 ** doclist and then traversed.
135907 static void fts3EvalAllocateReaders(
135908 Fts3Cursor *pCsr, /* FTS cursor handle */
135909 Fts3Expr *pExpr, /* Allocate readers for this expression */
135910 int *pnToken, /* OUT: Total number of tokens in phrase. */
135911 int *pnOr, /* OUT: Total number of OR nodes in expr. */
135912 int *pRc /* IN/OUT: Error code */
135914 if( pExpr && SQLITE_OK==*pRc ){
135915 if( pExpr->eType==FTSQUERY_PHRASE ){
135916 int i;
135917 int nToken = pExpr->pPhrase->nToken;
135918 *pnToken += nToken;
135919 for(i=0; i<nToken; i++){
135920 Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
135921 int rc = fts3TermSegReaderCursor(pCsr,
135922 pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
135924 if( rc!=SQLITE_OK ){
135925 *pRc = rc;
135926 return;
135929 assert( pExpr->pPhrase->iDoclistToken==0 );
135930 pExpr->pPhrase->iDoclistToken = -1;
135931 }else{
135932 *pnOr += (pExpr->eType==FTSQUERY_OR);
135933 fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
135934 fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
135940 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
135941 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
135943 ** This function assumes that pList points to a buffer allocated using
135944 ** sqlite3_malloc(). This function takes responsibility for eventually
135945 ** freeing the buffer.
135947 static void fts3EvalPhraseMergeToken(
135948 Fts3Table *pTab, /* FTS Table pointer */
135949 Fts3Phrase *p, /* Phrase to merge pList/nList into */
135950 int iToken, /* Token pList/nList corresponds to */
135951 char *pList, /* Pointer to doclist */
135952 int nList /* Number of bytes in pList */
135954 assert( iToken!=p->iDoclistToken );
135956 if( pList==0 ){
135957 sqlite3_free(p->doclist.aAll);
135958 p->doclist.aAll = 0;
135959 p->doclist.nAll = 0;
135962 else if( p->iDoclistToken<0 ){
135963 p->doclist.aAll = pList;
135964 p->doclist.nAll = nList;
135967 else if( p->doclist.aAll==0 ){
135968 sqlite3_free(pList);
135971 else {
135972 char *pLeft;
135973 char *pRight;
135974 int nLeft;
135975 int nRight;
135976 int nDiff;
135978 if( p->iDoclistToken<iToken ){
135979 pLeft = p->doclist.aAll;
135980 nLeft = p->doclist.nAll;
135981 pRight = pList;
135982 nRight = nList;
135983 nDiff = iToken - p->iDoclistToken;
135984 }else{
135985 pRight = p->doclist.aAll;
135986 nRight = p->doclist.nAll;
135987 pLeft = pList;
135988 nLeft = nList;
135989 nDiff = p->iDoclistToken - iToken;
135992 fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
135993 sqlite3_free(pLeft);
135994 p->doclist.aAll = pRight;
135995 p->doclist.nAll = nRight;
135998 if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
136002 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
136003 ** does not take deferred tokens into account.
136005 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
136007 static int fts3EvalPhraseLoad(
136008 Fts3Cursor *pCsr, /* FTS Cursor handle */
136009 Fts3Phrase *p /* Phrase object */
136011 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
136012 int iToken;
136013 int rc = SQLITE_OK;
136015 for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
136016 Fts3PhraseToken *pToken = &p->aToken[iToken];
136017 assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
136019 if( pToken->pSegcsr ){
136020 int nThis = 0;
136021 char *pThis = 0;
136022 rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
136023 if( rc==SQLITE_OK ){
136024 fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
136027 assert( pToken->pSegcsr==0 );
136030 return rc;
136034 ** This function is called on each phrase after the position lists for
136035 ** any deferred tokens have been loaded into memory. It updates the phrases
136036 ** current position list to include only those positions that are really
136037 ** instances of the phrase (after considering deferred tokens). If this
136038 ** means that the phrase does not appear in the current row, doclist.pList
136039 ** and doclist.nList are both zeroed.
136041 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
136043 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
136044 int iToken; /* Used to iterate through phrase tokens */
136045 char *aPoslist = 0; /* Position list for deferred tokens */
136046 int nPoslist = 0; /* Number of bytes in aPoslist */
136047 int iPrev = -1; /* Token number of previous deferred token */
136049 assert( pPhrase->doclist.bFreeList==0 );
136051 for(iToken=0; iToken<pPhrase->nToken; iToken++){
136052 Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
136053 Fts3DeferredToken *pDeferred = pToken->pDeferred;
136055 if( pDeferred ){
136056 char *pList = 0;
136057 int nList = 0;
136058 int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
136059 if( rc!=SQLITE_OK ) return rc;
136061 if( pList==0 ){
136062 sqlite3_free(aPoslist);
136063 pPhrase->doclist.pList = 0;
136064 pPhrase->doclist.nList = 0;
136065 return SQLITE_OK;
136067 }else if( aPoslist==0 ){
136068 aPoslist = pList;
136069 nPoslist = nList;
136071 }else{
136072 char *aOut = pList;
136073 char *p1 = aPoslist;
136074 char *p2 = aOut;
136076 assert( iPrev>=0 );
136077 fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
136078 sqlite3_free(aPoslist);
136079 aPoslist = pList;
136080 nPoslist = (int)(aOut - aPoslist);
136081 if( nPoslist==0 ){
136082 sqlite3_free(aPoslist);
136083 pPhrase->doclist.pList = 0;
136084 pPhrase->doclist.nList = 0;
136085 return SQLITE_OK;
136088 iPrev = iToken;
136092 if( iPrev>=0 ){
136093 int nMaxUndeferred = pPhrase->iDoclistToken;
136094 if( nMaxUndeferred<0 ){
136095 pPhrase->doclist.pList = aPoslist;
136096 pPhrase->doclist.nList = nPoslist;
136097 pPhrase->doclist.iDocid = pCsr->iPrevId;
136098 pPhrase->doclist.bFreeList = 1;
136099 }else{
136100 int nDistance;
136101 char *p1;
136102 char *p2;
136103 char *aOut;
136105 if( nMaxUndeferred>iPrev ){
136106 p1 = aPoslist;
136107 p2 = pPhrase->doclist.pList;
136108 nDistance = nMaxUndeferred - iPrev;
136109 }else{
136110 p1 = pPhrase->doclist.pList;
136111 p2 = aPoslist;
136112 nDistance = iPrev - nMaxUndeferred;
136115 aOut = (char *)sqlite3_malloc(nPoslist+8);
136116 if( !aOut ){
136117 sqlite3_free(aPoslist);
136118 return SQLITE_NOMEM;
136121 pPhrase->doclist.pList = aOut;
136122 if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
136123 pPhrase->doclist.bFreeList = 1;
136124 pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
136125 }else{
136126 sqlite3_free(aOut);
136127 pPhrase->doclist.pList = 0;
136128 pPhrase->doclist.nList = 0;
136130 sqlite3_free(aPoslist);
136134 return SQLITE_OK;
136138 ** Maximum number of tokens a phrase may have to be considered for the
136139 ** incremental doclists strategy.
136141 #define MAX_INCR_PHRASE_TOKENS 4
136144 ** This function is called for each Fts3Phrase in a full-text query
136145 ** expression to initialize the mechanism for returning rows. Once this
136146 ** function has been called successfully on an Fts3Phrase, it may be
136147 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
136149 ** If parameter bOptOk is true, then the phrase may (or may not) use the
136150 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
136151 ** memory within this call.
136153 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
136155 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
136156 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
136157 int rc = SQLITE_OK; /* Error code */
136158 int i;
136160 /* Determine if doclists may be loaded from disk incrementally. This is
136161 ** possible if the bOptOk argument is true, the FTS doclists will be
136162 ** scanned in forward order, and the phrase consists of
136163 ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
136164 ** tokens or prefix tokens that cannot use a prefix-index. */
136165 int bHaveIncr = 0;
136166 int bIncrOk = (bOptOk
136167 && pCsr->bDesc==pTab->bDescIdx
136168 && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
136169 && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
136170 #ifdef SQLITE_TEST
136171 && pTab->bNoIncrDoclist==0
136172 #endif
136174 for(i=0; bIncrOk==1 && i<p->nToken; i++){
136175 Fts3PhraseToken *pToken = &p->aToken[i];
136176 if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
136177 bIncrOk = 0;
136179 if( pToken->pSegcsr ) bHaveIncr = 1;
136182 if( bIncrOk && bHaveIncr ){
136183 /* Use the incremental approach. */
136184 int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
136185 for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
136186 Fts3PhraseToken *pToken = &p->aToken[i];
136187 Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
136188 if( pSegcsr ){
136189 rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
136192 p->bIncr = 1;
136193 }else{
136194 /* Load the full doclist for the phrase into memory. */
136195 rc = fts3EvalPhraseLoad(pCsr, p);
136196 p->bIncr = 0;
136199 assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
136200 return rc;
136204 ** This function is used to iterate backwards (from the end to start)
136205 ** through doclists. It is used by this module to iterate through phrase
136206 ** doclists in reverse and by the fts3_write.c module to iterate through
136207 ** pending-terms lists when writing to databases with "order=desc".
136209 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
136210 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
136211 ** function iterates from the end of the doclist to the beginning.
136213 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
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 int *pnList, /* OUT: List length pointer */
136220 u8 *pbEof /* OUT: End-of-file flag */
136222 char *p = *ppIter;
136224 assert( nDoclist>0 );
136225 assert( *pbEof==0 );
136226 assert( p || *piDocid==0 );
136227 assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
136229 if( p==0 ){
136230 sqlite3_int64 iDocid = 0;
136231 char *pNext = 0;
136232 char *pDocid = aDoclist;
136233 char *pEnd = &aDoclist[nDoclist];
136234 int iMul = 1;
136236 while( pDocid<pEnd ){
136237 sqlite3_int64 iDelta;
136238 pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
136239 iDocid += (iMul * iDelta);
136240 pNext = pDocid;
136241 fts3PoslistCopy(0, &pDocid);
136242 while( pDocid<pEnd && *pDocid==0 ) pDocid++;
136243 iMul = (bDescIdx ? -1 : 1);
136246 *pnList = (int)(pEnd - pNext);
136247 *ppIter = pNext;
136248 *piDocid = iDocid;
136249 }else{
136250 int iMul = (bDescIdx ? -1 : 1);
136251 sqlite3_int64 iDelta;
136252 fts3GetReverseVarint(&p, aDoclist, &iDelta);
136253 *piDocid -= (iMul * iDelta);
136255 if( p==aDoclist ){
136256 *pbEof = 1;
136257 }else{
136258 char *pSave = p;
136259 fts3ReversePoslist(aDoclist, &p);
136260 *pnList = (int)(pSave - p);
136262 *ppIter = p;
136267 ** Iterate forwards through a doclist.
136269 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
136270 int bDescIdx, /* True if the doclist is desc */
136271 char *aDoclist, /* Pointer to entire doclist */
136272 int nDoclist, /* Length of aDoclist in bytes */
136273 char **ppIter, /* IN/OUT: Iterator pointer */
136274 sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
136275 u8 *pbEof /* OUT: End-of-file flag */
136277 char *p = *ppIter;
136279 assert( nDoclist>0 );
136280 assert( *pbEof==0 );
136281 assert( p || *piDocid==0 );
136282 assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
136284 if( p==0 ){
136285 p = aDoclist;
136286 p += sqlite3Fts3GetVarint(p, piDocid);
136287 }else{
136288 fts3PoslistCopy(0, &p);
136289 if( p>=&aDoclist[nDoclist] ){
136290 *pbEof = 1;
136291 }else{
136292 sqlite3_int64 iVar;
136293 p += sqlite3Fts3GetVarint(p, &iVar);
136294 *piDocid += ((bDescIdx ? -1 : 1) * iVar);
136298 *ppIter = p;
136302 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
136303 ** to true if EOF is reached.
136305 static void fts3EvalDlPhraseNext(
136306 Fts3Table *pTab,
136307 Fts3Doclist *pDL,
136308 u8 *pbEof
136310 char *pIter; /* Used to iterate through aAll */
136311 char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
136313 if( pDL->pNextDocid ){
136314 pIter = pDL->pNextDocid;
136315 }else{
136316 pIter = pDL->aAll;
136319 if( pIter>=pEnd ){
136320 /* We have already reached the end of this doclist. EOF. */
136321 *pbEof = 1;
136322 }else{
136323 sqlite3_int64 iDelta;
136324 pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
136325 if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
136326 pDL->iDocid += iDelta;
136327 }else{
136328 pDL->iDocid -= iDelta;
136330 pDL->pList = pIter;
136331 fts3PoslistCopy(0, &pIter);
136332 pDL->nList = (int)(pIter - pDL->pList);
136334 /* pIter now points just past the 0x00 that terminates the position-
136335 ** list for document pDL->iDocid. However, if this position-list was
136336 ** edited in place by fts3EvalNearTrim(), then pIter may not actually
136337 ** point to the start of the next docid value. The following line deals
136338 ** with this case by advancing pIter past the zero-padding added by
136339 ** fts3EvalNearTrim(). */
136340 while( pIter<pEnd && *pIter==0 ) pIter++;
136342 pDL->pNextDocid = pIter;
136343 assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
136344 *pbEof = 0;
136349 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
136351 typedef struct TokenDoclist TokenDoclist;
136352 struct TokenDoclist {
136353 int bIgnore;
136354 sqlite3_int64 iDocid;
136355 char *pList;
136356 int nList;
136360 ** Token pToken is an incrementally loaded token that is part of a
136361 ** multi-token phrase. Advance it to the next matching document in the
136362 ** database and populate output variable *p with the details of the new
136363 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
136365 ** If an error occurs, return an SQLite error code. Otherwise, return
136366 ** SQLITE_OK.
136368 static int incrPhraseTokenNext(
136369 Fts3Table *pTab, /* Virtual table handle */
136370 Fts3Phrase *pPhrase, /* Phrase to advance token of */
136371 int iToken, /* Specific token to advance */
136372 TokenDoclist *p, /* OUT: Docid and doclist for new entry */
136373 u8 *pbEof /* OUT: True if iterator is at EOF */
136375 int rc = SQLITE_OK;
136377 if( pPhrase->iDoclistToken==iToken ){
136378 assert( p->bIgnore==0 );
136379 assert( pPhrase->aToken[iToken].pSegcsr==0 );
136380 fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
136381 p->pList = pPhrase->doclist.pList;
136382 p->nList = pPhrase->doclist.nList;
136383 p->iDocid = pPhrase->doclist.iDocid;
136384 }else{
136385 Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
136386 assert( pToken->pDeferred==0 );
136387 assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
136388 if( pToken->pSegcsr ){
136389 assert( p->bIgnore==0 );
136390 rc = sqlite3Fts3MsrIncrNext(
136391 pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
136393 if( p->pList==0 ) *pbEof = 1;
136394 }else{
136395 p->bIgnore = 1;
136399 return rc;
136404 ** The phrase iterator passed as the second argument:
136406 ** * features at least one token that uses an incremental doclist, and
136408 ** * does not contain any deferred tokens.
136410 ** Advance it to the next matching documnent in the database and populate
136411 ** the Fts3Doclist.pList and nList fields.
136413 ** If there is no "next" entry and no error occurs, then *pbEof is set to
136414 ** 1 before returning. Otherwise, if no error occurs and the iterator is
136415 ** successfully advanced, *pbEof is set to 0.
136417 ** If an error occurs, return an SQLite error code. Otherwise, return
136418 ** SQLITE_OK.
136420 static int fts3EvalIncrPhraseNext(
136421 Fts3Cursor *pCsr, /* FTS Cursor handle */
136422 Fts3Phrase *p, /* Phrase object to advance to next docid */
136423 u8 *pbEof /* OUT: Set to 1 if EOF */
136425 int rc = SQLITE_OK;
136426 Fts3Doclist *pDL = &p->doclist;
136427 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
136428 u8 bEof = 0;
136430 /* This is only called if it is guaranteed that the phrase has at least
136431 ** one incremental token. In which case the bIncr flag is set. */
136432 assert( p->bIncr==1 );
136434 if( p->nToken==1 && p->bIncr ){
136435 rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
136436 &pDL->iDocid, &pDL->pList, &pDL->nList
136438 if( pDL->pList==0 ) bEof = 1;
136439 }else{
136440 int bDescDoclist = pCsr->bDesc;
136441 struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
136443 memset(a, 0, sizeof(a));
136444 assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
136445 assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
136447 while( bEof==0 ){
136448 int bMaxSet = 0;
136449 sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
136450 int i; /* Used to iterate through tokens */
136452 /* Advance the iterator for each token in the phrase once. */
136453 for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
136454 rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
136455 if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
136456 iMax = a[i].iDocid;
136457 bMaxSet = 1;
136460 assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
136461 assert( rc!=SQLITE_OK || bMaxSet );
136463 /* Keep advancing iterators until they all point to the same document */
136464 for(i=0; i<p->nToken; i++){
136465 while( rc==SQLITE_OK && bEof==0
136466 && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
136468 rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
136469 if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
136470 iMax = a[i].iDocid;
136471 i = 0;
136476 /* Check if the current entries really are a phrase match */
136477 if( bEof==0 ){
136478 int nList = 0;
136479 int nByte = a[p->nToken-1].nList;
136480 char *aDoclist = sqlite3_malloc(nByte+1);
136481 if( !aDoclist ) return SQLITE_NOMEM;
136482 memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
136484 for(i=0; i<(p->nToken-1); i++){
136485 if( a[i].bIgnore==0 ){
136486 char *pL = a[i].pList;
136487 char *pR = aDoclist;
136488 char *pOut = aDoclist;
136489 int nDist = p->nToken-1-i;
136490 int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
136491 if( res==0 ) break;
136492 nList = (int)(pOut - aDoclist);
136495 if( i==(p->nToken-1) ){
136496 pDL->iDocid = iMax;
136497 pDL->pList = aDoclist;
136498 pDL->nList = nList;
136499 pDL->bFreeList = 1;
136500 break;
136502 sqlite3_free(aDoclist);
136507 *pbEof = bEof;
136508 return rc;
136512 ** Attempt to move the phrase iterator to point to the next matching docid.
136513 ** If an error occurs, return an SQLite error code. Otherwise, return
136514 ** SQLITE_OK.
136516 ** If there is no "next" entry and no error occurs, then *pbEof is set to
136517 ** 1 before returning. Otherwise, if no error occurs and the iterator is
136518 ** successfully advanced, *pbEof is set to 0.
136520 static int fts3EvalPhraseNext(
136521 Fts3Cursor *pCsr, /* FTS Cursor handle */
136522 Fts3Phrase *p, /* Phrase object to advance to next docid */
136523 u8 *pbEof /* OUT: Set to 1 if EOF */
136525 int rc = SQLITE_OK;
136526 Fts3Doclist *pDL = &p->doclist;
136527 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
136529 if( p->bIncr ){
136530 rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
136531 }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
136532 sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
136533 &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
136535 pDL->pList = pDL->pNextDocid;
136536 }else{
136537 fts3EvalDlPhraseNext(pTab, pDL, pbEof);
136540 return rc;
136545 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
136546 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
136547 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
136548 ** expressions for which all descendent tokens are deferred.
136550 ** If parameter bOptOk is zero, then it is guaranteed that the
136551 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
136552 ** each phrase in the expression (subject to deferred token processing).
136553 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
136554 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
136556 ** If an error occurs within this function, *pRc is set to an SQLite error
136557 ** code before returning.
136559 static void fts3EvalStartReaders(
136560 Fts3Cursor *pCsr, /* FTS Cursor handle */
136561 Fts3Expr *pExpr, /* Expression to initialize phrases in */
136562 int *pRc /* IN/OUT: Error code */
136564 if( pExpr && SQLITE_OK==*pRc ){
136565 if( pExpr->eType==FTSQUERY_PHRASE ){
136566 int i;
136567 int nToken = pExpr->pPhrase->nToken;
136568 for(i=0; i<nToken; i++){
136569 if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
136571 pExpr->bDeferred = (i==nToken);
136572 *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
136573 }else{
136574 fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
136575 fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
136576 pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
136582 ** An array of the following structures is assembled as part of the process
136583 ** of selecting tokens to defer before the query starts executing (as part
136584 ** of the xFilter() method). There is one element in the array for each
136585 ** token in the FTS expression.
136587 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
136588 ** to phrases that are connected only by AND and NEAR operators (not OR or
136589 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
136590 ** separately. The root of a tokens AND/NEAR cluster is stored in
136591 ** Fts3TokenAndCost.pRoot.
136593 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
136594 struct Fts3TokenAndCost {
136595 Fts3Phrase *pPhrase; /* The phrase the token belongs to */
136596 int iToken; /* Position of token in phrase */
136597 Fts3PhraseToken *pToken; /* The token itself */
136598 Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
136599 int nOvfl; /* Number of overflow pages to load doclist */
136600 int iCol; /* The column the token must match */
136604 ** This function is used to populate an allocated Fts3TokenAndCost array.
136606 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
136607 ** Otherwise, if an error occurs during execution, *pRc is set to an
136608 ** SQLite error code.
136610 static void fts3EvalTokenCosts(
136611 Fts3Cursor *pCsr, /* FTS Cursor handle */
136612 Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
136613 Fts3Expr *pExpr, /* Expression to consider */
136614 Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
136615 Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
136616 int *pRc /* IN/OUT: Error code */
136618 if( *pRc==SQLITE_OK ){
136619 if( pExpr->eType==FTSQUERY_PHRASE ){
136620 Fts3Phrase *pPhrase = pExpr->pPhrase;
136621 int i;
136622 for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
136623 Fts3TokenAndCost *pTC = (*ppTC)++;
136624 pTC->pPhrase = pPhrase;
136625 pTC->iToken = i;
136626 pTC->pRoot = pRoot;
136627 pTC->pToken = &pPhrase->aToken[i];
136628 pTC->iCol = pPhrase->iColumn;
136629 *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
136631 }else if( pExpr->eType!=FTSQUERY_NOT ){
136632 assert( pExpr->eType==FTSQUERY_OR
136633 || pExpr->eType==FTSQUERY_AND
136634 || pExpr->eType==FTSQUERY_NEAR
136636 assert( pExpr->pLeft && pExpr->pRight );
136637 if( pExpr->eType==FTSQUERY_OR ){
136638 pRoot = pExpr->pLeft;
136639 **ppOr = pRoot;
136640 (*ppOr)++;
136642 fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
136643 if( pExpr->eType==FTSQUERY_OR ){
136644 pRoot = pExpr->pRight;
136645 **ppOr = pRoot;
136646 (*ppOr)++;
136648 fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
136654 ** Determine the average document (row) size in pages. If successful,
136655 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
136656 ** an SQLite error code.
136658 ** The average document size in pages is calculated by first calculating
136659 ** determining the average size in bytes, B. If B is less than the amount
136660 ** of data that will fit on a single leaf page of an intkey table in
136661 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
136662 ** the number of overflow pages consumed by a record B bytes in size.
136664 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
136665 if( pCsr->nRowAvg==0 ){
136666 /* The average document size, which is required to calculate the cost
136667 ** of each doclist, has not yet been determined. Read the required
136668 ** data from the %_stat table to calculate it.
136670 ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
136671 ** varints, where nCol is the number of columns in the FTS3 table.
136672 ** The first varint is the number of documents currently stored in
136673 ** the table. The following nCol varints contain the total amount of
136674 ** data stored in all rows of each column of the table, from left
136675 ** to right.
136677 int rc;
136678 Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
136679 sqlite3_stmt *pStmt;
136680 sqlite3_int64 nDoc = 0;
136681 sqlite3_int64 nByte = 0;
136682 const char *pEnd;
136683 const char *a;
136685 rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
136686 if( rc!=SQLITE_OK ) return rc;
136687 a = sqlite3_column_blob(pStmt, 0);
136688 assert( a );
136690 pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
136691 a += sqlite3Fts3GetVarint(a, &nDoc);
136692 while( a<pEnd ){
136693 a += sqlite3Fts3GetVarint(a, &nByte);
136695 if( nDoc==0 || nByte==0 ){
136696 sqlite3_reset(pStmt);
136697 return FTS_CORRUPT_VTAB;
136700 pCsr->nDoc = nDoc;
136701 pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
136702 assert( pCsr->nRowAvg>0 );
136703 rc = sqlite3_reset(pStmt);
136704 if( rc!=SQLITE_OK ) return rc;
136707 *pnPage = pCsr->nRowAvg;
136708 return SQLITE_OK;
136712 ** This function is called to select the tokens (if any) that will be
136713 ** deferred. The array aTC[] has already been populated when this is
136714 ** called.
136716 ** This function is called once for each AND/NEAR cluster in the
136717 ** expression. Each invocation determines which tokens to defer within
136718 ** the cluster with root node pRoot. See comments above the definition
136719 ** of struct Fts3TokenAndCost for more details.
136721 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
136722 ** called on each token to defer. Otherwise, an SQLite error code is
136723 ** returned.
136725 static int fts3EvalSelectDeferred(
136726 Fts3Cursor *pCsr, /* FTS Cursor handle */
136727 Fts3Expr *pRoot, /* Consider tokens with this root node */
136728 Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
136729 int nTC /* Number of entries in aTC[] */
136731 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
136732 int nDocSize = 0; /* Number of pages per doc loaded */
136733 int rc = SQLITE_OK; /* Return code */
136734 int ii; /* Iterator variable for various purposes */
136735 int nOvfl = 0; /* Total overflow pages used by doclists */
136736 int nToken = 0; /* Total number of tokens in cluster */
136738 int nMinEst = 0; /* The minimum count for any phrase so far. */
136739 int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
136741 /* Tokens are never deferred for FTS tables created using the content=xxx
136742 ** option. The reason being that it is not guaranteed that the content
136743 ** table actually contains the same data as the index. To prevent this from
136744 ** causing any problems, the deferred token optimization is completely
136745 ** disabled for content=xxx tables. */
136746 if( pTab->zContentTbl ){
136747 return SQLITE_OK;
136750 /* Count the tokens in this AND/NEAR cluster. If none of the doclists
136751 ** associated with the tokens spill onto overflow pages, or if there is
136752 ** only 1 token, exit early. No tokens to defer in this case. */
136753 for(ii=0; ii<nTC; ii++){
136754 if( aTC[ii].pRoot==pRoot ){
136755 nOvfl += aTC[ii].nOvfl;
136756 nToken++;
136759 if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
136761 /* Obtain the average docsize (in pages). */
136762 rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
136763 assert( rc!=SQLITE_OK || nDocSize>0 );
136766 /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
136767 ** of the number of overflow pages that will be loaded by the pager layer
136768 ** to retrieve the entire doclist for the token from the full-text index.
136769 ** Load the doclists for tokens that are either:
136771 ** a. The cheapest token in the entire query (i.e. the one visited by the
136772 ** first iteration of this loop), or
136774 ** b. Part of a multi-token phrase.
136776 ** After each token doclist is loaded, merge it with the others from the
136777 ** same phrase and count the number of documents that the merged doclist
136778 ** contains. Set variable "nMinEst" to the smallest number of documents in
136779 ** any phrase doclist for which 1 or more token doclists have been loaded.
136780 ** Let nOther be the number of other phrases for which it is certain that
136781 ** one or more tokens will not be deferred.
136783 ** Then, for each token, defer it if loading the doclist would result in
136784 ** loading N or more overflow pages into memory, where N is computed as:
136786 ** (nMinEst + 4^nOther - 1) / (4^nOther)
136788 for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
136789 int iTC; /* Used to iterate through aTC[] array. */
136790 Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
136792 /* Set pTC to point to the cheapest remaining token. */
136793 for(iTC=0; iTC<nTC; iTC++){
136794 if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
136795 && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
136797 pTC = &aTC[iTC];
136800 assert( pTC );
136802 if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
136803 /* The number of overflow pages to load for this (and therefore all
136804 ** subsequent) tokens is greater than the estimated number of pages
136805 ** that will be loaded if all subsequent tokens are deferred.
136807 Fts3PhraseToken *pToken = pTC->pToken;
136808 rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
136809 fts3SegReaderCursorFree(pToken->pSegcsr);
136810 pToken->pSegcsr = 0;
136811 }else{
136812 /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
136813 ** for-loop. Except, limit the value to 2^24 to prevent it from
136814 ** overflowing the 32-bit integer it is stored in. */
136815 if( ii<12 ) nLoad4 = nLoad4*4;
136817 if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
136818 /* Either this is the cheapest token in the entire query, or it is
136819 ** part of a multi-token phrase. Either way, the entire doclist will
136820 ** (eventually) be loaded into memory. It may as well be now. */
136821 Fts3PhraseToken *pToken = pTC->pToken;
136822 int nList = 0;
136823 char *pList = 0;
136824 rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
136825 assert( rc==SQLITE_OK || pList==0 );
136826 if( rc==SQLITE_OK ){
136827 int nCount;
136828 fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
136829 nCount = fts3DoclistCountDocids(
136830 pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
136832 if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
136836 pTC->pToken = 0;
136839 return rc;
136843 ** This function is called from within the xFilter method. It initializes
136844 ** the full-text query currently stored in pCsr->pExpr. To iterate through
136845 ** the results of a query, the caller does:
136847 ** fts3EvalStart(pCsr);
136848 ** while( 1 ){
136849 ** fts3EvalNext(pCsr);
136850 ** if( pCsr->bEof ) break;
136851 ** ... return row pCsr->iPrevId to the caller ...
136854 static int fts3EvalStart(Fts3Cursor *pCsr){
136855 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
136856 int rc = SQLITE_OK;
136857 int nToken = 0;
136858 int nOr = 0;
136860 /* Allocate a MultiSegReader for each token in the expression. */
136861 fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
136863 /* Determine which, if any, tokens in the expression should be deferred. */
136864 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
136865 if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
136866 Fts3TokenAndCost *aTC;
136867 Fts3Expr **apOr;
136868 aTC = (Fts3TokenAndCost *)sqlite3_malloc(
136869 sizeof(Fts3TokenAndCost) * nToken
136870 + sizeof(Fts3Expr *) * nOr * 2
136872 apOr = (Fts3Expr **)&aTC[nToken];
136874 if( !aTC ){
136875 rc = SQLITE_NOMEM;
136876 }else{
136877 int ii;
136878 Fts3TokenAndCost *pTC = aTC;
136879 Fts3Expr **ppOr = apOr;
136881 fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
136882 nToken = (int)(pTC-aTC);
136883 nOr = (int)(ppOr-apOr);
136885 if( rc==SQLITE_OK ){
136886 rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
136887 for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
136888 rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
136892 sqlite3_free(aTC);
136895 #endif
136897 fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
136898 return rc;
136902 ** Invalidate the current position list for phrase pPhrase.
136904 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
136905 if( pPhrase->doclist.bFreeList ){
136906 sqlite3_free(pPhrase->doclist.pList);
136908 pPhrase->doclist.pList = 0;
136909 pPhrase->doclist.nList = 0;
136910 pPhrase->doclist.bFreeList = 0;
136914 ** This function is called to edit the position list associated with
136915 ** the phrase object passed as the fifth argument according to a NEAR
136916 ** condition. For example:
136918 ** abc NEAR/5 "def ghi"
136920 ** Parameter nNear is passed the NEAR distance of the expression (5 in
136921 ** the example above). When this function is called, *paPoslist points to
136922 ** the position list, and *pnToken is the number of phrase tokens in, the
136923 ** phrase on the other side of the NEAR operator to pPhrase. For example,
136924 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
136925 ** the position list associated with phrase "abc".
136927 ** All positions in the pPhrase position list that are not sufficiently
136928 ** close to a position in the *paPoslist position list are removed. If this
136929 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
136931 ** Before returning, *paPoslist is set to point to the position lsit
136932 ** associated with pPhrase. And *pnToken is set to the number of tokens in
136933 ** pPhrase.
136935 static int fts3EvalNearTrim(
136936 int nNear, /* NEAR distance. As in "NEAR/nNear". */
136937 char *aTmp, /* Temporary space to use */
136938 char **paPoslist, /* IN/OUT: Position list */
136939 int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
136940 Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
136942 int nParam1 = nNear + pPhrase->nToken;
136943 int nParam2 = nNear + *pnToken;
136944 int nNew;
136945 char *p2;
136946 char *pOut;
136947 int res;
136949 assert( pPhrase->doclist.pList );
136951 p2 = pOut = pPhrase->doclist.pList;
136952 res = fts3PoslistNearMerge(
136953 &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
136955 if( res ){
136956 nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
136957 assert( pPhrase->doclist.pList[nNew]=='\0' );
136958 assert( nNew<=pPhrase->doclist.nList && nNew>0 );
136959 memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
136960 pPhrase->doclist.nList = nNew;
136961 *paPoslist = pPhrase->doclist.pList;
136962 *pnToken = pPhrase->nToken;
136965 return res;
136969 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
136970 ** Otherwise, it advances the expression passed as the second argument to
136971 ** point to the next matching row in the database. Expressions iterate through
136972 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
136973 ** or descending if it is non-zero.
136975 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
136976 ** successful, the following variables in pExpr are set:
136978 ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
136979 ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
136981 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
136982 ** at EOF, then the following variables are populated with the position list
136983 ** for the phrase for the visited row:
136985 ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
136986 ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
136988 ** It says above that this function advances the expression to the next
136989 ** matching row. This is usually true, but there are the following exceptions:
136991 ** 1. Deferred tokens are not taken into account. If a phrase consists
136992 ** entirely of deferred tokens, it is assumed to match every row in
136993 ** the db. In this case the position-list is not populated at all.
136995 ** Or, if a phrase contains one or more deferred tokens and one or
136996 ** more non-deferred tokens, then the expression is advanced to the
136997 ** next possible match, considering only non-deferred tokens. In other
136998 ** words, if the phrase is "A B C", and "B" is deferred, the expression
136999 ** is advanced to the next row that contains an instance of "A * C",
137000 ** where "*" may match any single token. The position list in this case
137001 ** is populated as for "A * C" before returning.
137003 ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
137004 ** advanced to point to the next row that matches "x AND y".
137006 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
137007 ** really a match, taking into account deferred tokens and NEAR operators.
137009 static void fts3EvalNextRow(
137010 Fts3Cursor *pCsr, /* FTS Cursor handle */
137011 Fts3Expr *pExpr, /* Expr. to advance to next matching row */
137012 int *pRc /* IN/OUT: Error code */
137014 if( *pRc==SQLITE_OK ){
137015 int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
137016 assert( pExpr->bEof==0 );
137017 pExpr->bStart = 1;
137019 switch( pExpr->eType ){
137020 case FTSQUERY_NEAR:
137021 case FTSQUERY_AND: {
137022 Fts3Expr *pLeft = pExpr->pLeft;
137023 Fts3Expr *pRight = pExpr->pRight;
137024 assert( !pLeft->bDeferred || !pRight->bDeferred );
137026 if( pLeft->bDeferred ){
137027 /* LHS is entirely deferred. So we assume it matches every row.
137028 ** Advance the RHS iterator to find the next row visited. */
137029 fts3EvalNextRow(pCsr, pRight, pRc);
137030 pExpr->iDocid = pRight->iDocid;
137031 pExpr->bEof = pRight->bEof;
137032 }else if( pRight->bDeferred ){
137033 /* RHS is entirely deferred. So we assume it matches every row.
137034 ** Advance the LHS iterator to find the next row visited. */
137035 fts3EvalNextRow(pCsr, pLeft, pRc);
137036 pExpr->iDocid = pLeft->iDocid;
137037 pExpr->bEof = pLeft->bEof;
137038 }else{
137039 /* Neither the RHS or LHS are deferred. */
137040 fts3EvalNextRow(pCsr, pLeft, pRc);
137041 fts3EvalNextRow(pCsr, pRight, pRc);
137042 while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
137043 sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
137044 if( iDiff==0 ) break;
137045 if( iDiff<0 ){
137046 fts3EvalNextRow(pCsr, pLeft, pRc);
137047 }else{
137048 fts3EvalNextRow(pCsr, pRight, pRc);
137051 pExpr->iDocid = pLeft->iDocid;
137052 pExpr->bEof = (pLeft->bEof || pRight->bEof);
137054 break;
137057 case FTSQUERY_OR: {
137058 Fts3Expr *pLeft = pExpr->pLeft;
137059 Fts3Expr *pRight = pExpr->pRight;
137060 sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
137062 assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
137063 assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
137065 if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
137066 fts3EvalNextRow(pCsr, pLeft, pRc);
137067 }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
137068 fts3EvalNextRow(pCsr, pRight, pRc);
137069 }else{
137070 fts3EvalNextRow(pCsr, pLeft, pRc);
137071 fts3EvalNextRow(pCsr, pRight, pRc);
137074 pExpr->bEof = (pLeft->bEof && pRight->bEof);
137075 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
137076 if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
137077 pExpr->iDocid = pLeft->iDocid;
137078 }else{
137079 pExpr->iDocid = pRight->iDocid;
137082 break;
137085 case FTSQUERY_NOT: {
137086 Fts3Expr *pLeft = pExpr->pLeft;
137087 Fts3Expr *pRight = pExpr->pRight;
137089 if( pRight->bStart==0 ){
137090 fts3EvalNextRow(pCsr, pRight, pRc);
137091 assert( *pRc!=SQLITE_OK || pRight->bStart );
137094 fts3EvalNextRow(pCsr, pLeft, pRc);
137095 if( pLeft->bEof==0 ){
137096 while( !*pRc
137097 && !pRight->bEof
137098 && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
137100 fts3EvalNextRow(pCsr, pRight, pRc);
137103 pExpr->iDocid = pLeft->iDocid;
137104 pExpr->bEof = pLeft->bEof;
137105 break;
137108 default: {
137109 Fts3Phrase *pPhrase = pExpr->pPhrase;
137110 fts3EvalInvalidatePoslist(pPhrase);
137111 *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
137112 pExpr->iDocid = pPhrase->doclist.iDocid;
137113 break;
137120 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
137121 ** cluster, then this function returns 1 immediately.
137123 ** Otherwise, it checks if the current row really does match the NEAR
137124 ** expression, using the data currently stored in the position lists
137125 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
137127 ** If the current row is a match, the position list associated with each
137128 ** phrase in the NEAR expression is edited in place to contain only those
137129 ** phrase instances sufficiently close to their peers to satisfy all NEAR
137130 ** constraints. In this case it returns 1. If the NEAR expression does not
137131 ** match the current row, 0 is returned. The position lists may or may not
137132 ** be edited if 0 is returned.
137134 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
137135 int res = 1;
137137 /* The following block runs if pExpr is the root of a NEAR query.
137138 ** For example, the query:
137140 ** "w" NEAR "x" NEAR "y" NEAR "z"
137142 ** which is represented in tree form as:
137145 ** +--NEAR--+ <-- root of NEAR query
137146 ** | |
137147 ** +--NEAR--+ "z"
137148 ** | |
137149 ** +--NEAR--+ "y"
137150 ** | |
137151 ** "w" "x"
137153 ** The right-hand child of a NEAR node is always a phrase. The
137154 ** left-hand child may be either a phrase or a NEAR node. There are
137155 ** no exceptions to this - it's the way the parser in fts3_expr.c works.
137157 if( *pRc==SQLITE_OK
137158 && pExpr->eType==FTSQUERY_NEAR
137159 && pExpr->bEof==0
137160 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
137162 Fts3Expr *p;
137163 int nTmp = 0; /* Bytes of temp space */
137164 char *aTmp; /* Temp space for PoslistNearMerge() */
137166 /* Allocate temporary working space. */
137167 for(p=pExpr; p->pLeft; p=p->pLeft){
137168 nTmp += p->pRight->pPhrase->doclist.nList;
137170 nTmp += p->pPhrase->doclist.nList;
137171 if( nTmp==0 ){
137172 res = 0;
137173 }else{
137174 aTmp = sqlite3_malloc(nTmp*2);
137175 if( !aTmp ){
137176 *pRc = SQLITE_NOMEM;
137177 res = 0;
137178 }else{
137179 char *aPoslist = p->pPhrase->doclist.pList;
137180 int nToken = p->pPhrase->nToken;
137182 for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
137183 Fts3Phrase *pPhrase = p->pRight->pPhrase;
137184 int nNear = p->nNear;
137185 res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
137188 aPoslist = pExpr->pRight->pPhrase->doclist.pList;
137189 nToken = pExpr->pRight->pPhrase->nToken;
137190 for(p=pExpr->pLeft; p && res; p=p->pLeft){
137191 int nNear;
137192 Fts3Phrase *pPhrase;
137193 assert( p->pParent && p->pParent->pLeft==p );
137194 nNear = p->pParent->nNear;
137195 pPhrase = (
137196 p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
137198 res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
137202 sqlite3_free(aTmp);
137206 return res;
137210 ** This function is a helper function for fts3EvalTestDeferredAndNear().
137211 ** Assuming no error occurs or has occurred, It returns non-zero if the
137212 ** expression passed as the second argument matches the row that pCsr
137213 ** currently points to, or zero if it does not.
137215 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
137216 ** If an error occurs during execution of this function, *pRc is set to
137217 ** the appropriate SQLite error code. In this case the returned value is
137218 ** undefined.
137220 static int fts3EvalTestExpr(
137221 Fts3Cursor *pCsr, /* FTS cursor handle */
137222 Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
137223 int *pRc /* IN/OUT: Error code */
137225 int bHit = 1; /* Return value */
137226 if( *pRc==SQLITE_OK ){
137227 switch( pExpr->eType ){
137228 case FTSQUERY_NEAR:
137229 case FTSQUERY_AND:
137230 bHit = (
137231 fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
137232 && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
137233 && fts3EvalNearTest(pExpr, pRc)
137236 /* If the NEAR expression does not match any rows, zero the doclist for
137237 ** all phrases involved in the NEAR. This is because the snippet(),
137238 ** offsets() and matchinfo() functions are not supposed to recognize
137239 ** any instances of phrases that are part of unmatched NEAR queries.
137240 ** For example if this expression:
137242 ** ... MATCH 'a OR (b NEAR c)'
137244 ** is matched against a row containing:
137246 ** 'a b d e'
137248 ** then any snippet() should ony highlight the "a" term, not the "b"
137249 ** (as "b" is part of a non-matching NEAR clause).
137251 if( bHit==0
137252 && pExpr->eType==FTSQUERY_NEAR
137253 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
137255 Fts3Expr *p;
137256 for(p=pExpr; p->pPhrase==0; p=p->pLeft){
137257 if( p->pRight->iDocid==pCsr->iPrevId ){
137258 fts3EvalInvalidatePoslist(p->pRight->pPhrase);
137261 if( p->iDocid==pCsr->iPrevId ){
137262 fts3EvalInvalidatePoslist(p->pPhrase);
137266 break;
137268 case FTSQUERY_OR: {
137269 int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
137270 int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
137271 bHit = bHit1 || bHit2;
137272 break;
137275 case FTSQUERY_NOT:
137276 bHit = (
137277 fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
137278 && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
137280 break;
137282 default: {
137283 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
137284 if( pCsr->pDeferred
137285 && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
137287 Fts3Phrase *pPhrase = pExpr->pPhrase;
137288 assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
137289 if( pExpr->bDeferred ){
137290 fts3EvalInvalidatePoslist(pPhrase);
137292 *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
137293 bHit = (pPhrase->doclist.pList!=0);
137294 pExpr->iDocid = pCsr->iPrevId;
137295 }else
137296 #endif
137298 bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
137300 break;
137304 return bHit;
137308 ** This function is called as the second part of each xNext operation when
137309 ** iterating through the results of a full-text query. At this point the
137310 ** cursor points to a row that matches the query expression, with the
137311 ** following caveats:
137313 ** * Up until this point, "NEAR" operators in the expression have been
137314 ** treated as "AND".
137316 ** * Deferred tokens have not yet been considered.
137318 ** If *pRc is not SQLITE_OK when this function is called, it immediately
137319 ** returns 0. Otherwise, it tests whether or not after considering NEAR
137320 ** operators and deferred tokens the current row is still a match for the
137321 ** expression. It returns 1 if both of the following are true:
137323 ** 1. *pRc is SQLITE_OK when this function returns, and
137325 ** 2. After scanning the current FTS table row for the deferred tokens,
137326 ** it is determined that the row does *not* match the query.
137328 ** Or, if no error occurs and it seems the current row does match the FTS
137329 ** query, return 0.
137331 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
137332 int rc = *pRc;
137333 int bMiss = 0;
137334 if( rc==SQLITE_OK ){
137336 /* If there are one or more deferred tokens, load the current row into
137337 ** memory and scan it to determine the position list for each deferred
137338 ** token. Then, see if this row is really a match, considering deferred
137339 ** tokens and NEAR operators (neither of which were taken into account
137340 ** earlier, by fts3EvalNextRow()).
137342 if( pCsr->pDeferred ){
137343 rc = fts3CursorSeek(0, pCsr);
137344 if( rc==SQLITE_OK ){
137345 rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
137348 bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
137350 /* Free the position-lists accumulated for each deferred token above. */
137351 sqlite3Fts3FreeDeferredDoclists(pCsr);
137352 *pRc = rc;
137354 return (rc==SQLITE_OK && bMiss);
137358 ** Advance to the next document that matches the FTS expression in
137359 ** Fts3Cursor.pExpr.
137361 static int fts3EvalNext(Fts3Cursor *pCsr){
137362 int rc = SQLITE_OK; /* Return Code */
137363 Fts3Expr *pExpr = pCsr->pExpr;
137364 assert( pCsr->isEof==0 );
137365 if( pExpr==0 ){
137366 pCsr->isEof = 1;
137367 }else{
137369 if( pCsr->isRequireSeek==0 ){
137370 sqlite3_reset(pCsr->pStmt);
137372 assert( sqlite3_data_count(pCsr->pStmt)==0 );
137373 fts3EvalNextRow(pCsr, pExpr, &rc);
137374 pCsr->isEof = pExpr->bEof;
137375 pCsr->isRequireSeek = 1;
137376 pCsr->isMatchinfoNeeded = 1;
137377 pCsr->iPrevId = pExpr->iDocid;
137378 }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
137381 /* Check if the cursor is past the end of the docid range specified
137382 ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
137383 if( rc==SQLITE_OK && (
137384 (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
137385 || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
137387 pCsr->isEof = 1;
137390 return rc;
137394 ** Restart interation for expression pExpr so that the next call to
137395 ** fts3EvalNext() visits the first row. Do not allow incremental
137396 ** loading or merging of phrase doclists for this iteration.
137398 ** If *pRc is other than SQLITE_OK when this function is called, it is
137399 ** a no-op. If an error occurs within this function, *pRc is set to an
137400 ** SQLite error code before returning.
137402 static void fts3EvalRestart(
137403 Fts3Cursor *pCsr,
137404 Fts3Expr *pExpr,
137405 int *pRc
137407 if( pExpr && *pRc==SQLITE_OK ){
137408 Fts3Phrase *pPhrase = pExpr->pPhrase;
137410 if( pPhrase ){
137411 fts3EvalInvalidatePoslist(pPhrase);
137412 if( pPhrase->bIncr ){
137413 int i;
137414 for(i=0; i<pPhrase->nToken; i++){
137415 Fts3PhraseToken *pToken = &pPhrase->aToken[i];
137416 assert( pToken->pDeferred==0 );
137417 if( pToken->pSegcsr ){
137418 sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
137421 *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
137423 pPhrase->doclist.pNextDocid = 0;
137424 pPhrase->doclist.iDocid = 0;
137427 pExpr->iDocid = 0;
137428 pExpr->bEof = 0;
137429 pExpr->bStart = 0;
137431 fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
137432 fts3EvalRestart(pCsr, pExpr->pRight, pRc);
137437 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
137438 ** expression rooted at pExpr, the cursor iterates through all rows matched
137439 ** by pExpr, calling this function for each row. This function increments
137440 ** the values in Fts3Expr.aMI[] according to the position-list currently
137441 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
137442 ** expression nodes.
137444 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
137445 if( pExpr ){
137446 Fts3Phrase *pPhrase = pExpr->pPhrase;
137447 if( pPhrase && pPhrase->doclist.pList ){
137448 int iCol = 0;
137449 char *p = pPhrase->doclist.pList;
137451 assert( *p );
137452 while( 1 ){
137453 u8 c = 0;
137454 int iCnt = 0;
137455 while( 0xFE & (*p | c) ){
137456 if( (c&0x80)==0 ) iCnt++;
137457 c = *p++ & 0x80;
137460 /* aMI[iCol*3 + 1] = Number of occurrences
137461 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
137463 pExpr->aMI[iCol*3 + 1] += iCnt;
137464 pExpr->aMI[iCol*3 + 2] += (iCnt>0);
137465 if( *p==0x00 ) break;
137467 p += fts3GetVarint32(p, &iCol);
137471 fts3EvalUpdateCounts(pExpr->pLeft);
137472 fts3EvalUpdateCounts(pExpr->pRight);
137477 ** Expression pExpr must be of type FTSQUERY_PHRASE.
137479 ** If it is not already allocated and populated, this function allocates and
137480 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
137481 ** of a NEAR expression, then it also allocates and populates the same array
137482 ** for all other phrases that are part of the NEAR expression.
137484 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
137485 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
137487 static int fts3EvalGatherStats(
137488 Fts3Cursor *pCsr, /* Cursor object */
137489 Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
137491 int rc = SQLITE_OK; /* Return code */
137493 assert( pExpr->eType==FTSQUERY_PHRASE );
137494 if( pExpr->aMI==0 ){
137495 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
137496 Fts3Expr *pRoot; /* Root of NEAR expression */
137497 Fts3Expr *p; /* Iterator used for several purposes */
137499 sqlite3_int64 iPrevId = pCsr->iPrevId;
137500 sqlite3_int64 iDocid;
137501 u8 bEof;
137503 /* Find the root of the NEAR expression */
137504 pRoot = pExpr;
137505 while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
137506 pRoot = pRoot->pParent;
137508 iDocid = pRoot->iDocid;
137509 bEof = pRoot->bEof;
137510 assert( pRoot->bStart );
137512 /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
137513 for(p=pRoot; p; p=p->pLeft){
137514 Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
137515 assert( pE->aMI==0 );
137516 pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
137517 if( !pE->aMI ) return SQLITE_NOMEM;
137518 memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
137521 fts3EvalRestart(pCsr, pRoot, &rc);
137523 while( pCsr->isEof==0 && rc==SQLITE_OK ){
137526 /* Ensure the %_content statement is reset. */
137527 if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
137528 assert( sqlite3_data_count(pCsr->pStmt)==0 );
137530 /* Advance to the next document */
137531 fts3EvalNextRow(pCsr, pRoot, &rc);
137532 pCsr->isEof = pRoot->bEof;
137533 pCsr->isRequireSeek = 1;
137534 pCsr->isMatchinfoNeeded = 1;
137535 pCsr->iPrevId = pRoot->iDocid;
137536 }while( pCsr->isEof==0
137537 && pRoot->eType==FTSQUERY_NEAR
137538 && fts3EvalTestDeferredAndNear(pCsr, &rc)
137541 if( rc==SQLITE_OK && pCsr->isEof==0 ){
137542 fts3EvalUpdateCounts(pRoot);
137546 pCsr->isEof = 0;
137547 pCsr->iPrevId = iPrevId;
137549 if( bEof ){
137550 pRoot->bEof = bEof;
137551 }else{
137552 /* Caution: pRoot may iterate through docids in ascending or descending
137553 ** order. For this reason, even though it seems more defensive, the
137554 ** do loop can not be written:
137556 ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
137558 fts3EvalRestart(pCsr, pRoot, &rc);
137560 fts3EvalNextRow(pCsr, pRoot, &rc);
137561 assert( pRoot->bEof==0 );
137562 }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
137563 fts3EvalTestDeferredAndNear(pCsr, &rc);
137566 return rc;
137570 ** This function is used by the matchinfo() module to query a phrase
137571 ** expression node for the following information:
137573 ** 1. The total number of occurrences of the phrase in each column of
137574 ** the FTS table (considering all rows), and
137576 ** 2. For each column, the number of rows in the table for which the
137577 ** column contains at least one instance of the phrase.
137579 ** If no error occurs, SQLITE_OK is returned and the values for each column
137580 ** written into the array aiOut as follows:
137582 ** aiOut[iCol*3 + 1] = Number of occurrences
137583 ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
137585 ** Caveats:
137587 ** * If a phrase consists entirely of deferred tokens, then all output
137588 ** values are set to the number of documents in the table. In other
137589 ** words we assume that very common tokens occur exactly once in each
137590 ** column of each row of the table.
137592 ** * If a phrase contains some deferred tokens (and some non-deferred
137593 ** tokens), count the potential occurrence identified by considering
137594 ** the non-deferred tokens instead of actual phrase occurrences.
137596 ** * If the phrase is part of a NEAR expression, then only phrase instances
137597 ** that meet the NEAR constraint are included in the counts.
137599 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
137600 Fts3Cursor *pCsr, /* FTS cursor handle */
137601 Fts3Expr *pExpr, /* Phrase expression */
137602 u32 *aiOut /* Array to write results into (see above) */
137604 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
137605 int rc = SQLITE_OK;
137606 int iCol;
137608 if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
137609 assert( pCsr->nDoc>0 );
137610 for(iCol=0; iCol<pTab->nColumn; iCol++){
137611 aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
137612 aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
137614 }else{
137615 rc = fts3EvalGatherStats(pCsr, pExpr);
137616 if( rc==SQLITE_OK ){
137617 assert( pExpr->aMI );
137618 for(iCol=0; iCol<pTab->nColumn; iCol++){
137619 aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
137620 aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
137625 return rc;
137629 ** The expression pExpr passed as the second argument to this function
137630 ** must be of type FTSQUERY_PHRASE.
137632 ** The returned value is either NULL or a pointer to a buffer containing
137633 ** a position-list indicating the occurrences of the phrase in column iCol
137634 ** of the current row.
137636 ** More specifically, the returned buffer contains 1 varint for each
137637 ** occurrence of the phrase in the column, stored using the normal (delta+2)
137638 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
137639 ** if the requested column contains "a b X c d X X" and the position-list
137640 ** for 'X' is requested, the buffer returned may contain:
137642 ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
137644 ** This function works regardless of whether or not the phrase is deferred,
137645 ** incremental, or neither.
137647 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
137648 Fts3Cursor *pCsr, /* FTS3 cursor object */
137649 Fts3Expr *pExpr, /* Phrase to return doclist for */
137650 int iCol, /* Column to return position list for */
137651 char **ppOut /* OUT: Pointer to position list */
137653 Fts3Phrase *pPhrase = pExpr->pPhrase;
137654 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
137655 char *pIter;
137656 int iThis;
137657 sqlite3_int64 iDocid;
137659 /* If this phrase is applies specifically to some column other than
137660 ** column iCol, return a NULL pointer. */
137661 *ppOut = 0;
137662 assert( iCol>=0 && iCol<pTab->nColumn );
137663 if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
137664 return SQLITE_OK;
137667 iDocid = pExpr->iDocid;
137668 pIter = pPhrase->doclist.pList;
137669 if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
137670 int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
137671 int iMul; /* +1 if csr dir matches index dir, else -1 */
137672 int bOr = 0;
137673 u8 bEof = 0;
137674 u8 bTreeEof = 0;
137675 Fts3Expr *p; /* Used to iterate from pExpr to root */
137676 Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
137678 /* Check if this phrase descends from an OR expression node. If not,
137679 ** return NULL. Otherwise, the entry that corresponds to docid
137680 ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
137681 ** tree that the node is part of has been marked as EOF, but the node
137682 ** itself is not EOF, then it may point to an earlier entry. */
137683 pNear = pExpr;
137684 for(p=pExpr->pParent; p; p=p->pParent){
137685 if( p->eType==FTSQUERY_OR ) bOr = 1;
137686 if( p->eType==FTSQUERY_NEAR ) pNear = p;
137687 if( p->bEof ) bTreeEof = 1;
137689 if( bOr==0 ) return SQLITE_OK;
137691 /* This is the descendent of an OR node. In this case we cannot use
137692 ** an incremental phrase. Load the entire doclist for the phrase
137693 ** into memory in this case. */
137694 if( pPhrase->bIncr ){
137695 int rc = SQLITE_OK;
137696 int bEofSave = pExpr->bEof;
137697 fts3EvalRestart(pCsr, pExpr, &rc);
137698 while( rc==SQLITE_OK && !pExpr->bEof ){
137699 fts3EvalNextRow(pCsr, pExpr, &rc);
137700 if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
137702 pIter = pPhrase->doclist.pList;
137703 assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
137704 if( rc!=SQLITE_OK ) return rc;
137707 iMul = ((pCsr->bDesc==bDescDoclist) ? 1 : -1);
137708 while( bTreeEof==1
137709 && pNear->bEof==0
137710 && (DOCID_CMP(pNear->iDocid, pCsr->iPrevId) * iMul)<0
137712 int rc = SQLITE_OK;
137713 fts3EvalNextRow(pCsr, pExpr, &rc);
137714 if( rc!=SQLITE_OK ) return rc;
137715 iDocid = pExpr->iDocid;
137716 pIter = pPhrase->doclist.pList;
137719 bEof = (pPhrase->doclist.nAll==0);
137720 assert( bDescDoclist==0 || bDescDoclist==1 );
137721 assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
137723 if( bEof==0 ){
137724 if( pCsr->bDesc==bDescDoclist ){
137725 int dummy;
137726 if( pNear->bEof ){
137727 /* This expression is already at EOF. So position it to point to the
137728 ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable
137729 ** iDocid is already set for this entry, so all that is required is
137730 ** to set pIter to point to the first byte of the last position-list
137731 ** in the doclist.
137733 ** It would also be correct to set pIter and iDocid to zero. In
137734 ** this case, the first call to sqltie3Fts4DoclistPrev() below
137735 ** would also move the iterator to point to the last entry in the
137736 ** doclist. However, this is expensive, as to do so it has to
137737 ** iterate through the entire doclist from start to finish (since
137738 ** it does not know the docid for the last entry). */
137739 pIter = &pPhrase->doclist.aAll[pPhrase->doclist.nAll-1];
137740 fts3ReversePoslist(pPhrase->doclist.aAll, &pIter);
137742 while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
137743 sqlite3Fts3DoclistPrev(
137744 bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
137745 &pIter, &iDocid, &dummy, &bEof
137748 }else{
137749 if( pNear->bEof ){
137750 pIter = 0;
137751 iDocid = 0;
137753 while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
137754 sqlite3Fts3DoclistNext(
137755 bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
137756 &pIter, &iDocid, &bEof
137762 if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
137764 if( pIter==0 ) return SQLITE_OK;
137766 if( *pIter==0x01 ){
137767 pIter++;
137768 pIter += fts3GetVarint32(pIter, &iThis);
137769 }else{
137770 iThis = 0;
137772 while( iThis<iCol ){
137773 fts3ColumnlistCopy(0, &pIter);
137774 if( *pIter==0x00 ) return 0;
137775 pIter++;
137776 pIter += fts3GetVarint32(pIter, &iThis);
137779 *ppOut = ((iCol==iThis)?pIter:0);
137780 return SQLITE_OK;
137784 ** Free all components of the Fts3Phrase structure that were allocated by
137785 ** the eval module. Specifically, this means to free:
137787 ** * the contents of pPhrase->doclist, and
137788 ** * any Fts3MultiSegReader objects held by phrase tokens.
137790 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
137791 if( pPhrase ){
137792 int i;
137793 sqlite3_free(pPhrase->doclist.aAll);
137794 fts3EvalInvalidatePoslist(pPhrase);
137795 memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
137796 for(i=0; i<pPhrase->nToken; i++){
137797 fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
137798 pPhrase->aToken[i].pSegcsr = 0;
137805 ** Return SQLITE_CORRUPT_VTAB.
137807 #ifdef SQLITE_DEBUG
137808 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
137809 return SQLITE_CORRUPT_VTAB;
137811 #endif
137813 #if !SQLITE_CORE
137815 ** Initialize API pointer table, if required.
137817 #ifdef _WIN32
137818 __declspec(dllexport)
137819 #endif
137820 SQLITE_API int sqlite3_fts3_init(
137821 sqlite3 *db,
137822 char **pzErrMsg,
137823 const sqlite3_api_routines *pApi
137825 SQLITE_EXTENSION_INIT2(pApi)
137826 return sqlite3Fts3Init(db);
137828 #endif
137830 #endif
137832 /************** End of fts3.c ************************************************/
137833 /************** Begin file fts3_aux.c ****************************************/
137835 ** 2011 Jan 27
137837 ** The author disclaims copyright to this source code. In place of
137838 ** a legal notice, here is a blessing:
137840 ** May you do good and not evil.
137841 ** May you find forgiveness for yourself and forgive others.
137842 ** May you share freely, never taking more than you give.
137844 ******************************************************************************
137847 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
137849 /* #include <string.h> */
137850 /* #include <assert.h> */
137852 typedef struct Fts3auxTable Fts3auxTable;
137853 typedef struct Fts3auxCursor Fts3auxCursor;
137855 struct Fts3auxTable {
137856 sqlite3_vtab base; /* Base class used by SQLite core */
137857 Fts3Table *pFts3Tab;
137860 struct Fts3auxCursor {
137861 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
137862 Fts3MultiSegReader csr; /* Must be right after "base" */
137863 Fts3SegFilter filter;
137864 char *zStop;
137865 int nStop; /* Byte-length of string zStop */
137866 int iLangid; /* Language id to query */
137867 int isEof; /* True if cursor is at EOF */
137868 sqlite3_int64 iRowid; /* Current rowid */
137870 int iCol; /* Current value of 'col' column */
137871 int nStat; /* Size of aStat[] array */
137872 struct Fts3auxColstats {
137873 sqlite3_int64 nDoc; /* 'documents' values for current csr row */
137874 sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
137875 } *aStat;
137879 ** Schema of the terms table.
137881 #define FTS3_AUX_SCHEMA \
137882 "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
137885 ** This function does all the work for both the xConnect and xCreate methods.
137886 ** These tables have no persistent representation of their own, so xConnect
137887 ** and xCreate are identical operations.
137889 static int fts3auxConnectMethod(
137890 sqlite3 *db, /* Database connection */
137891 void *pUnused, /* Unused */
137892 int argc, /* Number of elements in argv array */
137893 const char * const *argv, /* xCreate/xConnect argument array */
137894 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
137895 char **pzErr /* OUT: sqlite3_malloc'd error message */
137897 char const *zDb; /* Name of database (e.g. "main") */
137898 char const *zFts3; /* Name of fts3 table */
137899 int nDb; /* Result of strlen(zDb) */
137900 int nFts3; /* Result of strlen(zFts3) */
137901 int nByte; /* Bytes of space to allocate here */
137902 int rc; /* value returned by declare_vtab() */
137903 Fts3auxTable *p; /* Virtual table object to return */
137905 UNUSED_PARAMETER(pUnused);
137907 /* The user should invoke this in one of two forms:
137909 ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
137910 ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
137912 if( argc!=4 && argc!=5 ) goto bad_args;
137914 zDb = argv[1];
137915 nDb = (int)strlen(zDb);
137916 if( argc==5 ){
137917 if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
137918 zDb = argv[3];
137919 nDb = (int)strlen(zDb);
137920 zFts3 = argv[4];
137921 }else{
137922 goto bad_args;
137924 }else{
137925 zFts3 = argv[3];
137927 nFts3 = (int)strlen(zFts3);
137929 rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
137930 if( rc!=SQLITE_OK ) return rc;
137932 nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
137933 p = (Fts3auxTable *)sqlite3_malloc(nByte);
137934 if( !p ) return SQLITE_NOMEM;
137935 memset(p, 0, nByte);
137937 p->pFts3Tab = (Fts3Table *)&p[1];
137938 p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
137939 p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
137940 p->pFts3Tab->db = db;
137941 p->pFts3Tab->nIndex = 1;
137943 memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
137944 memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
137945 sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
137947 *ppVtab = (sqlite3_vtab *)p;
137948 return SQLITE_OK;
137950 bad_args:
137951 *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
137952 return SQLITE_ERROR;
137956 ** This function does the work for both the xDisconnect and xDestroy methods.
137957 ** These tables have no persistent representation of their own, so xDisconnect
137958 ** and xDestroy are identical operations.
137960 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
137961 Fts3auxTable *p = (Fts3auxTable *)pVtab;
137962 Fts3Table *pFts3 = p->pFts3Tab;
137963 int i;
137965 /* Free any prepared statements held */
137966 for(i=0; i<SizeofArray(pFts3->aStmt); i++){
137967 sqlite3_finalize(pFts3->aStmt[i]);
137969 sqlite3_free(pFts3->zSegmentsTbl);
137970 sqlite3_free(p);
137971 return SQLITE_OK;
137974 #define FTS4AUX_EQ_CONSTRAINT 1
137975 #define FTS4AUX_GE_CONSTRAINT 2
137976 #define FTS4AUX_LE_CONSTRAINT 4
137979 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
137981 static int fts3auxBestIndexMethod(
137982 sqlite3_vtab *pVTab,
137983 sqlite3_index_info *pInfo
137985 int i;
137986 int iEq = -1;
137987 int iGe = -1;
137988 int iLe = -1;
137989 int iLangid = -1;
137990 int iNext = 1; /* Next free argvIndex value */
137992 UNUSED_PARAMETER(pVTab);
137994 /* This vtab delivers always results in "ORDER BY term ASC" order. */
137995 if( pInfo->nOrderBy==1
137996 && pInfo->aOrderBy[0].iColumn==0
137997 && pInfo->aOrderBy[0].desc==0
137999 pInfo->orderByConsumed = 1;
138002 /* Search for equality and range constraints on the "term" column.
138003 ** And equality constraints on the hidden "languageid" column. */
138004 for(i=0; i<pInfo->nConstraint; i++){
138005 if( pInfo->aConstraint[i].usable ){
138006 int op = pInfo->aConstraint[i].op;
138007 int iCol = pInfo->aConstraint[i].iColumn;
138009 if( iCol==0 ){
138010 if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
138011 if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
138012 if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
138013 if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
138014 if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
138016 if( iCol==4 ){
138017 if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
138022 if( iEq>=0 ){
138023 pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
138024 pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
138025 pInfo->estimatedCost = 5;
138026 }else{
138027 pInfo->idxNum = 0;
138028 pInfo->estimatedCost = 20000;
138029 if( iGe>=0 ){
138030 pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
138031 pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
138032 pInfo->estimatedCost /= 2;
138034 if( iLe>=0 ){
138035 pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
138036 pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
138037 pInfo->estimatedCost /= 2;
138040 if( iLangid>=0 ){
138041 pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
138042 pInfo->estimatedCost--;
138045 return SQLITE_OK;
138049 ** xOpen - Open a cursor.
138051 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
138052 Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
138054 UNUSED_PARAMETER(pVTab);
138056 pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
138057 if( !pCsr ) return SQLITE_NOMEM;
138058 memset(pCsr, 0, sizeof(Fts3auxCursor));
138060 *ppCsr = (sqlite3_vtab_cursor *)pCsr;
138061 return SQLITE_OK;
138065 ** xClose - Close a cursor.
138067 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
138068 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
138069 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
138071 sqlite3Fts3SegmentsClose(pFts3);
138072 sqlite3Fts3SegReaderFinish(&pCsr->csr);
138073 sqlite3_free((void *)pCsr->filter.zTerm);
138074 sqlite3_free(pCsr->zStop);
138075 sqlite3_free(pCsr->aStat);
138076 sqlite3_free(pCsr);
138077 return SQLITE_OK;
138080 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
138081 if( nSize>pCsr->nStat ){
138082 struct Fts3auxColstats *aNew;
138083 aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
138084 sizeof(struct Fts3auxColstats) * nSize
138086 if( aNew==0 ) return SQLITE_NOMEM;
138087 memset(&aNew[pCsr->nStat], 0,
138088 sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
138090 pCsr->aStat = aNew;
138091 pCsr->nStat = nSize;
138093 return SQLITE_OK;
138097 ** xNext - Advance the cursor to the next row, if any.
138099 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
138100 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
138101 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
138102 int rc;
138104 /* Increment our pretend rowid value. */
138105 pCsr->iRowid++;
138107 for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
138108 if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
138111 rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
138112 if( rc==SQLITE_ROW ){
138113 int i = 0;
138114 int nDoclist = pCsr->csr.nDoclist;
138115 char *aDoclist = pCsr->csr.aDoclist;
138116 int iCol;
138118 int eState = 0;
138120 if( pCsr->zStop ){
138121 int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
138122 int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
138123 if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
138124 pCsr->isEof = 1;
138125 return SQLITE_OK;
138129 if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
138130 memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
138131 iCol = 0;
138133 while( i<nDoclist ){
138134 sqlite3_int64 v = 0;
138136 i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
138137 switch( eState ){
138138 /* State 0. In this state the integer just read was a docid. */
138139 case 0:
138140 pCsr->aStat[0].nDoc++;
138141 eState = 1;
138142 iCol = 0;
138143 break;
138145 /* State 1. In this state we are expecting either a 1, indicating
138146 ** that the following integer will be a column number, or the
138147 ** start of a position list for column 0.
138149 ** The only difference between state 1 and state 2 is that if the
138150 ** integer encountered in state 1 is not 0 or 1, then we need to
138151 ** increment the column 0 "nDoc" count for this term.
138153 case 1:
138154 assert( iCol==0 );
138155 if( v>1 ){
138156 pCsr->aStat[1].nDoc++;
138158 eState = 2;
138159 /* fall through */
138161 case 2:
138162 if( v==0 ){ /* 0x00. Next integer will be a docid. */
138163 eState = 0;
138164 }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
138165 eState = 3;
138166 }else{ /* 2 or greater. A position. */
138167 pCsr->aStat[iCol+1].nOcc++;
138168 pCsr->aStat[0].nOcc++;
138170 break;
138172 /* State 3. The integer just read is a column number. */
138173 default: assert( eState==3 );
138174 iCol = (int)v;
138175 if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
138176 pCsr->aStat[iCol+1].nDoc++;
138177 eState = 2;
138178 break;
138182 pCsr->iCol = 0;
138183 rc = SQLITE_OK;
138184 }else{
138185 pCsr->isEof = 1;
138187 return rc;
138191 ** xFilter - Initialize a cursor to point at the start of its data.
138193 static int fts3auxFilterMethod(
138194 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
138195 int idxNum, /* Strategy index */
138196 const char *idxStr, /* Unused */
138197 int nVal, /* Number of elements in apVal */
138198 sqlite3_value **apVal /* Arguments for the indexing scheme */
138200 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
138201 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
138202 int rc;
138203 int isScan = 0;
138204 int iLangVal = 0; /* Language id to query */
138206 int iEq = -1; /* Index of term=? value in apVal */
138207 int iGe = -1; /* Index of term>=? value in apVal */
138208 int iLe = -1; /* Index of term<=? value in apVal */
138209 int iLangid = -1; /* Index of languageid=? value in apVal */
138210 int iNext = 0;
138212 UNUSED_PARAMETER(nVal);
138213 UNUSED_PARAMETER(idxStr);
138215 assert( idxStr==0 );
138216 assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
138217 || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
138218 || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
138221 if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
138222 iEq = iNext++;
138223 }else{
138224 isScan = 1;
138225 if( idxNum & FTS4AUX_GE_CONSTRAINT ){
138226 iGe = iNext++;
138228 if( idxNum & FTS4AUX_LE_CONSTRAINT ){
138229 iLe = iNext++;
138232 if( iNext<nVal ){
138233 iLangid = iNext++;
138236 /* In case this cursor is being reused, close and zero it. */
138237 testcase(pCsr->filter.zTerm);
138238 sqlite3Fts3SegReaderFinish(&pCsr->csr);
138239 sqlite3_free((void *)pCsr->filter.zTerm);
138240 sqlite3_free(pCsr->aStat);
138241 memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
138243 pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
138244 if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
138246 if( iEq>=0 || iGe>=0 ){
138247 const unsigned char *zStr = sqlite3_value_text(apVal[0]);
138248 assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
138249 if( zStr ){
138250 pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
138251 pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
138252 if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
138256 if( iLe>=0 ){
138257 pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
138258 pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
138259 if( pCsr->zStop==0 ) return SQLITE_NOMEM;
138262 if( iLangid>=0 ){
138263 iLangVal = sqlite3_value_int(apVal[iLangid]);
138265 /* If the user specified a negative value for the languageid, use zero
138266 ** instead. This works, as the "languageid=?" constraint will also
138267 ** be tested by the VDBE layer. The test will always be false (since
138268 ** this module will not return a row with a negative languageid), and
138269 ** so the overall query will return zero rows. */
138270 if( iLangVal<0 ) iLangVal = 0;
138272 pCsr->iLangid = iLangVal;
138274 rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
138275 pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
138277 if( rc==SQLITE_OK ){
138278 rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
138281 if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
138282 return rc;
138286 ** xEof - Return true if the cursor is at EOF, or false otherwise.
138288 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
138289 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
138290 return pCsr->isEof;
138294 ** xColumn - Return a column value.
138296 static int fts3auxColumnMethod(
138297 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
138298 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
138299 int iCol /* Index of column to read value from */
138301 Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
138303 assert( p->isEof==0 );
138304 switch( iCol ){
138305 case 0: /* term */
138306 sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
138307 break;
138309 case 1: /* col */
138310 if( p->iCol ){
138311 sqlite3_result_int(pCtx, p->iCol-1);
138312 }else{
138313 sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
138315 break;
138317 case 2: /* documents */
138318 sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
138319 break;
138321 case 3: /* occurrences */
138322 sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
138323 break;
138325 default: /* languageid */
138326 assert( iCol==4 );
138327 sqlite3_result_int(pCtx, p->iLangid);
138328 break;
138331 return SQLITE_OK;
138335 ** xRowid - Return the current rowid for the cursor.
138337 static int fts3auxRowidMethod(
138338 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
138339 sqlite_int64 *pRowid /* OUT: Rowid value */
138341 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
138342 *pRowid = pCsr->iRowid;
138343 return SQLITE_OK;
138347 ** Register the fts3aux module with database connection db. Return SQLITE_OK
138348 ** if successful or an error code if sqlite3_create_module() fails.
138350 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
138351 static const sqlite3_module fts3aux_module = {
138352 0, /* iVersion */
138353 fts3auxConnectMethod, /* xCreate */
138354 fts3auxConnectMethod, /* xConnect */
138355 fts3auxBestIndexMethod, /* xBestIndex */
138356 fts3auxDisconnectMethod, /* xDisconnect */
138357 fts3auxDisconnectMethod, /* xDestroy */
138358 fts3auxOpenMethod, /* xOpen */
138359 fts3auxCloseMethod, /* xClose */
138360 fts3auxFilterMethod, /* xFilter */
138361 fts3auxNextMethod, /* xNext */
138362 fts3auxEofMethod, /* xEof */
138363 fts3auxColumnMethod, /* xColumn */
138364 fts3auxRowidMethod, /* xRowid */
138365 0, /* xUpdate */
138366 0, /* xBegin */
138367 0, /* xSync */
138368 0, /* xCommit */
138369 0, /* xRollback */
138370 0, /* xFindFunction */
138371 0, /* xRename */
138372 0, /* xSavepoint */
138373 0, /* xRelease */
138374 0 /* xRollbackTo */
138376 int rc; /* Return code */
138378 rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
138379 return rc;
138382 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
138384 /************** End of fts3_aux.c ********************************************/
138385 /************** Begin file fts3_expr.c ***************************************/
138387 ** 2008 Nov 28
138389 ** The author disclaims copyright to this source code. In place of
138390 ** a legal notice, here is a blessing:
138392 ** May you do good and not evil.
138393 ** May you find forgiveness for yourself and forgive others.
138394 ** May you share freely, never taking more than you give.
138396 ******************************************************************************
138398 ** This module contains code that implements a parser for fts3 query strings
138399 ** (the right-hand argument to the MATCH operator). Because the supported
138400 ** syntax is relatively simple, the whole tokenizer/parser system is
138401 ** hand-coded.
138403 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
138406 ** By default, this module parses the legacy syntax that has been
138407 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
138408 ** is defined, then it uses the new syntax. The differences between
138409 ** the new and the old syntaxes are:
138411 ** a) The new syntax supports parenthesis. The old does not.
138413 ** b) The new syntax supports the AND and NOT operators. The old does not.
138415 ** c) The old syntax supports the "-" token qualifier. This is not
138416 ** supported by the new syntax (it is replaced by the NOT operator).
138418 ** d) When using the old syntax, the OR operator has a greater precedence
138419 ** than an implicit AND. When using the new, both implicity and explicit
138420 ** AND operators have a higher precedence than OR.
138422 ** If compiled with SQLITE_TEST defined, then this module exports the
138423 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
138424 ** to zero causes the module to use the old syntax. If it is set to
138425 ** non-zero the new syntax is activated. This is so both syntaxes can
138426 ** be tested using a single build of testfixture.
138428 ** The following describes the syntax supported by the fts3 MATCH
138429 ** operator in a similar format to that used by the lemon parser
138430 ** generator. This module does not use actually lemon, it uses a
138431 ** custom parser.
138433 ** query ::= andexpr (OR andexpr)*.
138435 ** andexpr ::= notexpr (AND? notexpr)*.
138437 ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
138438 ** notexpr ::= LP query RP.
138440 ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
138442 ** distance_opt ::= .
138443 ** distance_opt ::= / INTEGER.
138445 ** phrase ::= TOKEN.
138446 ** phrase ::= COLUMN:TOKEN.
138447 ** phrase ::= "TOKEN TOKEN TOKEN...".
138450 #ifdef SQLITE_TEST
138451 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
138452 #else
138453 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
138454 # define sqlite3_fts3_enable_parentheses 1
138455 # else
138456 # define sqlite3_fts3_enable_parentheses 0
138457 # endif
138458 #endif
138461 ** Default span for NEAR operators.
138463 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
138465 /* #include <string.h> */
138466 /* #include <assert.h> */
138469 ** isNot:
138470 ** This variable is used by function getNextNode(). When getNextNode() is
138471 ** called, it sets ParseContext.isNot to true if the 'next node' is a
138472 ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
138473 ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
138474 ** zero.
138476 typedef struct ParseContext ParseContext;
138477 struct ParseContext {
138478 sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
138479 int iLangid; /* Language id used with tokenizer */
138480 const char **azCol; /* Array of column names for fts3 table */
138481 int bFts4; /* True to allow FTS4-only syntax */
138482 int nCol; /* Number of entries in azCol[] */
138483 int iDefaultCol; /* Default column to query */
138484 int isNot; /* True if getNextNode() sees a unary - */
138485 sqlite3_context *pCtx; /* Write error message here */
138486 int nNest; /* Number of nested brackets */
138490 ** This function is equivalent to the standard isspace() function.
138492 ** The standard isspace() can be awkward to use safely, because although it
138493 ** is defined to accept an argument of type int, its behavior when passed
138494 ** an integer that falls outside of the range of the unsigned char type
138495 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
138496 ** is defined to accept an argument of type char, and always returns 0 for
138497 ** any values that fall outside of the range of the unsigned char type (i.e.
138498 ** negative values).
138500 static int fts3isspace(char c){
138501 return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
138505 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
138506 ** zero the memory before returning a pointer to it. If unsuccessful,
138507 ** return NULL.
138509 static void *fts3MallocZero(int nByte){
138510 void *pRet = sqlite3_malloc(nByte);
138511 if( pRet ) memset(pRet, 0, nByte);
138512 return pRet;
138515 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
138516 sqlite3_tokenizer *pTokenizer,
138517 int iLangid,
138518 const char *z,
138519 int n,
138520 sqlite3_tokenizer_cursor **ppCsr
138522 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
138523 sqlite3_tokenizer_cursor *pCsr = 0;
138524 int rc;
138526 rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
138527 assert( rc==SQLITE_OK || pCsr==0 );
138528 if( rc==SQLITE_OK ){
138529 pCsr->pTokenizer = pTokenizer;
138530 if( pModule->iVersion>=1 ){
138531 rc = pModule->xLanguageid(pCsr, iLangid);
138532 if( rc!=SQLITE_OK ){
138533 pModule->xClose(pCsr);
138534 pCsr = 0;
138538 *ppCsr = pCsr;
138539 return rc;
138543 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
138544 ** call fts3ExprParse(). So this forward declaration is required.
138546 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
138549 ** Extract the next token from buffer z (length n) using the tokenizer
138550 ** and other information (column names etc.) in pParse. Create an Fts3Expr
138551 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
138552 ** single token and set *ppExpr to point to it. If the end of the buffer is
138553 ** reached before a token is found, set *ppExpr to zero. It is the
138554 ** responsibility of the caller to eventually deallocate the allocated
138555 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
138557 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
138558 ** fails.
138560 static int getNextToken(
138561 ParseContext *pParse, /* fts3 query parse context */
138562 int iCol, /* Value for Fts3Phrase.iColumn */
138563 const char *z, int n, /* Input string */
138564 Fts3Expr **ppExpr, /* OUT: expression */
138565 int *pnConsumed /* OUT: Number of bytes consumed */
138567 sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
138568 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
138569 int rc;
138570 sqlite3_tokenizer_cursor *pCursor;
138571 Fts3Expr *pRet = 0;
138572 int i = 0;
138574 /* Set variable i to the maximum number of bytes of input to tokenize. */
138575 for(i=0; i<n; i++){
138576 if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
138577 if( z[i]=='"' ) break;
138580 *pnConsumed = i;
138581 rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
138582 if( rc==SQLITE_OK ){
138583 const char *zToken;
138584 int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
138585 int nByte; /* total space to allocate */
138587 rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
138588 if( rc==SQLITE_OK ){
138589 nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
138590 pRet = (Fts3Expr *)fts3MallocZero(nByte);
138591 if( !pRet ){
138592 rc = SQLITE_NOMEM;
138593 }else{
138594 pRet->eType = FTSQUERY_PHRASE;
138595 pRet->pPhrase = (Fts3Phrase *)&pRet[1];
138596 pRet->pPhrase->nToken = 1;
138597 pRet->pPhrase->iColumn = iCol;
138598 pRet->pPhrase->aToken[0].n = nToken;
138599 pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
138600 memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
138602 if( iEnd<n && z[iEnd]=='*' ){
138603 pRet->pPhrase->aToken[0].isPrefix = 1;
138604 iEnd++;
138607 while( 1 ){
138608 if( !sqlite3_fts3_enable_parentheses
138609 && iStart>0 && z[iStart-1]=='-'
138611 pParse->isNot = 1;
138612 iStart--;
138613 }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
138614 pRet->pPhrase->aToken[0].bFirst = 1;
138615 iStart--;
138616 }else{
138617 break;
138622 *pnConsumed = iEnd;
138623 }else if( i && rc==SQLITE_DONE ){
138624 rc = SQLITE_OK;
138627 pModule->xClose(pCursor);
138630 *ppExpr = pRet;
138631 return rc;
138636 ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
138637 ** then free the old allocation.
138639 static void *fts3ReallocOrFree(void *pOrig, int nNew){
138640 void *pRet = sqlite3_realloc(pOrig, nNew);
138641 if( !pRet ){
138642 sqlite3_free(pOrig);
138644 return pRet;
138648 ** Buffer zInput, length nInput, contains the contents of a quoted string
138649 ** that appeared as part of an fts3 query expression. Neither quote character
138650 ** is included in the buffer. This function attempts to tokenize the entire
138651 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
138652 ** containing the results.
138654 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
138655 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
138656 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
138657 ** to 0.
138659 static int getNextString(
138660 ParseContext *pParse, /* fts3 query parse context */
138661 const char *zInput, int nInput, /* Input string */
138662 Fts3Expr **ppExpr /* OUT: expression */
138664 sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
138665 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
138666 int rc;
138667 Fts3Expr *p = 0;
138668 sqlite3_tokenizer_cursor *pCursor = 0;
138669 char *zTemp = 0;
138670 int nTemp = 0;
138672 const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
138673 int nToken = 0;
138675 /* The final Fts3Expr data structure, including the Fts3Phrase,
138676 ** Fts3PhraseToken structures token buffers are all stored as a single
138677 ** allocation so that the expression can be freed with a single call to
138678 ** sqlite3_free(). Setting this up requires a two pass approach.
138680 ** The first pass, in the block below, uses a tokenizer cursor to iterate
138681 ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
138682 ** to assemble data in two dynamic buffers:
138684 ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
138685 ** structure, followed by the array of Fts3PhraseToken
138686 ** structures. This pass only populates the Fts3PhraseToken array.
138688 ** Buffer zTemp: Contains copies of all tokens.
138690 ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
138691 ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
138692 ** structures.
138694 rc = sqlite3Fts3OpenTokenizer(
138695 pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
138696 if( rc==SQLITE_OK ){
138697 int ii;
138698 for(ii=0; rc==SQLITE_OK; ii++){
138699 const char *zByte;
138700 int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
138701 rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
138702 if( rc==SQLITE_OK ){
138703 Fts3PhraseToken *pToken;
138705 p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
138706 if( !p ) goto no_mem;
138708 zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
138709 if( !zTemp ) goto no_mem;
138711 assert( nToken==ii );
138712 pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
138713 memset(pToken, 0, sizeof(Fts3PhraseToken));
138715 memcpy(&zTemp[nTemp], zByte, nByte);
138716 nTemp += nByte;
138718 pToken->n = nByte;
138719 pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
138720 pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
138721 nToken = ii+1;
138725 pModule->xClose(pCursor);
138726 pCursor = 0;
138729 if( rc==SQLITE_DONE ){
138730 int jj;
138731 char *zBuf = 0;
138733 p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
138734 if( !p ) goto no_mem;
138735 memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
138736 p->eType = FTSQUERY_PHRASE;
138737 p->pPhrase = (Fts3Phrase *)&p[1];
138738 p->pPhrase->iColumn = pParse->iDefaultCol;
138739 p->pPhrase->nToken = nToken;
138741 zBuf = (char *)&p->pPhrase->aToken[nToken];
138742 if( zTemp ){
138743 memcpy(zBuf, zTemp, nTemp);
138744 sqlite3_free(zTemp);
138745 }else{
138746 assert( nTemp==0 );
138749 for(jj=0; jj<p->pPhrase->nToken; jj++){
138750 p->pPhrase->aToken[jj].z = zBuf;
138751 zBuf += p->pPhrase->aToken[jj].n;
138753 rc = SQLITE_OK;
138756 *ppExpr = p;
138757 return rc;
138758 no_mem:
138760 if( pCursor ){
138761 pModule->xClose(pCursor);
138763 sqlite3_free(zTemp);
138764 sqlite3_free(p);
138765 *ppExpr = 0;
138766 return SQLITE_NOMEM;
138770 ** The output variable *ppExpr is populated with an allocated Fts3Expr
138771 ** structure, or set to 0 if the end of the input buffer is reached.
138773 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
138774 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
138775 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
138777 static int getNextNode(
138778 ParseContext *pParse, /* fts3 query parse context */
138779 const char *z, int n, /* Input string */
138780 Fts3Expr **ppExpr, /* OUT: expression */
138781 int *pnConsumed /* OUT: Number of bytes consumed */
138783 static const struct Fts3Keyword {
138784 char *z; /* Keyword text */
138785 unsigned char n; /* Length of the keyword */
138786 unsigned char parenOnly; /* Only valid in paren mode */
138787 unsigned char eType; /* Keyword code */
138788 } aKeyword[] = {
138789 { "OR" , 2, 0, FTSQUERY_OR },
138790 { "AND", 3, 1, FTSQUERY_AND },
138791 { "NOT", 3, 1, FTSQUERY_NOT },
138792 { "NEAR", 4, 0, FTSQUERY_NEAR }
138794 int ii;
138795 int iCol;
138796 int iColLen;
138797 int rc;
138798 Fts3Expr *pRet = 0;
138800 const char *zInput = z;
138801 int nInput = n;
138803 pParse->isNot = 0;
138805 /* Skip over any whitespace before checking for a keyword, an open or
138806 ** close bracket, or a quoted string.
138808 while( nInput>0 && fts3isspace(*zInput) ){
138809 nInput--;
138810 zInput++;
138812 if( nInput==0 ){
138813 return SQLITE_DONE;
138816 /* See if we are dealing with a keyword. */
138817 for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
138818 const struct Fts3Keyword *pKey = &aKeyword[ii];
138820 if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
138821 continue;
138824 if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
138825 int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
138826 int nKey = pKey->n;
138827 char cNext;
138829 /* If this is a "NEAR" keyword, check for an explicit nearness. */
138830 if( pKey->eType==FTSQUERY_NEAR ){
138831 assert( nKey==4 );
138832 if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
138833 nNear = 0;
138834 for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
138835 nNear = nNear * 10 + (zInput[nKey] - '0');
138840 /* At this point this is probably a keyword. But for that to be true,
138841 ** the next byte must contain either whitespace, an open or close
138842 ** parenthesis, a quote character, or EOF.
138844 cNext = zInput[nKey];
138845 if( fts3isspace(cNext)
138846 || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
138848 pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
138849 if( !pRet ){
138850 return SQLITE_NOMEM;
138852 pRet->eType = pKey->eType;
138853 pRet->nNear = nNear;
138854 *ppExpr = pRet;
138855 *pnConsumed = (int)((zInput - z) + nKey);
138856 return SQLITE_OK;
138859 /* Turns out that wasn't a keyword after all. This happens if the
138860 ** user has supplied a token such as "ORacle". Continue.
138865 /* See if we are dealing with a quoted phrase. If this is the case, then
138866 ** search for the closing quote and pass the whole string to getNextString()
138867 ** for processing. This is easy to do, as fts3 has no syntax for escaping
138868 ** a quote character embedded in a string.
138870 if( *zInput=='"' ){
138871 for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
138872 *pnConsumed = (int)((zInput - z) + ii + 1);
138873 if( ii==nInput ){
138874 return SQLITE_ERROR;
138876 return getNextString(pParse, &zInput[1], ii-1, ppExpr);
138879 if( sqlite3_fts3_enable_parentheses ){
138880 if( *zInput=='(' ){
138881 int nConsumed = 0;
138882 pParse->nNest++;
138883 rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
138884 if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
138885 *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
138886 return rc;
138887 }else if( *zInput==')' ){
138888 pParse->nNest--;
138889 *pnConsumed = (int)((zInput - z) + 1);
138890 *ppExpr = 0;
138891 return SQLITE_DONE;
138895 /* If control flows to this point, this must be a regular token, or
138896 ** the end of the input. Read a regular token using the sqlite3_tokenizer
138897 ** interface. Before doing so, figure out if there is an explicit
138898 ** column specifier for the token.
138900 ** TODO: Strangely, it is not possible to associate a column specifier
138901 ** with a quoted phrase, only with a single token. Not sure if this was
138902 ** an implementation artifact or an intentional decision when fts3 was
138903 ** first implemented. Whichever it was, this module duplicates the
138904 ** limitation.
138906 iCol = pParse->iDefaultCol;
138907 iColLen = 0;
138908 for(ii=0; ii<pParse->nCol; ii++){
138909 const char *zStr = pParse->azCol[ii];
138910 int nStr = (int)strlen(zStr);
138911 if( nInput>nStr && zInput[nStr]==':'
138912 && sqlite3_strnicmp(zStr, zInput, nStr)==0
138914 iCol = ii;
138915 iColLen = (int)((zInput - z) + nStr + 1);
138916 break;
138919 rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
138920 *pnConsumed += iColLen;
138921 return rc;
138925 ** The argument is an Fts3Expr structure for a binary operator (any type
138926 ** except an FTSQUERY_PHRASE). Return an integer value representing the
138927 ** precedence of the operator. Lower values have a higher precedence (i.e.
138928 ** group more tightly). For example, in the C language, the == operator
138929 ** groups more tightly than ||, and would therefore have a higher precedence.
138931 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
138932 ** is defined), the order of the operators in precedence from highest to
138933 ** lowest is:
138935 ** NEAR
138936 ** NOT
138937 ** AND (including implicit ANDs)
138938 ** OR
138940 ** Note that when using the old query syntax, the OR operator has a higher
138941 ** precedence than the AND operator.
138943 static int opPrecedence(Fts3Expr *p){
138944 assert( p->eType!=FTSQUERY_PHRASE );
138945 if( sqlite3_fts3_enable_parentheses ){
138946 return p->eType;
138947 }else if( p->eType==FTSQUERY_NEAR ){
138948 return 1;
138949 }else if( p->eType==FTSQUERY_OR ){
138950 return 2;
138952 assert( p->eType==FTSQUERY_AND );
138953 return 3;
138957 ** Argument ppHead contains a pointer to the current head of a query
138958 ** expression tree being parsed. pPrev is the expression node most recently
138959 ** inserted into the tree. This function adds pNew, which is always a binary
138960 ** operator node, into the expression tree based on the relative precedence
138961 ** of pNew and the existing nodes of the tree. This may result in the head
138962 ** of the tree changing, in which case *ppHead is set to the new root node.
138964 static void insertBinaryOperator(
138965 Fts3Expr **ppHead, /* Pointer to the root node of a tree */
138966 Fts3Expr *pPrev, /* Node most recently inserted into the tree */
138967 Fts3Expr *pNew /* New binary node to insert into expression tree */
138969 Fts3Expr *pSplit = pPrev;
138970 while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
138971 pSplit = pSplit->pParent;
138974 if( pSplit->pParent ){
138975 assert( pSplit->pParent->pRight==pSplit );
138976 pSplit->pParent->pRight = pNew;
138977 pNew->pParent = pSplit->pParent;
138978 }else{
138979 *ppHead = pNew;
138981 pNew->pLeft = pSplit;
138982 pSplit->pParent = pNew;
138986 ** Parse the fts3 query expression found in buffer z, length n. This function
138987 ** returns either when the end of the buffer is reached or an unmatched
138988 ** closing bracket - ')' - is encountered.
138990 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
138991 ** parsed form of the expression and *pnConsumed is set to the number of
138992 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
138993 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
138995 static int fts3ExprParse(
138996 ParseContext *pParse, /* fts3 query parse context */
138997 const char *z, int n, /* Text of MATCH query */
138998 Fts3Expr **ppExpr, /* OUT: Parsed query structure */
138999 int *pnConsumed /* OUT: Number of bytes consumed */
139001 Fts3Expr *pRet = 0;
139002 Fts3Expr *pPrev = 0;
139003 Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
139004 int nIn = n;
139005 const char *zIn = z;
139006 int rc = SQLITE_OK;
139007 int isRequirePhrase = 1;
139009 while( rc==SQLITE_OK ){
139010 Fts3Expr *p = 0;
139011 int nByte = 0;
139013 rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
139014 assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
139015 if( rc==SQLITE_OK ){
139016 if( p ){
139017 int isPhrase;
139019 if( !sqlite3_fts3_enable_parentheses
139020 && p->eType==FTSQUERY_PHRASE && pParse->isNot
139022 /* Create an implicit NOT operator. */
139023 Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
139024 if( !pNot ){
139025 sqlite3Fts3ExprFree(p);
139026 rc = SQLITE_NOMEM;
139027 goto exprparse_out;
139029 pNot->eType = FTSQUERY_NOT;
139030 pNot->pRight = p;
139031 p->pParent = pNot;
139032 if( pNotBranch ){
139033 pNot->pLeft = pNotBranch;
139034 pNotBranch->pParent = pNot;
139036 pNotBranch = pNot;
139037 p = pPrev;
139038 }else{
139039 int eType = p->eType;
139040 isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
139042 /* The isRequirePhrase variable is set to true if a phrase or
139043 ** an expression contained in parenthesis is required. If a
139044 ** binary operator (AND, OR, NOT or NEAR) is encounted when
139045 ** isRequirePhrase is set, this is a syntax error.
139047 if( !isPhrase && isRequirePhrase ){
139048 sqlite3Fts3ExprFree(p);
139049 rc = SQLITE_ERROR;
139050 goto exprparse_out;
139053 if( isPhrase && !isRequirePhrase ){
139054 /* Insert an implicit AND operator. */
139055 Fts3Expr *pAnd;
139056 assert( pRet && pPrev );
139057 pAnd = fts3MallocZero(sizeof(Fts3Expr));
139058 if( !pAnd ){
139059 sqlite3Fts3ExprFree(p);
139060 rc = SQLITE_NOMEM;
139061 goto exprparse_out;
139063 pAnd->eType = FTSQUERY_AND;
139064 insertBinaryOperator(&pRet, pPrev, pAnd);
139065 pPrev = pAnd;
139068 /* This test catches attempts to make either operand of a NEAR
139069 ** operator something other than a phrase. For example, either of
139070 ** the following:
139072 ** (bracketed expression) NEAR phrase
139073 ** phrase NEAR (bracketed expression)
139075 ** Return an error in either case.
139077 if( pPrev && (
139078 (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
139079 || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
139081 sqlite3Fts3ExprFree(p);
139082 rc = SQLITE_ERROR;
139083 goto exprparse_out;
139086 if( isPhrase ){
139087 if( pRet ){
139088 assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
139089 pPrev->pRight = p;
139090 p->pParent = pPrev;
139091 }else{
139092 pRet = p;
139094 }else{
139095 insertBinaryOperator(&pRet, pPrev, p);
139097 isRequirePhrase = !isPhrase;
139099 pPrev = p;
139101 assert( nByte>0 );
139103 assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
139104 nIn -= nByte;
139105 zIn += nByte;
139108 if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
139109 rc = SQLITE_ERROR;
139112 if( rc==SQLITE_DONE ){
139113 rc = SQLITE_OK;
139114 if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
139115 if( !pRet ){
139116 rc = SQLITE_ERROR;
139117 }else{
139118 Fts3Expr *pIter = pNotBranch;
139119 while( pIter->pLeft ){
139120 pIter = pIter->pLeft;
139122 pIter->pLeft = pRet;
139123 pRet->pParent = pIter;
139124 pRet = pNotBranch;
139128 *pnConsumed = n - nIn;
139130 exprparse_out:
139131 if( rc!=SQLITE_OK ){
139132 sqlite3Fts3ExprFree(pRet);
139133 sqlite3Fts3ExprFree(pNotBranch);
139134 pRet = 0;
139136 *ppExpr = pRet;
139137 return rc;
139141 ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
139142 ** as the only argument is more than nMaxDepth.
139144 static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
139145 int rc = SQLITE_OK;
139146 if( p ){
139147 if( nMaxDepth<0 ){
139148 rc = SQLITE_TOOBIG;
139149 }else{
139150 rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
139151 if( rc==SQLITE_OK ){
139152 rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
139156 return rc;
139160 ** This function attempts to transform the expression tree at (*pp) to
139161 ** an equivalent but more balanced form. The tree is modified in place.
139162 ** If successful, SQLITE_OK is returned and (*pp) set to point to the
139163 ** new root expression node.
139165 ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
139167 ** Otherwise, if an error occurs, an SQLite error code is returned and
139168 ** expression (*pp) freed.
139170 static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
139171 int rc = SQLITE_OK; /* Return code */
139172 Fts3Expr *pRoot = *pp; /* Initial root node */
139173 Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
139174 int eType = pRoot->eType; /* Type of node in this tree */
139176 if( nMaxDepth==0 ){
139177 rc = SQLITE_ERROR;
139180 if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
139181 Fts3Expr **apLeaf;
139182 apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
139183 if( 0==apLeaf ){
139184 rc = SQLITE_NOMEM;
139185 }else{
139186 memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
139189 if( rc==SQLITE_OK ){
139190 int i;
139191 Fts3Expr *p;
139193 /* Set $p to point to the left-most leaf in the tree of eType nodes. */
139194 for(p=pRoot; p->eType==eType; p=p->pLeft){
139195 assert( p->pParent==0 || p->pParent->pLeft==p );
139196 assert( p->pLeft && p->pRight );
139199 /* This loop runs once for each leaf in the tree of eType nodes. */
139200 while( 1 ){
139201 int iLvl;
139202 Fts3Expr *pParent = p->pParent; /* Current parent of p */
139204 assert( pParent==0 || pParent->pLeft==p );
139205 p->pParent = 0;
139206 if( pParent ){
139207 pParent->pLeft = 0;
139208 }else{
139209 pRoot = 0;
139211 rc = fts3ExprBalance(&p, nMaxDepth-1);
139212 if( rc!=SQLITE_OK ) break;
139214 for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
139215 if( apLeaf[iLvl]==0 ){
139216 apLeaf[iLvl] = p;
139217 p = 0;
139218 }else{
139219 assert( pFree );
139220 pFree->pLeft = apLeaf[iLvl];
139221 pFree->pRight = p;
139222 pFree->pLeft->pParent = pFree;
139223 pFree->pRight->pParent = pFree;
139225 p = pFree;
139226 pFree = pFree->pParent;
139227 p->pParent = 0;
139228 apLeaf[iLvl] = 0;
139231 if( p ){
139232 sqlite3Fts3ExprFree(p);
139233 rc = SQLITE_TOOBIG;
139234 break;
139237 /* If that was the last leaf node, break out of the loop */
139238 if( pParent==0 ) break;
139240 /* Set $p to point to the next leaf in the tree of eType nodes */
139241 for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
139243 /* Remove pParent from the original tree. */
139244 assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
139245 pParent->pRight->pParent = pParent->pParent;
139246 if( pParent->pParent ){
139247 pParent->pParent->pLeft = pParent->pRight;
139248 }else{
139249 assert( pParent==pRoot );
139250 pRoot = pParent->pRight;
139253 /* Link pParent into the free node list. It will be used as an
139254 ** internal node of the new tree. */
139255 pParent->pParent = pFree;
139256 pFree = pParent;
139259 if( rc==SQLITE_OK ){
139260 p = 0;
139261 for(i=0; i<nMaxDepth; i++){
139262 if( apLeaf[i] ){
139263 if( p==0 ){
139264 p = apLeaf[i];
139265 p->pParent = 0;
139266 }else{
139267 assert( pFree!=0 );
139268 pFree->pRight = p;
139269 pFree->pLeft = apLeaf[i];
139270 pFree->pLeft->pParent = pFree;
139271 pFree->pRight->pParent = pFree;
139273 p = pFree;
139274 pFree = pFree->pParent;
139275 p->pParent = 0;
139279 pRoot = p;
139280 }else{
139281 /* An error occurred. Delete the contents of the apLeaf[] array
139282 ** and pFree list. Everything else is cleaned up by the call to
139283 ** sqlite3Fts3ExprFree(pRoot) below. */
139284 Fts3Expr *pDel;
139285 for(i=0; i<nMaxDepth; i++){
139286 sqlite3Fts3ExprFree(apLeaf[i]);
139288 while( (pDel=pFree)!=0 ){
139289 pFree = pDel->pParent;
139290 sqlite3_free(pDel);
139294 assert( pFree==0 );
139295 sqlite3_free( apLeaf );
139299 if( rc!=SQLITE_OK ){
139300 sqlite3Fts3ExprFree(pRoot);
139301 pRoot = 0;
139303 *pp = pRoot;
139304 return rc;
139308 ** This function is similar to sqlite3Fts3ExprParse(), with the following
139309 ** differences:
139311 ** 1. It does not do expression rebalancing.
139312 ** 2. It does not check that the expression does not exceed the
139313 ** maximum allowable depth.
139314 ** 3. Even if it fails, *ppExpr may still be set to point to an
139315 ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
139316 ** in this case.
139318 static int fts3ExprParseUnbalanced(
139319 sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
139320 int iLangid, /* Language id for tokenizer */
139321 char **azCol, /* Array of column names for fts3 table */
139322 int bFts4, /* True to allow FTS4-only syntax */
139323 int nCol, /* Number of entries in azCol[] */
139324 int iDefaultCol, /* Default column to query */
139325 const char *z, int n, /* Text of MATCH query */
139326 Fts3Expr **ppExpr /* OUT: Parsed query structure */
139328 int nParsed;
139329 int rc;
139330 ParseContext sParse;
139332 memset(&sParse, 0, sizeof(ParseContext));
139333 sParse.pTokenizer = pTokenizer;
139334 sParse.iLangid = iLangid;
139335 sParse.azCol = (const char **)azCol;
139336 sParse.nCol = nCol;
139337 sParse.iDefaultCol = iDefaultCol;
139338 sParse.bFts4 = bFts4;
139339 if( z==0 ){
139340 *ppExpr = 0;
139341 return SQLITE_OK;
139343 if( n<0 ){
139344 n = (int)strlen(z);
139346 rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
139347 assert( rc==SQLITE_OK || *ppExpr==0 );
139349 /* Check for mismatched parenthesis */
139350 if( rc==SQLITE_OK && sParse.nNest ){
139351 rc = SQLITE_ERROR;
139354 return rc;
139358 ** Parameters z and n contain a pointer to and length of a buffer containing
139359 ** an fts3 query expression, respectively. This function attempts to parse the
139360 ** query expression and create a tree of Fts3Expr structures representing the
139361 ** parsed expression. If successful, *ppExpr is set to point to the head
139362 ** of the parsed expression tree and SQLITE_OK is returned. If an error
139363 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
139364 ** error) is returned and *ppExpr is set to 0.
139366 ** If parameter n is a negative number, then z is assumed to point to a
139367 ** nul-terminated string and the length is determined using strlen().
139369 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
139370 ** use to normalize query tokens while parsing the expression. The azCol[]
139371 ** array, which is assumed to contain nCol entries, should contain the names
139372 ** of each column in the target fts3 table, in order from left to right.
139373 ** Column names must be nul-terminated strings.
139375 ** The iDefaultCol parameter should be passed the index of the table column
139376 ** that appears on the left-hand-side of the MATCH operator (the default
139377 ** column to match against for tokens for which a column name is not explicitly
139378 ** specified as part of the query string), or -1 if tokens may by default
139379 ** match any table column.
139381 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
139382 sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
139383 int iLangid, /* Language id for tokenizer */
139384 char **azCol, /* Array of column names for fts3 table */
139385 int bFts4, /* True to allow FTS4-only syntax */
139386 int nCol, /* Number of entries in azCol[] */
139387 int iDefaultCol, /* Default column to query */
139388 const char *z, int n, /* Text of MATCH query */
139389 Fts3Expr **ppExpr, /* OUT: Parsed query structure */
139390 char **pzErr /* OUT: Error message (sqlite3_malloc) */
139392 int rc = fts3ExprParseUnbalanced(
139393 pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
139396 /* Rebalance the expression. And check that its depth does not exceed
139397 ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
139398 if( rc==SQLITE_OK && *ppExpr ){
139399 rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
139400 if( rc==SQLITE_OK ){
139401 rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
139405 if( rc!=SQLITE_OK ){
139406 sqlite3Fts3ExprFree(*ppExpr);
139407 *ppExpr = 0;
139408 if( rc==SQLITE_TOOBIG ){
139409 *pzErr = sqlite3_mprintf(
139410 "FTS expression tree is too large (maximum depth %d)",
139411 SQLITE_FTS3_MAX_EXPR_DEPTH
139413 rc = SQLITE_ERROR;
139414 }else if( rc==SQLITE_ERROR ){
139415 *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
139419 return rc;
139423 ** Free a single node of an expression tree.
139425 static void fts3FreeExprNode(Fts3Expr *p){
139426 assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
139427 sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
139428 sqlite3_free(p->aMI);
139429 sqlite3_free(p);
139433 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
139435 ** This function would be simpler if it recursively called itself. But
139436 ** that would mean passing a sufficiently large expression to ExprParse()
139437 ** could cause a stack overflow.
139439 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
139440 Fts3Expr *p;
139441 assert( pDel==0 || pDel->pParent==0 );
139442 for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
139443 assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
139445 while( p ){
139446 Fts3Expr *pParent = p->pParent;
139447 fts3FreeExprNode(p);
139448 if( pParent && p==pParent->pLeft && pParent->pRight ){
139449 p = pParent->pRight;
139450 while( p && (p->pLeft || p->pRight) ){
139451 assert( p==p->pParent->pRight || p==p->pParent->pLeft );
139452 p = (p->pLeft ? p->pLeft : p->pRight);
139454 }else{
139455 p = pParent;
139460 /****************************************************************************
139461 *****************************************************************************
139462 ** Everything after this point is just test code.
139465 #ifdef SQLITE_TEST
139467 /* #include <stdio.h> */
139470 ** Function to query the hash-table of tokenizers (see README.tokenizers).
139472 static int queryTestTokenizer(
139473 sqlite3 *db,
139474 const char *zName,
139475 const sqlite3_tokenizer_module **pp
139477 int rc;
139478 sqlite3_stmt *pStmt;
139479 const char zSql[] = "SELECT fts3_tokenizer(?)";
139481 *pp = 0;
139482 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
139483 if( rc!=SQLITE_OK ){
139484 return rc;
139487 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
139488 if( SQLITE_ROW==sqlite3_step(pStmt) ){
139489 if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
139490 memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
139494 return sqlite3_finalize(pStmt);
139498 ** Return a pointer to a buffer containing a text representation of the
139499 ** expression passed as the first argument. The buffer is obtained from
139500 ** sqlite3_malloc(). It is the responsibility of the caller to use
139501 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
139502 ** NULL is returned.
139504 ** If the second argument is not NULL, then its contents are prepended to
139505 ** the returned expression text and then freed using sqlite3_free().
139507 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
139508 if( pExpr==0 ){
139509 return sqlite3_mprintf("");
139511 switch( pExpr->eType ){
139512 case FTSQUERY_PHRASE: {
139513 Fts3Phrase *pPhrase = pExpr->pPhrase;
139514 int i;
139515 zBuf = sqlite3_mprintf(
139516 "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
139517 for(i=0; zBuf && i<pPhrase->nToken; i++){
139518 zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
139519 pPhrase->aToken[i].n, pPhrase->aToken[i].z,
139520 (pPhrase->aToken[i].isPrefix?"+":"")
139523 return zBuf;
139526 case FTSQUERY_NEAR:
139527 zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
139528 break;
139529 case FTSQUERY_NOT:
139530 zBuf = sqlite3_mprintf("%zNOT ", zBuf);
139531 break;
139532 case FTSQUERY_AND:
139533 zBuf = sqlite3_mprintf("%zAND ", zBuf);
139534 break;
139535 case FTSQUERY_OR:
139536 zBuf = sqlite3_mprintf("%zOR ", zBuf);
139537 break;
139540 if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
139541 if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
139542 if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
139544 if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
139545 if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
139547 return zBuf;
139551 ** This is the implementation of a scalar SQL function used to test the
139552 ** expression parser. It should be called as follows:
139554 ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
139556 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
139557 ** to parse the query expression (see README.tokenizers). The second argument
139558 ** is the query expression to parse. Each subsequent argument is the name
139559 ** of a column of the fts3 table that the query expression may refer to.
139560 ** For example:
139562 ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
139564 static void fts3ExprTest(
139565 sqlite3_context *context,
139566 int argc,
139567 sqlite3_value **argv
139569 sqlite3_tokenizer_module const *pModule = 0;
139570 sqlite3_tokenizer *pTokenizer = 0;
139571 int rc;
139572 char **azCol = 0;
139573 const char *zExpr;
139574 int nExpr;
139575 int nCol;
139576 int ii;
139577 Fts3Expr *pExpr;
139578 char *zBuf = 0;
139579 sqlite3 *db = sqlite3_context_db_handle(context);
139581 if( argc<3 ){
139582 sqlite3_result_error(context,
139583 "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
139585 return;
139588 rc = queryTestTokenizer(db,
139589 (const char *)sqlite3_value_text(argv[0]), &pModule);
139590 if( rc==SQLITE_NOMEM ){
139591 sqlite3_result_error_nomem(context);
139592 goto exprtest_out;
139593 }else if( !pModule ){
139594 sqlite3_result_error(context, "No such tokenizer module", -1);
139595 goto exprtest_out;
139598 rc = pModule->xCreate(0, 0, &pTokenizer);
139599 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
139600 if( rc==SQLITE_NOMEM ){
139601 sqlite3_result_error_nomem(context);
139602 goto exprtest_out;
139604 pTokenizer->pModule = pModule;
139606 zExpr = (const char *)sqlite3_value_text(argv[1]);
139607 nExpr = sqlite3_value_bytes(argv[1]);
139608 nCol = argc-2;
139609 azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
139610 if( !azCol ){
139611 sqlite3_result_error_nomem(context);
139612 goto exprtest_out;
139614 for(ii=0; ii<nCol; ii++){
139615 azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
139618 if( sqlite3_user_data(context) ){
139619 char *zDummy = 0;
139620 rc = sqlite3Fts3ExprParse(
139621 pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
139623 assert( rc==SQLITE_OK || pExpr==0 );
139624 sqlite3_free(zDummy);
139625 }else{
139626 rc = fts3ExprParseUnbalanced(
139627 pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
139631 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
139632 sqlite3Fts3ExprFree(pExpr);
139633 sqlite3_result_error(context, "Error parsing expression", -1);
139634 }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
139635 sqlite3_result_error_nomem(context);
139636 }else{
139637 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
139638 sqlite3_free(zBuf);
139641 sqlite3Fts3ExprFree(pExpr);
139643 exprtest_out:
139644 if( pModule && pTokenizer ){
139645 rc = pModule->xDestroy(pTokenizer);
139647 sqlite3_free(azCol);
139651 ** Register the query expression parser test function fts3_exprtest()
139652 ** with database connection db.
139654 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
139655 int rc = sqlite3_create_function(
139656 db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
139658 if( rc==SQLITE_OK ){
139659 rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
139660 -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
139663 return rc;
139666 #endif
139667 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
139669 /************** End of fts3_expr.c *******************************************/
139670 /************** Begin file fts3_hash.c ***************************************/
139672 ** 2001 September 22
139674 ** The author disclaims copyright to this source code. In place of
139675 ** a legal notice, here is a blessing:
139677 ** May you do good and not evil.
139678 ** May you find forgiveness for yourself and forgive others.
139679 ** May you share freely, never taking more than you give.
139681 *************************************************************************
139682 ** This is the implementation of generic hash-tables used in SQLite.
139683 ** We've modified it slightly to serve as a standalone hash table
139684 ** implementation for the full-text indexing module.
139688 ** The code in this file is only compiled if:
139690 ** * The FTS3 module is being built as an extension
139691 ** (in which case SQLITE_CORE is not defined), or
139693 ** * The FTS3 module is being built into the core of
139694 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
139696 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
139698 /* #include <assert.h> */
139699 /* #include <stdlib.h> */
139700 /* #include <string.h> */
139704 ** Malloc and Free functions
139706 static void *fts3HashMalloc(int n){
139707 void *p = sqlite3_malloc(n);
139708 if( p ){
139709 memset(p, 0, n);
139711 return p;
139713 static void fts3HashFree(void *p){
139714 sqlite3_free(p);
139717 /* Turn bulk memory into a hash table object by initializing the
139718 ** fields of the Hash structure.
139720 ** "pNew" is a pointer to the hash table that is to be initialized.
139721 ** keyClass is one of the constants
139722 ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
139723 ** determines what kind of key the hash table will use. "copyKey" is
139724 ** true if the hash table should make its own private copy of keys and
139725 ** false if it should just use the supplied pointer.
139727 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
139728 assert( pNew!=0 );
139729 assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
139730 pNew->keyClass = keyClass;
139731 pNew->copyKey = copyKey;
139732 pNew->first = 0;
139733 pNew->count = 0;
139734 pNew->htsize = 0;
139735 pNew->ht = 0;
139738 /* Remove all entries from a hash table. Reclaim all memory.
139739 ** Call this routine to delete a hash table or to reset a hash table
139740 ** to the empty state.
139742 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
139743 Fts3HashElem *elem; /* For looping over all elements of the table */
139745 assert( pH!=0 );
139746 elem = pH->first;
139747 pH->first = 0;
139748 fts3HashFree(pH->ht);
139749 pH->ht = 0;
139750 pH->htsize = 0;
139751 while( elem ){
139752 Fts3HashElem *next_elem = elem->next;
139753 if( pH->copyKey && elem->pKey ){
139754 fts3HashFree(elem->pKey);
139756 fts3HashFree(elem);
139757 elem = next_elem;
139759 pH->count = 0;
139763 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
139765 static int fts3StrHash(const void *pKey, int nKey){
139766 const char *z = (const char *)pKey;
139767 unsigned h = 0;
139768 if( nKey<=0 ) nKey = (int) strlen(z);
139769 while( nKey > 0 ){
139770 h = (h<<3) ^ h ^ *z++;
139771 nKey--;
139773 return (int)(h & 0x7fffffff);
139775 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
139776 if( n1!=n2 ) return 1;
139777 return strncmp((const char*)pKey1,(const char*)pKey2,n1);
139781 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
139783 static int fts3BinHash(const void *pKey, int nKey){
139784 int h = 0;
139785 const char *z = (const char *)pKey;
139786 while( nKey-- > 0 ){
139787 h = (h<<3) ^ h ^ *(z++);
139789 return h & 0x7fffffff;
139791 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
139792 if( n1!=n2 ) return 1;
139793 return memcmp(pKey1,pKey2,n1);
139797 ** Return a pointer to the appropriate hash function given the key class.
139799 ** The C syntax in this function definition may be unfamilar to some
139800 ** programmers, so we provide the following additional explanation:
139802 ** The name of the function is "ftsHashFunction". The function takes a
139803 ** single parameter "keyClass". The return value of ftsHashFunction()
139804 ** is a pointer to another function. Specifically, the return value
139805 ** of ftsHashFunction() is a pointer to a function that takes two parameters
139806 ** with types "const void*" and "int" and returns an "int".
139808 static int (*ftsHashFunction(int keyClass))(const void*,int){
139809 if( keyClass==FTS3_HASH_STRING ){
139810 return &fts3StrHash;
139811 }else{
139812 assert( keyClass==FTS3_HASH_BINARY );
139813 return &fts3BinHash;
139818 ** Return a pointer to the appropriate hash function given the key class.
139820 ** For help in interpreted the obscure C code in the function definition,
139821 ** see the header comment on the previous function.
139823 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
139824 if( keyClass==FTS3_HASH_STRING ){
139825 return &fts3StrCompare;
139826 }else{
139827 assert( keyClass==FTS3_HASH_BINARY );
139828 return &fts3BinCompare;
139832 /* Link an element into the hash table
139834 static void fts3HashInsertElement(
139835 Fts3Hash *pH, /* The complete hash table */
139836 struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
139837 Fts3HashElem *pNew /* The element to be inserted */
139839 Fts3HashElem *pHead; /* First element already in pEntry */
139840 pHead = pEntry->chain;
139841 if( pHead ){
139842 pNew->next = pHead;
139843 pNew->prev = pHead->prev;
139844 if( pHead->prev ){ pHead->prev->next = pNew; }
139845 else { pH->first = pNew; }
139846 pHead->prev = pNew;
139847 }else{
139848 pNew->next = pH->first;
139849 if( pH->first ){ pH->first->prev = pNew; }
139850 pNew->prev = 0;
139851 pH->first = pNew;
139853 pEntry->count++;
139854 pEntry->chain = pNew;
139858 /* Resize the hash table so that it cantains "new_size" buckets.
139859 ** "new_size" must be a power of 2. The hash table might fail
139860 ** to resize if sqliteMalloc() fails.
139862 ** Return non-zero if a memory allocation error occurs.
139864 static int fts3Rehash(Fts3Hash *pH, int new_size){
139865 struct _fts3ht *new_ht; /* The new hash table */
139866 Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
139867 int (*xHash)(const void*,int); /* The hash function */
139869 assert( (new_size & (new_size-1))==0 );
139870 new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
139871 if( new_ht==0 ) return 1;
139872 fts3HashFree(pH->ht);
139873 pH->ht = new_ht;
139874 pH->htsize = new_size;
139875 xHash = ftsHashFunction(pH->keyClass);
139876 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
139877 int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
139878 next_elem = elem->next;
139879 fts3HashInsertElement(pH, &new_ht[h], elem);
139881 return 0;
139884 /* This function (for internal use only) locates an element in an
139885 ** hash table that matches the given key. The hash for this key has
139886 ** already been computed and is passed as the 4th parameter.
139888 static Fts3HashElem *fts3FindElementByHash(
139889 const Fts3Hash *pH, /* The pH to be searched */
139890 const void *pKey, /* The key we are searching for */
139891 int nKey,
139892 int h /* The hash for this key. */
139894 Fts3HashElem *elem; /* Used to loop thru the element list */
139895 int count; /* Number of elements left to test */
139896 int (*xCompare)(const void*,int,const void*,int); /* comparison function */
139898 if( pH->ht ){
139899 struct _fts3ht *pEntry = &pH->ht[h];
139900 elem = pEntry->chain;
139901 count = pEntry->count;
139902 xCompare = ftsCompareFunction(pH->keyClass);
139903 while( count-- && elem ){
139904 if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
139905 return elem;
139907 elem = elem->next;
139910 return 0;
139913 /* Remove a single entry from the hash table given a pointer to that
139914 ** element and a hash on the element's key.
139916 static void fts3RemoveElementByHash(
139917 Fts3Hash *pH, /* The pH containing "elem" */
139918 Fts3HashElem* elem, /* The element to be removed from the pH */
139919 int h /* Hash value for the element */
139921 struct _fts3ht *pEntry;
139922 if( elem->prev ){
139923 elem->prev->next = elem->next;
139924 }else{
139925 pH->first = elem->next;
139927 if( elem->next ){
139928 elem->next->prev = elem->prev;
139930 pEntry = &pH->ht[h];
139931 if( pEntry->chain==elem ){
139932 pEntry->chain = elem->next;
139934 pEntry->count--;
139935 if( pEntry->count<=0 ){
139936 pEntry->chain = 0;
139938 if( pH->copyKey && elem->pKey ){
139939 fts3HashFree(elem->pKey);
139941 fts3HashFree( elem );
139942 pH->count--;
139943 if( pH->count<=0 ){
139944 assert( pH->first==0 );
139945 assert( pH->count==0 );
139946 fts3HashClear(pH);
139950 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
139951 const Fts3Hash *pH,
139952 const void *pKey,
139953 int nKey
139955 int h; /* A hash on key */
139956 int (*xHash)(const void*,int); /* The hash function */
139958 if( pH==0 || pH->ht==0 ) return 0;
139959 xHash = ftsHashFunction(pH->keyClass);
139960 assert( xHash!=0 );
139961 h = (*xHash)(pKey,nKey);
139962 assert( (pH->htsize & (pH->htsize-1))==0 );
139963 return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
139967 ** Attempt to locate an element of the hash table pH with a key
139968 ** that matches pKey,nKey. Return the data for this element if it is
139969 ** found, or NULL if there is no match.
139971 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
139972 Fts3HashElem *pElem; /* The element that matches key (if any) */
139974 pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
139975 return pElem ? pElem->data : 0;
139978 /* Insert an element into the hash table pH. The key is pKey,nKey
139979 ** and the data is "data".
139981 ** If no element exists with a matching key, then a new
139982 ** element is created. A copy of the key is made if the copyKey
139983 ** flag is set. NULL is returned.
139985 ** If another element already exists with the same key, then the
139986 ** new data replaces the old data and the old data is returned.
139987 ** The key is not copied in this instance. If a malloc fails, then
139988 ** the new data is returned and the hash table is unchanged.
139990 ** If the "data" parameter to this function is NULL, then the
139991 ** element corresponding to "key" is removed from the hash table.
139993 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
139994 Fts3Hash *pH, /* The hash table to insert into */
139995 const void *pKey, /* The key */
139996 int nKey, /* Number of bytes in the key */
139997 void *data /* The data */
139999 int hraw; /* Raw hash value of the key */
140000 int h; /* the hash of the key modulo hash table size */
140001 Fts3HashElem *elem; /* Used to loop thru the element list */
140002 Fts3HashElem *new_elem; /* New element added to the pH */
140003 int (*xHash)(const void*,int); /* The hash function */
140005 assert( pH!=0 );
140006 xHash = ftsHashFunction(pH->keyClass);
140007 assert( xHash!=0 );
140008 hraw = (*xHash)(pKey, nKey);
140009 assert( (pH->htsize & (pH->htsize-1))==0 );
140010 h = hraw & (pH->htsize-1);
140011 elem = fts3FindElementByHash(pH,pKey,nKey,h);
140012 if( elem ){
140013 void *old_data = elem->data;
140014 if( data==0 ){
140015 fts3RemoveElementByHash(pH,elem,h);
140016 }else{
140017 elem->data = data;
140019 return old_data;
140021 if( data==0 ) return 0;
140022 if( (pH->htsize==0 && fts3Rehash(pH,8))
140023 || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
140025 pH->count = 0;
140026 return data;
140028 assert( pH->htsize>0 );
140029 new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
140030 if( new_elem==0 ) return data;
140031 if( pH->copyKey && pKey!=0 ){
140032 new_elem->pKey = fts3HashMalloc( nKey );
140033 if( new_elem->pKey==0 ){
140034 fts3HashFree(new_elem);
140035 return data;
140037 memcpy((void*)new_elem->pKey, pKey, nKey);
140038 }else{
140039 new_elem->pKey = (void*)pKey;
140041 new_elem->nKey = nKey;
140042 pH->count++;
140043 assert( pH->htsize>0 );
140044 assert( (pH->htsize & (pH->htsize-1))==0 );
140045 h = hraw & (pH->htsize-1);
140046 fts3HashInsertElement(pH, &pH->ht[h], new_elem);
140047 new_elem->data = data;
140048 return 0;
140051 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
140053 /************** End of fts3_hash.c *******************************************/
140054 /************** Begin file fts3_porter.c *************************************/
140056 ** 2006 September 30
140058 ** The author disclaims copyright to this source code. In place of
140059 ** a legal notice, here is a blessing:
140061 ** May you do good and not evil.
140062 ** May you find forgiveness for yourself and forgive others.
140063 ** May you share freely, never taking more than you give.
140065 *************************************************************************
140066 ** Implementation of the full-text-search tokenizer that implements
140067 ** a Porter stemmer.
140071 ** The code in this file is only compiled if:
140073 ** * The FTS3 module is being built as an extension
140074 ** (in which case SQLITE_CORE is not defined), or
140076 ** * The FTS3 module is being built into the core of
140077 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
140079 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
140081 /* #include <assert.h> */
140082 /* #include <stdlib.h> */
140083 /* #include <stdio.h> */
140084 /* #include <string.h> */
140088 ** Class derived from sqlite3_tokenizer
140090 typedef struct porter_tokenizer {
140091 sqlite3_tokenizer base; /* Base class */
140092 } porter_tokenizer;
140095 ** Class derived from sqlite3_tokenizer_cursor
140097 typedef struct porter_tokenizer_cursor {
140098 sqlite3_tokenizer_cursor base;
140099 const char *zInput; /* input we are tokenizing */
140100 int nInput; /* size of the input */
140101 int iOffset; /* current position in zInput */
140102 int iToken; /* index of next token to be returned */
140103 char *zToken; /* storage for current token */
140104 int nAllocated; /* space allocated to zToken buffer */
140105 } porter_tokenizer_cursor;
140109 ** Create a new tokenizer instance.
140111 static int porterCreate(
140112 int argc, const char * const *argv,
140113 sqlite3_tokenizer **ppTokenizer
140115 porter_tokenizer *t;
140117 UNUSED_PARAMETER(argc);
140118 UNUSED_PARAMETER(argv);
140120 t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
140121 if( t==NULL ) return SQLITE_NOMEM;
140122 memset(t, 0, sizeof(*t));
140123 *ppTokenizer = &t->base;
140124 return SQLITE_OK;
140128 ** Destroy a tokenizer
140130 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
140131 sqlite3_free(pTokenizer);
140132 return SQLITE_OK;
140136 ** Prepare to begin tokenizing a particular string. The input
140137 ** string to be tokenized is zInput[0..nInput-1]. A cursor
140138 ** used to incrementally tokenize this string is returned in
140139 ** *ppCursor.
140141 static int porterOpen(
140142 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
140143 const char *zInput, int nInput, /* String to be tokenized */
140144 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
140146 porter_tokenizer_cursor *c;
140148 UNUSED_PARAMETER(pTokenizer);
140150 c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
140151 if( c==NULL ) return SQLITE_NOMEM;
140153 c->zInput = zInput;
140154 if( zInput==0 ){
140155 c->nInput = 0;
140156 }else if( nInput<0 ){
140157 c->nInput = (int)strlen(zInput);
140158 }else{
140159 c->nInput = nInput;
140161 c->iOffset = 0; /* start tokenizing at the beginning */
140162 c->iToken = 0;
140163 c->zToken = NULL; /* no space allocated, yet. */
140164 c->nAllocated = 0;
140166 *ppCursor = &c->base;
140167 return SQLITE_OK;
140171 ** Close a tokenization cursor previously opened by a call to
140172 ** porterOpen() above.
140174 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
140175 porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
140176 sqlite3_free(c->zToken);
140177 sqlite3_free(c);
140178 return SQLITE_OK;
140181 ** Vowel or consonant
140183 static const char vOrCType[] = {
140184 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
140185 1, 1, 1, 2, 1
140189 ** isConsonant() and isVowel() determine if their first character in
140190 ** the string they point to is a consonant or a vowel, according
140191 ** to Porter ruls.
140193 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
140194 ** 'Y' is a consonant unless it follows another consonant,
140195 ** in which case it is a vowel.
140197 ** In these routine, the letters are in reverse order. So the 'y' rule
140198 ** is that 'y' is a consonant unless it is followed by another
140199 ** consonent.
140201 static int isVowel(const char*);
140202 static int isConsonant(const char *z){
140203 int j;
140204 char x = *z;
140205 if( x==0 ) return 0;
140206 assert( x>='a' && x<='z' );
140207 j = vOrCType[x-'a'];
140208 if( j<2 ) return j;
140209 return z[1]==0 || isVowel(z + 1);
140211 static int isVowel(const char *z){
140212 int j;
140213 char x = *z;
140214 if( x==0 ) return 0;
140215 assert( x>='a' && x<='z' );
140216 j = vOrCType[x-'a'];
140217 if( j<2 ) return 1-j;
140218 return isConsonant(z + 1);
140222 ** Let any sequence of one or more vowels be represented by V and let
140223 ** C be sequence of one or more consonants. Then every word can be
140224 ** represented as:
140226 ** [C] (VC){m} [V]
140228 ** In prose: A word is an optional consonant followed by zero or
140229 ** vowel-consonant pairs followed by an optional vowel. "m" is the
140230 ** number of vowel consonant pairs. This routine computes the value
140231 ** of m for the first i bytes of a word.
140233 ** Return true if the m-value for z is 1 or more. In other words,
140234 ** return true if z contains at least one vowel that is followed
140235 ** by a consonant.
140237 ** In this routine z[] is in reverse order. So we are really looking
140238 ** for an instance of of a consonant followed by a vowel.
140240 static int m_gt_0(const char *z){
140241 while( isVowel(z) ){ z++; }
140242 if( *z==0 ) return 0;
140243 while( isConsonant(z) ){ z++; }
140244 return *z!=0;
140247 /* Like mgt0 above except we are looking for a value of m which is
140248 ** exactly 1
140250 static int m_eq_1(const char *z){
140251 while( isVowel(z) ){ z++; }
140252 if( *z==0 ) return 0;
140253 while( isConsonant(z) ){ z++; }
140254 if( *z==0 ) return 0;
140255 while( isVowel(z) ){ z++; }
140256 if( *z==0 ) return 1;
140257 while( isConsonant(z) ){ z++; }
140258 return *z==0;
140261 /* Like mgt0 above except we are looking for a value of m>1 instead
140262 ** or m>0
140264 static int m_gt_1(const char *z){
140265 while( isVowel(z) ){ z++; }
140266 if( *z==0 ) return 0;
140267 while( isConsonant(z) ){ z++; }
140268 if( *z==0 ) return 0;
140269 while( isVowel(z) ){ z++; }
140270 if( *z==0 ) return 0;
140271 while( isConsonant(z) ){ z++; }
140272 return *z!=0;
140276 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
140278 static int hasVowel(const char *z){
140279 while( isConsonant(z) ){ z++; }
140280 return *z!=0;
140284 ** Return TRUE if the word ends in a double consonant.
140286 ** The text is reversed here. So we are really looking at
140287 ** the first two characters of z[].
140289 static int doubleConsonant(const char *z){
140290 return isConsonant(z) && z[0]==z[1];
140294 ** Return TRUE if the word ends with three letters which
140295 ** are consonant-vowel-consonent and where the final consonant
140296 ** is not 'w', 'x', or 'y'.
140298 ** The word is reversed here. So we are really checking the
140299 ** first three letters and the first one cannot be in [wxy].
140301 static int star_oh(const char *z){
140302 return
140303 isConsonant(z) &&
140304 z[0]!='w' && z[0]!='x' && z[0]!='y' &&
140305 isVowel(z+1) &&
140306 isConsonant(z+2);
140310 ** If the word ends with zFrom and xCond() is true for the stem
140311 ** of the word that preceeds the zFrom ending, then change the
140312 ** ending to zTo.
140314 ** The input word *pz and zFrom are both in reverse order. zTo
140315 ** is in normal order.
140317 ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
140318 ** match. Not that TRUE is returned even if xCond() fails and
140319 ** no substitution occurs.
140321 static int stem(
140322 char **pz, /* The word being stemmed (Reversed) */
140323 const char *zFrom, /* If the ending matches this... (Reversed) */
140324 const char *zTo, /* ... change the ending to this (not reversed) */
140325 int (*xCond)(const char*) /* Condition that must be true */
140327 char *z = *pz;
140328 while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
140329 if( *zFrom!=0 ) return 0;
140330 if( xCond && !xCond(z) ) return 1;
140331 while( *zTo ){
140332 *(--z) = *(zTo++);
140334 *pz = z;
140335 return 1;
140339 ** This is the fallback stemmer used when the porter stemmer is
140340 ** inappropriate. The input word is copied into the output with
140341 ** US-ASCII case folding. If the input word is too long (more
140342 ** than 20 bytes if it contains no digits or more than 6 bytes if
140343 ** it contains digits) then word is truncated to 20 or 6 bytes
140344 ** by taking 10 or 3 bytes from the beginning and end.
140346 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
140347 int i, mx, j;
140348 int hasDigit = 0;
140349 for(i=0; i<nIn; i++){
140350 char c = zIn[i];
140351 if( c>='A' && c<='Z' ){
140352 zOut[i] = c - 'A' + 'a';
140353 }else{
140354 if( c>='0' && c<='9' ) hasDigit = 1;
140355 zOut[i] = c;
140358 mx = hasDigit ? 3 : 10;
140359 if( nIn>mx*2 ){
140360 for(j=mx, i=nIn-mx; i<nIn; i++, j++){
140361 zOut[j] = zOut[i];
140363 i = j;
140365 zOut[i] = 0;
140366 *pnOut = i;
140371 ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
140372 ** zOut is at least big enough to hold nIn bytes. Write the actual
140373 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
140375 ** Any upper-case characters in the US-ASCII character set ([A-Z])
140376 ** are converted to lower case. Upper-case UTF characters are
140377 ** unchanged.
140379 ** Words that are longer than about 20 bytes are stemmed by retaining
140380 ** a few bytes from the beginning and the end of the word. If the
140381 ** word contains digits, 3 bytes are taken from the beginning and
140382 ** 3 bytes from the end. For long words without digits, 10 bytes
140383 ** are taken from each end. US-ASCII case folding still applies.
140385 ** If the input word contains not digits but does characters not
140386 ** in [a-zA-Z] then no stemming is attempted and this routine just
140387 ** copies the input into the input into the output with US-ASCII
140388 ** case folding.
140390 ** Stemming never increases the length of the word. So there is
140391 ** no chance of overflowing the zOut buffer.
140393 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
140394 int i, j;
140395 char zReverse[28];
140396 char *z, *z2;
140397 if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
140398 /* The word is too big or too small for the porter stemmer.
140399 ** Fallback to the copy stemmer */
140400 copy_stemmer(zIn, nIn, zOut, pnOut);
140401 return;
140403 for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
140404 char c = zIn[i];
140405 if( c>='A' && c<='Z' ){
140406 zReverse[j] = c + 'a' - 'A';
140407 }else if( c>='a' && c<='z' ){
140408 zReverse[j] = c;
140409 }else{
140410 /* The use of a character not in [a-zA-Z] means that we fallback
140411 ** to the copy stemmer */
140412 copy_stemmer(zIn, nIn, zOut, pnOut);
140413 return;
140416 memset(&zReverse[sizeof(zReverse)-5], 0, 5);
140417 z = &zReverse[j+1];
140420 /* Step 1a */
140421 if( z[0]=='s' ){
140423 !stem(&z, "sess", "ss", 0) &&
140424 !stem(&z, "sei", "i", 0) &&
140425 !stem(&z, "ss", "ss", 0)
140431 /* Step 1b */
140432 z2 = z;
140433 if( stem(&z, "dee", "ee", m_gt_0) ){
140434 /* Do nothing. The work was all in the test */
140435 }else if(
140436 (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
140437 && z!=z2
140439 if( stem(&z, "ta", "ate", 0) ||
140440 stem(&z, "lb", "ble", 0) ||
140441 stem(&z, "zi", "ize", 0) ){
140442 /* Do nothing. The work was all in the test */
140443 }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
140445 }else if( m_eq_1(z) && star_oh(z) ){
140446 *(--z) = 'e';
140450 /* Step 1c */
140451 if( z[0]=='y' && hasVowel(z+1) ){
140452 z[0] = 'i';
140455 /* Step 2 */
140456 switch( z[1] ){
140457 case 'a':
140458 if( !stem(&z, "lanoita", "ate", m_gt_0) ){
140459 stem(&z, "lanoit", "tion", m_gt_0);
140461 break;
140462 case 'c':
140463 if( !stem(&z, "icne", "ence", m_gt_0) ){
140464 stem(&z, "icna", "ance", m_gt_0);
140466 break;
140467 case 'e':
140468 stem(&z, "rezi", "ize", m_gt_0);
140469 break;
140470 case 'g':
140471 stem(&z, "igol", "log", m_gt_0);
140472 break;
140473 case 'l':
140474 if( !stem(&z, "ilb", "ble", m_gt_0)
140475 && !stem(&z, "illa", "al", m_gt_0)
140476 && !stem(&z, "iltne", "ent", m_gt_0)
140477 && !stem(&z, "ile", "e", m_gt_0)
140479 stem(&z, "ilsuo", "ous", m_gt_0);
140481 break;
140482 case 'o':
140483 if( !stem(&z, "noitazi", "ize", m_gt_0)
140484 && !stem(&z, "noita", "ate", m_gt_0)
140486 stem(&z, "rota", "ate", m_gt_0);
140488 break;
140489 case 's':
140490 if( !stem(&z, "msila", "al", m_gt_0)
140491 && !stem(&z, "ssenevi", "ive", m_gt_0)
140492 && !stem(&z, "ssenluf", "ful", m_gt_0)
140494 stem(&z, "ssensuo", "ous", m_gt_0);
140496 break;
140497 case 't':
140498 if( !stem(&z, "itila", "al", m_gt_0)
140499 && !stem(&z, "itivi", "ive", m_gt_0)
140501 stem(&z, "itilib", "ble", m_gt_0);
140503 break;
140506 /* Step 3 */
140507 switch( z[0] ){
140508 case 'e':
140509 if( !stem(&z, "etaci", "ic", m_gt_0)
140510 && !stem(&z, "evita", "", m_gt_0)
140512 stem(&z, "ezila", "al", m_gt_0);
140514 break;
140515 case 'i':
140516 stem(&z, "itici", "ic", m_gt_0);
140517 break;
140518 case 'l':
140519 if( !stem(&z, "laci", "ic", m_gt_0) ){
140520 stem(&z, "luf", "", m_gt_0);
140522 break;
140523 case 's':
140524 stem(&z, "ssen", "", m_gt_0);
140525 break;
140528 /* Step 4 */
140529 switch( z[1] ){
140530 case 'a':
140531 if( z[0]=='l' && m_gt_1(z+2) ){
140532 z += 2;
140534 break;
140535 case 'c':
140536 if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
140537 z += 4;
140539 break;
140540 case 'e':
140541 if( z[0]=='r' && m_gt_1(z+2) ){
140542 z += 2;
140544 break;
140545 case 'i':
140546 if( z[0]=='c' && m_gt_1(z+2) ){
140547 z += 2;
140549 break;
140550 case 'l':
140551 if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
140552 z += 4;
140554 break;
140555 case 'n':
140556 if( z[0]=='t' ){
140557 if( z[2]=='a' ){
140558 if( m_gt_1(z+3) ){
140559 z += 3;
140561 }else if( z[2]=='e' ){
140562 if( !stem(&z, "tneme", "", m_gt_1)
140563 && !stem(&z, "tnem", "", m_gt_1)
140565 stem(&z, "tne", "", m_gt_1);
140569 break;
140570 case 'o':
140571 if( z[0]=='u' ){
140572 if( m_gt_1(z+2) ){
140573 z += 2;
140575 }else if( z[3]=='s' || z[3]=='t' ){
140576 stem(&z, "noi", "", m_gt_1);
140578 break;
140579 case 's':
140580 if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
140581 z += 3;
140583 break;
140584 case 't':
140585 if( !stem(&z, "eta", "", m_gt_1) ){
140586 stem(&z, "iti", "", m_gt_1);
140588 break;
140589 case 'u':
140590 if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
140591 z += 3;
140593 break;
140594 case 'v':
140595 case 'z':
140596 if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
140597 z += 3;
140599 break;
140602 /* Step 5a */
140603 if( z[0]=='e' ){
140604 if( m_gt_1(z+1) ){
140606 }else if( m_eq_1(z+1) && !star_oh(z+1) ){
140611 /* Step 5b */
140612 if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
140616 /* z[] is now the stemmed word in reverse order. Flip it back
140617 ** around into forward order and return.
140619 *pnOut = i = (int)strlen(z);
140620 zOut[i] = 0;
140621 while( *z ){
140622 zOut[--i] = *(z++);
140627 ** Characters that can be part of a token. We assume any character
140628 ** whose value is greater than 0x80 (any UTF character) can be
140629 ** part of a token. In other words, delimiters all must have
140630 ** values of 0x7f or lower.
140632 static const char porterIdChar[] = {
140633 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
140634 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
140635 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
140636 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
140637 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
140638 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
140640 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
140643 ** Extract the next token from a tokenization cursor. The cursor must
140644 ** have been opened by a prior call to porterOpen().
140646 static int porterNext(
140647 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
140648 const char **pzToken, /* OUT: *pzToken is the token text */
140649 int *pnBytes, /* OUT: Number of bytes in token */
140650 int *piStartOffset, /* OUT: Starting offset of token */
140651 int *piEndOffset, /* OUT: Ending offset of token */
140652 int *piPosition /* OUT: Position integer of token */
140654 porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
140655 const char *z = c->zInput;
140657 while( c->iOffset<c->nInput ){
140658 int iStartOffset, ch;
140660 /* Scan past delimiter characters */
140661 while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
140662 c->iOffset++;
140665 /* Count non-delimiter characters. */
140666 iStartOffset = c->iOffset;
140667 while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
140668 c->iOffset++;
140671 if( c->iOffset>iStartOffset ){
140672 int n = c->iOffset-iStartOffset;
140673 if( n>c->nAllocated ){
140674 char *pNew;
140675 c->nAllocated = n+20;
140676 pNew = sqlite3_realloc(c->zToken, c->nAllocated);
140677 if( !pNew ) return SQLITE_NOMEM;
140678 c->zToken = pNew;
140680 porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
140681 *pzToken = c->zToken;
140682 *piStartOffset = iStartOffset;
140683 *piEndOffset = c->iOffset;
140684 *piPosition = c->iToken++;
140685 return SQLITE_OK;
140688 return SQLITE_DONE;
140692 ** The set of routines that implement the porter-stemmer tokenizer
140694 static const sqlite3_tokenizer_module porterTokenizerModule = {
140696 porterCreate,
140697 porterDestroy,
140698 porterOpen,
140699 porterClose,
140700 porterNext,
140705 ** Allocate a new porter tokenizer. Return a pointer to the new
140706 ** tokenizer in *ppModule
140708 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
140709 sqlite3_tokenizer_module const**ppModule
140711 *ppModule = &porterTokenizerModule;
140714 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
140716 /************** End of fts3_porter.c *****************************************/
140717 /************** Begin file fts3_tokenizer.c **********************************/
140719 ** 2007 June 22
140721 ** The author disclaims copyright to this source code. In place of
140722 ** a legal notice, here is a blessing:
140724 ** May you do good and not evil.
140725 ** May you find forgiveness for yourself and forgive others.
140726 ** May you share freely, never taking more than you give.
140728 ******************************************************************************
140730 ** This is part of an SQLite module implementing full-text search.
140731 ** This particular file implements the generic tokenizer interface.
140735 ** The code in this file is only compiled if:
140737 ** * The FTS3 module is being built as an extension
140738 ** (in which case SQLITE_CORE is not defined), or
140740 ** * The FTS3 module is being built into the core of
140741 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
140743 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
140745 /* #include <assert.h> */
140746 /* #include <string.h> */
140749 ** Implementation of the SQL scalar function for accessing the underlying
140750 ** hash table. This function may be called as follows:
140752 ** SELECT <function-name>(<key-name>);
140753 ** SELECT <function-name>(<key-name>, <pointer>);
140755 ** where <function-name> is the name passed as the second argument
140756 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
140758 ** If the <pointer> argument is specified, it must be a blob value
140759 ** containing a pointer to be stored as the hash data corresponding
140760 ** to the string <key-name>. If <pointer> is not specified, then
140761 ** the string <key-name> must already exist in the has table. Otherwise,
140762 ** an error is returned.
140764 ** Whether or not the <pointer> argument is specified, the value returned
140765 ** is a blob containing the pointer stored as the hash data corresponding
140766 ** to string <key-name> (after the hash-table is updated, if applicable).
140768 static void scalarFunc(
140769 sqlite3_context *context,
140770 int argc,
140771 sqlite3_value **argv
140773 Fts3Hash *pHash;
140774 void *pPtr = 0;
140775 const unsigned char *zName;
140776 int nName;
140778 assert( argc==1 || argc==2 );
140780 pHash = (Fts3Hash *)sqlite3_user_data(context);
140782 zName = sqlite3_value_text(argv[0]);
140783 nName = sqlite3_value_bytes(argv[0])+1;
140785 if( argc==2 ){
140786 void *pOld;
140787 int n = sqlite3_value_bytes(argv[1]);
140788 if( n!=sizeof(pPtr) ){
140789 sqlite3_result_error(context, "argument type mismatch", -1);
140790 return;
140792 pPtr = *(void **)sqlite3_value_blob(argv[1]);
140793 pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
140794 if( pOld==pPtr ){
140795 sqlite3_result_error(context, "out of memory", -1);
140796 return;
140798 }else{
140799 pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
140800 if( !pPtr ){
140801 char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
140802 sqlite3_result_error(context, zErr, -1);
140803 sqlite3_free(zErr);
140804 return;
140808 sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
140811 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
140812 static const char isFtsIdChar[] = {
140813 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
140814 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
140815 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
140816 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
140817 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
140818 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
140819 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
140820 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
140822 return (c&0x80 || isFtsIdChar[(int)(c)]);
140825 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
140826 const char *z1;
140827 const char *z2 = 0;
140829 /* Find the start of the next token. */
140830 z1 = zStr;
140831 while( z2==0 ){
140832 char c = *z1;
140833 switch( c ){
140834 case '\0': return 0; /* No more tokens here */
140835 case '\'':
140836 case '"':
140837 case '`': {
140838 z2 = z1;
140839 while( *++z2 && (*z2!=c || *++z2==c) );
140840 break;
140842 case '[':
140843 z2 = &z1[1];
140844 while( *z2 && z2[0]!=']' ) z2++;
140845 if( *z2 ) z2++;
140846 break;
140848 default:
140849 if( sqlite3Fts3IsIdChar(*z1) ){
140850 z2 = &z1[1];
140851 while( sqlite3Fts3IsIdChar(*z2) ) z2++;
140852 }else{
140853 z1++;
140858 *pn = (int)(z2-z1);
140859 return z1;
140862 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
140863 Fts3Hash *pHash, /* Tokenizer hash table */
140864 const char *zArg, /* Tokenizer name */
140865 sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
140866 char **pzErr /* OUT: Set to malloced error message */
140868 int rc;
140869 char *z = (char *)zArg;
140870 int n = 0;
140871 char *zCopy;
140872 char *zEnd; /* Pointer to nul-term of zCopy */
140873 sqlite3_tokenizer_module *m;
140875 zCopy = sqlite3_mprintf("%s", zArg);
140876 if( !zCopy ) return SQLITE_NOMEM;
140877 zEnd = &zCopy[strlen(zCopy)];
140879 z = (char *)sqlite3Fts3NextToken(zCopy, &n);
140880 z[n] = '\0';
140881 sqlite3Fts3Dequote(z);
140883 m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
140884 if( !m ){
140885 *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
140886 rc = SQLITE_ERROR;
140887 }else{
140888 char const **aArg = 0;
140889 int iArg = 0;
140890 z = &z[n+1];
140891 while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
140892 int nNew = sizeof(char *)*(iArg+1);
140893 char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
140894 if( !aNew ){
140895 sqlite3_free(zCopy);
140896 sqlite3_free((void *)aArg);
140897 return SQLITE_NOMEM;
140899 aArg = aNew;
140900 aArg[iArg++] = z;
140901 z[n] = '\0';
140902 sqlite3Fts3Dequote(z);
140903 z = &z[n+1];
140905 rc = m->xCreate(iArg, aArg, ppTok);
140906 assert( rc!=SQLITE_OK || *ppTok );
140907 if( rc!=SQLITE_OK ){
140908 *pzErr = sqlite3_mprintf("unknown tokenizer");
140909 }else{
140910 (*ppTok)->pModule = m;
140912 sqlite3_free((void *)aArg);
140915 sqlite3_free(zCopy);
140916 return rc;
140920 #ifdef SQLITE_TEST
140922 #include <tcl.h>
140923 /* #include <string.h> */
140926 ** Implementation of a special SQL scalar function for testing tokenizers
140927 ** designed to be used in concert with the Tcl testing framework. This
140928 ** function must be called with two or more arguments:
140930 ** SELECT <function-name>(<key-name>, ..., <input-string>);
140932 ** where <function-name> is the name passed as the second argument
140933 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
140934 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
140936 ** The return value is a string that may be interpreted as a Tcl
140937 ** list. For each token in the <input-string>, three elements are
140938 ** added to the returned list. The first is the token position, the
140939 ** second is the token text (folded, stemmed, etc.) and the third is the
140940 ** substring of <input-string> associated with the token. For example,
140941 ** using the built-in "simple" tokenizer:
140943 ** SELECT fts_tokenizer_test('simple', 'I don't see how');
140945 ** will return the string:
140947 ** "{0 i I 1 dont don't 2 see see 3 how how}"
140950 static void testFunc(
140951 sqlite3_context *context,
140952 int argc,
140953 sqlite3_value **argv
140955 Fts3Hash *pHash;
140956 sqlite3_tokenizer_module *p;
140957 sqlite3_tokenizer *pTokenizer = 0;
140958 sqlite3_tokenizer_cursor *pCsr = 0;
140960 const char *zErr = 0;
140962 const char *zName;
140963 int nName;
140964 const char *zInput;
140965 int nInput;
140967 const char *azArg[64];
140969 const char *zToken;
140970 int nToken = 0;
140971 int iStart = 0;
140972 int iEnd = 0;
140973 int iPos = 0;
140974 int i;
140976 Tcl_Obj *pRet;
140978 if( argc<2 ){
140979 sqlite3_result_error(context, "insufficient arguments", -1);
140980 return;
140983 nName = sqlite3_value_bytes(argv[0]);
140984 zName = (const char *)sqlite3_value_text(argv[0]);
140985 nInput = sqlite3_value_bytes(argv[argc-1]);
140986 zInput = (const char *)sqlite3_value_text(argv[argc-1]);
140988 pHash = (Fts3Hash *)sqlite3_user_data(context);
140989 p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
140991 if( !p ){
140992 char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
140993 sqlite3_result_error(context, zErr, -1);
140994 sqlite3_free(zErr);
140995 return;
140998 pRet = Tcl_NewObj();
140999 Tcl_IncrRefCount(pRet);
141001 for(i=1; i<argc-1; i++){
141002 azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
141005 if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
141006 zErr = "error in xCreate()";
141007 goto finish;
141009 pTokenizer->pModule = p;
141010 if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
141011 zErr = "error in xOpen()";
141012 goto finish;
141015 while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
141016 Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
141017 Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
141018 zToken = &zInput[iStart];
141019 nToken = iEnd-iStart;
141020 Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
141023 if( SQLITE_OK!=p->xClose(pCsr) ){
141024 zErr = "error in xClose()";
141025 goto finish;
141027 if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
141028 zErr = "error in xDestroy()";
141029 goto finish;
141032 finish:
141033 if( zErr ){
141034 sqlite3_result_error(context, zErr, -1);
141035 }else{
141036 sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
141038 Tcl_DecrRefCount(pRet);
141041 static
141042 int registerTokenizer(
141043 sqlite3 *db,
141044 char *zName,
141045 const sqlite3_tokenizer_module *p
141047 int rc;
141048 sqlite3_stmt *pStmt;
141049 const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
141051 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
141052 if( rc!=SQLITE_OK ){
141053 return rc;
141056 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
141057 sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
141058 sqlite3_step(pStmt);
141060 return sqlite3_finalize(pStmt);
141063 static
141064 int queryTokenizer(
141065 sqlite3 *db,
141066 char *zName,
141067 const sqlite3_tokenizer_module **pp
141069 int rc;
141070 sqlite3_stmt *pStmt;
141071 const char zSql[] = "SELECT fts3_tokenizer(?)";
141073 *pp = 0;
141074 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
141075 if( rc!=SQLITE_OK ){
141076 return rc;
141079 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
141080 if( SQLITE_ROW==sqlite3_step(pStmt) ){
141081 if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
141082 memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
141086 return sqlite3_finalize(pStmt);
141089 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
141092 ** Implementation of the scalar function fts3_tokenizer_internal_test().
141093 ** This function is used for testing only, it is not included in the
141094 ** build unless SQLITE_TEST is defined.
141096 ** The purpose of this is to test that the fts3_tokenizer() function
141097 ** can be used as designed by the C-code in the queryTokenizer and
141098 ** registerTokenizer() functions above. These two functions are repeated
141099 ** in the README.tokenizer file as an example, so it is important to
141100 ** test them.
141102 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
141103 ** function with no arguments. An assert() will fail if a problem is
141104 ** detected. i.e.:
141106 ** SELECT fts3_tokenizer_internal_test();
141109 static void intTestFunc(
141110 sqlite3_context *context,
141111 int argc,
141112 sqlite3_value **argv
141114 int rc;
141115 const sqlite3_tokenizer_module *p1;
141116 const sqlite3_tokenizer_module *p2;
141117 sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
141119 UNUSED_PARAMETER(argc);
141120 UNUSED_PARAMETER(argv);
141122 /* Test the query function */
141123 sqlite3Fts3SimpleTokenizerModule(&p1);
141124 rc = queryTokenizer(db, "simple", &p2);
141125 assert( rc==SQLITE_OK );
141126 assert( p1==p2 );
141127 rc = queryTokenizer(db, "nosuchtokenizer", &p2);
141128 assert( rc==SQLITE_ERROR );
141129 assert( p2==0 );
141130 assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
141132 /* Test the storage function */
141133 rc = registerTokenizer(db, "nosuchtokenizer", p1);
141134 assert( rc==SQLITE_OK );
141135 rc = queryTokenizer(db, "nosuchtokenizer", &p2);
141136 assert( rc==SQLITE_OK );
141137 assert( p2==p1 );
141139 sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
141142 #endif
141145 ** Set up SQL objects in database db used to access the contents of
141146 ** the hash table pointed to by argument pHash. The hash table must
141147 ** been initialized to use string keys, and to take a private copy
141148 ** of the key when a value is inserted. i.e. by a call similar to:
141150 ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
141152 ** This function adds a scalar function (see header comment above
141153 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
141154 ** defined at compilation time, a temporary virtual table (see header
141155 ** comment above struct HashTableVtab) to the database schema. Both
141156 ** provide read/write access to the contents of *pHash.
141158 ** The third argument to this function, zName, is used as the name
141159 ** of both the scalar and, if created, the virtual table.
141161 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
141162 sqlite3 *db,
141163 Fts3Hash *pHash,
141164 const char *zName
141166 int rc = SQLITE_OK;
141167 void *p = (void *)pHash;
141168 const int any = SQLITE_ANY;
141170 #ifdef SQLITE_TEST
141171 char *zTest = 0;
141172 char *zTest2 = 0;
141173 void *pdb = (void *)db;
141174 zTest = sqlite3_mprintf("%s_test", zName);
141175 zTest2 = sqlite3_mprintf("%s_internal_test", zName);
141176 if( !zTest || !zTest2 ){
141177 rc = SQLITE_NOMEM;
141179 #endif
141181 if( SQLITE_OK==rc ){
141182 rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
141184 if( SQLITE_OK==rc ){
141185 rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
141187 #ifdef SQLITE_TEST
141188 if( SQLITE_OK==rc ){
141189 rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
141191 if( SQLITE_OK==rc ){
141192 rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
141194 #endif
141196 #ifdef SQLITE_TEST
141197 sqlite3_free(zTest);
141198 sqlite3_free(zTest2);
141199 #endif
141201 return rc;
141204 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
141206 /************** End of fts3_tokenizer.c **************************************/
141207 /************** Begin file fts3_tokenizer1.c *********************************/
141209 ** 2006 Oct 10
141211 ** The author disclaims copyright to this source code. In place of
141212 ** a legal notice, here is a blessing:
141214 ** May you do good and not evil.
141215 ** May you find forgiveness for yourself and forgive others.
141216 ** May you share freely, never taking more than you give.
141218 ******************************************************************************
141220 ** Implementation of the "simple" full-text-search tokenizer.
141224 ** The code in this file is only compiled if:
141226 ** * The FTS3 module is being built as an extension
141227 ** (in which case SQLITE_CORE is not defined), or
141229 ** * The FTS3 module is being built into the core of
141230 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
141232 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
141234 /* #include <assert.h> */
141235 /* #include <stdlib.h> */
141236 /* #include <stdio.h> */
141237 /* #include <string.h> */
141240 typedef struct simple_tokenizer {
141241 sqlite3_tokenizer base;
141242 char delim[128]; /* flag ASCII delimiters */
141243 } simple_tokenizer;
141245 typedef struct simple_tokenizer_cursor {
141246 sqlite3_tokenizer_cursor base;
141247 const char *pInput; /* input we are tokenizing */
141248 int nBytes; /* size of the input */
141249 int iOffset; /* current position in pInput */
141250 int iToken; /* index of next token to be returned */
141251 char *pToken; /* storage for current token */
141252 int nTokenAllocated; /* space allocated to zToken buffer */
141253 } simple_tokenizer_cursor;
141256 static int simpleDelim(simple_tokenizer *t, unsigned char c){
141257 return c<0x80 && t->delim[c];
141259 static int fts3_isalnum(int x){
141260 return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
141264 ** Create a new tokenizer instance.
141266 static int simpleCreate(
141267 int argc, const char * const *argv,
141268 sqlite3_tokenizer **ppTokenizer
141270 simple_tokenizer *t;
141272 t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
141273 if( t==NULL ) return SQLITE_NOMEM;
141274 memset(t, 0, sizeof(*t));
141276 /* TODO(shess) Delimiters need to remain the same from run to run,
141277 ** else we need to reindex. One solution would be a meta-table to
141278 ** track such information in the database, then we'd only want this
141279 ** information on the initial create.
141281 if( argc>1 ){
141282 int i, n = (int)strlen(argv[1]);
141283 for(i=0; i<n; i++){
141284 unsigned char ch = argv[1][i];
141285 /* We explicitly don't support UTF-8 delimiters for now. */
141286 if( ch>=0x80 ){
141287 sqlite3_free(t);
141288 return SQLITE_ERROR;
141290 t->delim[ch] = 1;
141292 } else {
141293 /* Mark non-alphanumeric ASCII characters as delimiters */
141294 int i;
141295 for(i=1; i<0x80; i++){
141296 t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
141300 *ppTokenizer = &t->base;
141301 return SQLITE_OK;
141305 ** Destroy a tokenizer
141307 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
141308 sqlite3_free(pTokenizer);
141309 return SQLITE_OK;
141313 ** Prepare to begin tokenizing a particular string. The input
141314 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
141315 ** used to incrementally tokenize this string is returned in
141316 ** *ppCursor.
141318 static int simpleOpen(
141319 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
141320 const char *pInput, int nBytes, /* String to be tokenized */
141321 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
141323 simple_tokenizer_cursor *c;
141325 UNUSED_PARAMETER(pTokenizer);
141327 c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
141328 if( c==NULL ) return SQLITE_NOMEM;
141330 c->pInput = pInput;
141331 if( pInput==0 ){
141332 c->nBytes = 0;
141333 }else if( nBytes<0 ){
141334 c->nBytes = (int)strlen(pInput);
141335 }else{
141336 c->nBytes = nBytes;
141338 c->iOffset = 0; /* start tokenizing at the beginning */
141339 c->iToken = 0;
141340 c->pToken = NULL; /* no space allocated, yet. */
141341 c->nTokenAllocated = 0;
141343 *ppCursor = &c->base;
141344 return SQLITE_OK;
141348 ** Close a tokenization cursor previously opened by a call to
141349 ** simpleOpen() above.
141351 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
141352 simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
141353 sqlite3_free(c->pToken);
141354 sqlite3_free(c);
141355 return SQLITE_OK;
141359 ** Extract the next token from a tokenization cursor. The cursor must
141360 ** have been opened by a prior call to simpleOpen().
141362 static int simpleNext(
141363 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
141364 const char **ppToken, /* OUT: *ppToken is the token text */
141365 int *pnBytes, /* OUT: Number of bytes in token */
141366 int *piStartOffset, /* OUT: Starting offset of token */
141367 int *piEndOffset, /* OUT: Ending offset of token */
141368 int *piPosition /* OUT: Position integer of token */
141370 simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
141371 simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
141372 unsigned char *p = (unsigned char *)c->pInput;
141374 while( c->iOffset<c->nBytes ){
141375 int iStartOffset;
141377 /* Scan past delimiter characters */
141378 while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
141379 c->iOffset++;
141382 /* Count non-delimiter characters. */
141383 iStartOffset = c->iOffset;
141384 while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
141385 c->iOffset++;
141388 if( c->iOffset>iStartOffset ){
141389 int i, n = c->iOffset-iStartOffset;
141390 if( n>c->nTokenAllocated ){
141391 char *pNew;
141392 c->nTokenAllocated = n+20;
141393 pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
141394 if( !pNew ) return SQLITE_NOMEM;
141395 c->pToken = pNew;
141397 for(i=0; i<n; i++){
141398 /* TODO(shess) This needs expansion to handle UTF-8
141399 ** case-insensitivity.
141401 unsigned char ch = p[iStartOffset+i];
141402 c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
141404 *ppToken = c->pToken;
141405 *pnBytes = n;
141406 *piStartOffset = iStartOffset;
141407 *piEndOffset = c->iOffset;
141408 *piPosition = c->iToken++;
141410 return SQLITE_OK;
141413 return SQLITE_DONE;
141417 ** The set of routines that implement the simple tokenizer
141419 static const sqlite3_tokenizer_module simpleTokenizerModule = {
141421 simpleCreate,
141422 simpleDestroy,
141423 simpleOpen,
141424 simpleClose,
141425 simpleNext,
141430 ** Allocate a new simple tokenizer. Return a pointer to the new
141431 ** tokenizer in *ppModule
141433 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
141434 sqlite3_tokenizer_module const**ppModule
141436 *ppModule = &simpleTokenizerModule;
141439 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
141441 /************** End of fts3_tokenizer1.c *************************************/
141442 /************** Begin file fts3_tokenize_vtab.c ******************************/
141444 ** 2013 Apr 22
141446 ** The author disclaims copyright to this source code. In place of
141447 ** a legal notice, here is a blessing:
141449 ** May you do good and not evil.
141450 ** May you find forgiveness for yourself and forgive others.
141451 ** May you share freely, never taking more than you give.
141453 ******************************************************************************
141455 ** This file contains code for the "fts3tokenize" virtual table module.
141456 ** An fts3tokenize virtual table is created as follows:
141458 ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
141459 ** <tokenizer-name>, <arg-1>, ...
141460 ** );
141462 ** The table created has the following schema:
141464 ** CREATE TABLE <tbl>(input, token, start, end, position)
141466 ** When queried, the query must include a WHERE clause of type:
141468 ** input = <string>
141470 ** The virtual table module tokenizes this <string>, using the FTS3
141471 ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
141472 ** statement and returns one row for each token in the result. With
141473 ** fields set as follows:
141475 ** input: Always set to a copy of <string>
141476 ** token: A token from the input.
141477 ** start: Byte offset of the token within the input <string>.
141478 ** end: Byte offset of the byte immediately following the end of the
141479 ** token within the input string.
141480 ** pos: Token offset of token within input.
141483 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
141485 /* #include <string.h> */
141486 /* #include <assert.h> */
141488 typedef struct Fts3tokTable Fts3tokTable;
141489 typedef struct Fts3tokCursor Fts3tokCursor;
141492 ** Virtual table structure.
141494 struct Fts3tokTable {
141495 sqlite3_vtab base; /* Base class used by SQLite core */
141496 const sqlite3_tokenizer_module *pMod;
141497 sqlite3_tokenizer *pTok;
141501 ** Virtual table cursor structure.
141503 struct Fts3tokCursor {
141504 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
141505 char *zInput; /* Input string */
141506 sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
141507 int iRowid; /* Current 'rowid' value */
141508 const char *zToken; /* Current 'token' value */
141509 int nToken; /* Size of zToken in bytes */
141510 int iStart; /* Current 'start' value */
141511 int iEnd; /* Current 'end' value */
141512 int iPos; /* Current 'pos' value */
141516 ** Query FTS for the tokenizer implementation named zName.
141518 static int fts3tokQueryTokenizer(
141519 Fts3Hash *pHash,
141520 const char *zName,
141521 const sqlite3_tokenizer_module **pp,
141522 char **pzErr
141524 sqlite3_tokenizer_module *p;
141525 int nName = (int)strlen(zName);
141527 p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
141528 if( !p ){
141529 *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
141530 return SQLITE_ERROR;
141533 *pp = p;
141534 return SQLITE_OK;
141538 ** The second argument, argv[], is an array of pointers to nul-terminated
141539 ** strings. This function makes a copy of the array and strings into a
141540 ** single block of memory. It then dequotes any of the strings that appear
141541 ** to be quoted.
141543 ** If successful, output parameter *pazDequote is set to point at the
141544 ** array of dequoted strings and SQLITE_OK is returned. The caller is
141545 ** responsible for eventually calling sqlite3_free() to free the array
141546 ** in this case. Or, if an error occurs, an SQLite error code is returned.
141547 ** The final value of *pazDequote is undefined in this case.
141549 static int fts3tokDequoteArray(
141550 int argc, /* Number of elements in argv[] */
141551 const char * const *argv, /* Input array */
141552 char ***pazDequote /* Output array */
141554 int rc = SQLITE_OK; /* Return code */
141555 if( argc==0 ){
141556 *pazDequote = 0;
141557 }else{
141558 int i;
141559 int nByte = 0;
141560 char **azDequote;
141562 for(i=0; i<argc; i++){
141563 nByte += (int)(strlen(argv[i]) + 1);
141566 *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
141567 if( azDequote==0 ){
141568 rc = SQLITE_NOMEM;
141569 }else{
141570 char *pSpace = (char *)&azDequote[argc];
141571 for(i=0; i<argc; i++){
141572 int n = (int)strlen(argv[i]);
141573 azDequote[i] = pSpace;
141574 memcpy(pSpace, argv[i], n+1);
141575 sqlite3Fts3Dequote(pSpace);
141576 pSpace += (n+1);
141581 return rc;
141585 ** Schema of the tokenizer table.
141587 #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
141590 ** This function does all the work for both the xConnect and xCreate methods.
141591 ** These tables have no persistent representation of their own, so xConnect
141592 ** and xCreate are identical operations.
141594 ** argv[0]: module name
141595 ** argv[1]: database name
141596 ** argv[2]: table name
141597 ** argv[3]: first argument (tokenizer name)
141599 static int fts3tokConnectMethod(
141600 sqlite3 *db, /* Database connection */
141601 void *pHash, /* Hash table of tokenizers */
141602 int argc, /* Number of elements in argv array */
141603 const char * const *argv, /* xCreate/xConnect argument array */
141604 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
141605 char **pzErr /* OUT: sqlite3_malloc'd error message */
141607 Fts3tokTable *pTab;
141608 const sqlite3_tokenizer_module *pMod = 0;
141609 sqlite3_tokenizer *pTok = 0;
141610 int rc;
141611 char **azDequote = 0;
141612 int nDequote;
141614 rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
141615 if( rc!=SQLITE_OK ) return rc;
141617 nDequote = argc-3;
141618 rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
141620 if( rc==SQLITE_OK ){
141621 const char *zModule;
141622 if( nDequote<1 ){
141623 zModule = "simple";
141624 }else{
141625 zModule = azDequote[0];
141627 rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
141630 assert( (rc==SQLITE_OK)==(pMod!=0) );
141631 if( rc==SQLITE_OK ){
141632 const char * const *azArg = (const char * const *)&azDequote[1];
141633 rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
141636 if( rc==SQLITE_OK ){
141637 pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
141638 if( pTab==0 ){
141639 rc = SQLITE_NOMEM;
141643 if( rc==SQLITE_OK ){
141644 memset(pTab, 0, sizeof(Fts3tokTable));
141645 pTab->pMod = pMod;
141646 pTab->pTok = pTok;
141647 *ppVtab = &pTab->base;
141648 }else{
141649 if( pTok ){
141650 pMod->xDestroy(pTok);
141654 sqlite3_free(azDequote);
141655 return rc;
141659 ** This function does the work for both the xDisconnect and xDestroy methods.
141660 ** These tables have no persistent representation of their own, so xDisconnect
141661 ** and xDestroy are identical operations.
141663 static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
141664 Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
141666 pTab->pMod->xDestroy(pTab->pTok);
141667 sqlite3_free(pTab);
141668 return SQLITE_OK;
141672 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
141674 static int fts3tokBestIndexMethod(
141675 sqlite3_vtab *pVTab,
141676 sqlite3_index_info *pInfo
141678 int i;
141679 UNUSED_PARAMETER(pVTab);
141681 for(i=0; i<pInfo->nConstraint; i++){
141682 if( pInfo->aConstraint[i].usable
141683 && pInfo->aConstraint[i].iColumn==0
141684 && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
141686 pInfo->idxNum = 1;
141687 pInfo->aConstraintUsage[i].argvIndex = 1;
141688 pInfo->aConstraintUsage[i].omit = 1;
141689 pInfo->estimatedCost = 1;
141690 return SQLITE_OK;
141694 pInfo->idxNum = 0;
141695 assert( pInfo->estimatedCost>1000000.0 );
141697 return SQLITE_OK;
141701 ** xOpen - Open a cursor.
141703 static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
141704 Fts3tokCursor *pCsr;
141705 UNUSED_PARAMETER(pVTab);
141707 pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
141708 if( pCsr==0 ){
141709 return SQLITE_NOMEM;
141711 memset(pCsr, 0, sizeof(Fts3tokCursor));
141713 *ppCsr = (sqlite3_vtab_cursor *)pCsr;
141714 return SQLITE_OK;
141718 ** Reset the tokenizer cursor passed as the only argument. As if it had
141719 ** just been returned by fts3tokOpenMethod().
141721 static void fts3tokResetCursor(Fts3tokCursor *pCsr){
141722 if( pCsr->pCsr ){
141723 Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
141724 pTab->pMod->xClose(pCsr->pCsr);
141725 pCsr->pCsr = 0;
141727 sqlite3_free(pCsr->zInput);
141728 pCsr->zInput = 0;
141729 pCsr->zToken = 0;
141730 pCsr->nToken = 0;
141731 pCsr->iStart = 0;
141732 pCsr->iEnd = 0;
141733 pCsr->iPos = 0;
141734 pCsr->iRowid = 0;
141738 ** xClose - Close a cursor.
141740 static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
141741 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
141743 fts3tokResetCursor(pCsr);
141744 sqlite3_free(pCsr);
141745 return SQLITE_OK;
141749 ** xNext - Advance the cursor to the next row, if any.
141751 static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
141752 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
141753 Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
141754 int rc; /* Return code */
141756 pCsr->iRowid++;
141757 rc = pTab->pMod->xNext(pCsr->pCsr,
141758 &pCsr->zToken, &pCsr->nToken,
141759 &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
141762 if( rc!=SQLITE_OK ){
141763 fts3tokResetCursor(pCsr);
141764 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
141767 return rc;
141771 ** xFilter - Initialize a cursor to point at the start of its data.
141773 static int fts3tokFilterMethod(
141774 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
141775 int idxNum, /* Strategy index */
141776 const char *idxStr, /* Unused */
141777 int nVal, /* Number of elements in apVal */
141778 sqlite3_value **apVal /* Arguments for the indexing scheme */
141780 int rc = SQLITE_ERROR;
141781 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
141782 Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
141783 UNUSED_PARAMETER(idxStr);
141784 UNUSED_PARAMETER(nVal);
141786 fts3tokResetCursor(pCsr);
141787 if( idxNum==1 ){
141788 const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
141789 int nByte = sqlite3_value_bytes(apVal[0]);
141790 pCsr->zInput = sqlite3_malloc(nByte+1);
141791 if( pCsr->zInput==0 ){
141792 rc = SQLITE_NOMEM;
141793 }else{
141794 memcpy(pCsr->zInput, zByte, nByte);
141795 pCsr->zInput[nByte] = 0;
141796 rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
141797 if( rc==SQLITE_OK ){
141798 pCsr->pCsr->pTokenizer = pTab->pTok;
141803 if( rc!=SQLITE_OK ) return rc;
141804 return fts3tokNextMethod(pCursor);
141808 ** xEof - Return true if the cursor is at EOF, or false otherwise.
141810 static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
141811 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
141812 return (pCsr->zToken==0);
141816 ** xColumn - Return a column value.
141818 static int fts3tokColumnMethod(
141819 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
141820 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
141821 int iCol /* Index of column to read value from */
141823 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
141825 /* CREATE TABLE x(input, token, start, end, position) */
141826 switch( iCol ){
141827 case 0:
141828 sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
141829 break;
141830 case 1:
141831 sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
141832 break;
141833 case 2:
141834 sqlite3_result_int(pCtx, pCsr->iStart);
141835 break;
141836 case 3:
141837 sqlite3_result_int(pCtx, pCsr->iEnd);
141838 break;
141839 default:
141840 assert( iCol==4 );
141841 sqlite3_result_int(pCtx, pCsr->iPos);
141842 break;
141844 return SQLITE_OK;
141848 ** xRowid - Return the current rowid for the cursor.
141850 static int fts3tokRowidMethod(
141851 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
141852 sqlite_int64 *pRowid /* OUT: Rowid value */
141854 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
141855 *pRowid = (sqlite3_int64)pCsr->iRowid;
141856 return SQLITE_OK;
141860 ** Register the fts3tok module with database connection db. Return SQLITE_OK
141861 ** if successful or an error code if sqlite3_create_module() fails.
141863 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
141864 static const sqlite3_module fts3tok_module = {
141865 0, /* iVersion */
141866 fts3tokConnectMethod, /* xCreate */
141867 fts3tokConnectMethod, /* xConnect */
141868 fts3tokBestIndexMethod, /* xBestIndex */
141869 fts3tokDisconnectMethod, /* xDisconnect */
141870 fts3tokDisconnectMethod, /* xDestroy */
141871 fts3tokOpenMethod, /* xOpen */
141872 fts3tokCloseMethod, /* xClose */
141873 fts3tokFilterMethod, /* xFilter */
141874 fts3tokNextMethod, /* xNext */
141875 fts3tokEofMethod, /* xEof */
141876 fts3tokColumnMethod, /* xColumn */
141877 fts3tokRowidMethod, /* xRowid */
141878 0, /* xUpdate */
141879 0, /* xBegin */
141880 0, /* xSync */
141881 0, /* xCommit */
141882 0, /* xRollback */
141883 0, /* xFindFunction */
141884 0, /* xRename */
141885 0, /* xSavepoint */
141886 0, /* xRelease */
141887 0 /* xRollbackTo */
141889 int rc; /* Return code */
141891 rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
141892 return rc;
141895 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
141897 /************** End of fts3_tokenize_vtab.c **********************************/
141898 /************** Begin file fts3_write.c **************************************/
141900 ** 2009 Oct 23
141902 ** The author disclaims copyright to this source code. In place of
141903 ** a legal notice, here is a blessing:
141905 ** May you do good and not evil.
141906 ** May you find forgiveness for yourself and forgive others.
141907 ** May you share freely, never taking more than you give.
141909 ******************************************************************************
141911 ** This file is part of the SQLite FTS3 extension module. Specifically,
141912 ** this file contains code to insert, update and delete rows from FTS3
141913 ** tables. It also contains code to merge FTS3 b-tree segments. Some
141914 ** of the sub-routines used to merge segments are also used by the query
141915 ** code in fts3.c.
141918 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
141920 /* #include <string.h> */
141921 /* #include <assert.h> */
141922 /* #include <stdlib.h> */
141925 #define FTS_MAX_APPENDABLE_HEIGHT 16
141928 ** When full-text index nodes are loaded from disk, the buffer that they
141929 ** are loaded into has the following number of bytes of padding at the end
141930 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
141931 ** of 920 bytes is allocated for it.
141933 ** This means that if we have a pointer into a buffer containing node data,
141934 ** it is always safe to read up to two varints from it without risking an
141935 ** overread, even if the node data is corrupted.
141937 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
141940 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
141941 ** memory incrementally instead of all at once. This can be a big performance
141942 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
141943 ** method before retrieving all query results (as may happen, for example,
141944 ** if a query has a LIMIT clause).
141946 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
141947 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
141948 ** The code is written so that the hard lower-limit for each of these values
141949 ** is 1. Clearly such small values would be inefficient, but can be useful
141950 ** for testing purposes.
141952 ** If this module is built with SQLITE_TEST defined, these constants may
141953 ** be overridden at runtime for testing purposes. File fts3_test.c contains
141954 ** a Tcl interface to read and write the values.
141956 #ifdef SQLITE_TEST
141957 int test_fts3_node_chunksize = (4*1024);
141958 int test_fts3_node_chunk_threshold = (4*1024)*4;
141959 # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
141960 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
141961 #else
141962 # define FTS3_NODE_CHUNKSIZE (4*1024)
141963 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
141964 #endif
141967 ** The two values that may be meaningfully bound to the :1 parameter in
141968 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
141970 #define FTS_STAT_DOCTOTAL 0
141971 #define FTS_STAT_INCRMERGEHINT 1
141972 #define FTS_STAT_AUTOINCRMERGE 2
141975 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
141976 ** and incremental merge operation that takes place. This is used for
141977 ** debugging FTS only, it should not usually be turned on in production
141978 ** systems.
141980 #ifdef FTS3_LOG_MERGES
141981 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
141982 sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
141984 #else
141985 #define fts3LogMerge(x, y)
141986 #endif
141989 typedef struct PendingList PendingList;
141990 typedef struct SegmentNode SegmentNode;
141991 typedef struct SegmentWriter SegmentWriter;
141994 ** An instance of the following data structure is used to build doclists
141995 ** incrementally. See function fts3PendingListAppend() for details.
141997 struct PendingList {
141998 int nData;
141999 char *aData;
142000 int nSpace;
142001 sqlite3_int64 iLastDocid;
142002 sqlite3_int64 iLastCol;
142003 sqlite3_int64 iLastPos;
142008 ** Each cursor has a (possibly empty) linked list of the following objects.
142010 struct Fts3DeferredToken {
142011 Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
142012 int iCol; /* Column token must occur in */
142013 Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
142014 PendingList *pList; /* Doclist is assembled here */
142018 ** An instance of this structure is used to iterate through the terms on
142019 ** a contiguous set of segment b-tree leaf nodes. Although the details of
142020 ** this structure are only manipulated by code in this file, opaque handles
142021 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
142022 ** terms when querying the full-text index. See functions:
142024 ** sqlite3Fts3SegReaderNew()
142025 ** sqlite3Fts3SegReaderFree()
142026 ** sqlite3Fts3SegReaderIterate()
142028 ** Methods used to manipulate Fts3SegReader structures:
142030 ** fts3SegReaderNext()
142031 ** fts3SegReaderFirstDocid()
142032 ** fts3SegReaderNextDocid()
142034 struct Fts3SegReader {
142035 int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
142036 u8 bLookup; /* True for a lookup only */
142037 u8 rootOnly; /* True for a root-only reader */
142039 sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
142040 sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
142041 sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
142042 sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
142044 char *aNode; /* Pointer to node data (or NULL) */
142045 int nNode; /* Size of buffer at aNode (or 0) */
142046 int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
142047 sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
142049 Fts3HashElem **ppNextElem;
142051 /* Variables set by fts3SegReaderNext(). These may be read directly
142052 ** by the caller. They are valid from the time SegmentReaderNew() returns
142053 ** until SegmentReaderNext() returns something other than SQLITE_OK
142054 ** (i.e. SQLITE_DONE).
142056 int nTerm; /* Number of bytes in current term */
142057 char *zTerm; /* Pointer to current term */
142058 int nTermAlloc; /* Allocated size of zTerm buffer */
142059 char *aDoclist; /* Pointer to doclist of current entry */
142060 int nDoclist; /* Size of doclist in current entry */
142062 /* The following variables are used by fts3SegReaderNextDocid() to iterate
142063 ** through the current doclist (aDoclist/nDoclist).
142065 char *pOffsetList;
142066 int nOffsetList; /* For descending pending seg-readers only */
142067 sqlite3_int64 iDocid;
142070 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
142071 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
142074 ** An instance of this structure is used to create a segment b-tree in the
142075 ** database. The internal details of this type are only accessed by the
142076 ** following functions:
142078 ** fts3SegWriterAdd()
142079 ** fts3SegWriterFlush()
142080 ** fts3SegWriterFree()
142082 struct SegmentWriter {
142083 SegmentNode *pTree; /* Pointer to interior tree structure */
142084 sqlite3_int64 iFirst; /* First slot in %_segments written */
142085 sqlite3_int64 iFree; /* Next free slot in %_segments */
142086 char *zTerm; /* Pointer to previous term buffer */
142087 int nTerm; /* Number of bytes in zTerm */
142088 int nMalloc; /* Size of malloc'd buffer at zMalloc */
142089 char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
142090 int nSize; /* Size of allocation at aData */
142091 int nData; /* Bytes of data in aData */
142092 char *aData; /* Pointer to block from malloc() */
142093 i64 nLeafData; /* Number of bytes of leaf data written */
142097 ** Type SegmentNode is used by the following three functions to create
142098 ** the interior part of the segment b+-tree structures (everything except
142099 ** the leaf nodes). These functions and type are only ever used by code
142100 ** within the fts3SegWriterXXX() family of functions described above.
142102 ** fts3NodeAddTerm()
142103 ** fts3NodeWrite()
142104 ** fts3NodeFree()
142106 ** When a b+tree is written to the database (either as a result of a merge
142107 ** or the pending-terms table being flushed), leaves are written into the
142108 ** database file as soon as they are completely populated. The interior of
142109 ** the tree is assembled in memory and written out only once all leaves have
142110 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
142111 ** very large, meaning that the interior of the tree consumes relatively
142112 ** little memory.
142114 struct SegmentNode {
142115 SegmentNode *pParent; /* Parent node (or NULL for root node) */
142116 SegmentNode *pRight; /* Pointer to right-sibling */
142117 SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
142118 int nEntry; /* Number of terms written to node so far */
142119 char *zTerm; /* Pointer to previous term buffer */
142120 int nTerm; /* Number of bytes in zTerm */
142121 int nMalloc; /* Size of malloc'd buffer at zMalloc */
142122 char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
142123 int nData; /* Bytes of valid data so far */
142124 char *aData; /* Node data */
142128 ** Valid values for the second argument to fts3SqlStmt().
142130 #define SQL_DELETE_CONTENT 0
142131 #define SQL_IS_EMPTY 1
142132 #define SQL_DELETE_ALL_CONTENT 2
142133 #define SQL_DELETE_ALL_SEGMENTS 3
142134 #define SQL_DELETE_ALL_SEGDIR 4
142135 #define SQL_DELETE_ALL_DOCSIZE 5
142136 #define SQL_DELETE_ALL_STAT 6
142137 #define SQL_SELECT_CONTENT_BY_ROWID 7
142138 #define SQL_NEXT_SEGMENT_INDEX 8
142139 #define SQL_INSERT_SEGMENTS 9
142140 #define SQL_NEXT_SEGMENTS_ID 10
142141 #define SQL_INSERT_SEGDIR 11
142142 #define SQL_SELECT_LEVEL 12
142143 #define SQL_SELECT_LEVEL_RANGE 13
142144 #define SQL_SELECT_LEVEL_COUNT 14
142145 #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
142146 #define SQL_DELETE_SEGDIR_LEVEL 16
142147 #define SQL_DELETE_SEGMENTS_RANGE 17
142148 #define SQL_CONTENT_INSERT 18
142149 #define SQL_DELETE_DOCSIZE 19
142150 #define SQL_REPLACE_DOCSIZE 20
142151 #define SQL_SELECT_DOCSIZE 21
142152 #define SQL_SELECT_STAT 22
142153 #define SQL_REPLACE_STAT 23
142155 #define SQL_SELECT_ALL_PREFIX_LEVEL 24
142156 #define SQL_DELETE_ALL_TERMS_SEGDIR 25
142157 #define SQL_DELETE_SEGDIR_RANGE 26
142158 #define SQL_SELECT_ALL_LANGID 27
142159 #define SQL_FIND_MERGE_LEVEL 28
142160 #define SQL_MAX_LEAF_NODE_ESTIMATE 29
142161 #define SQL_DELETE_SEGDIR_ENTRY 30
142162 #define SQL_SHIFT_SEGDIR_ENTRY 31
142163 #define SQL_SELECT_SEGDIR 32
142164 #define SQL_CHOMP_SEGDIR 33
142165 #define SQL_SEGMENT_IS_APPENDABLE 34
142166 #define SQL_SELECT_INDEXES 35
142167 #define SQL_SELECT_MXLEVEL 36
142169 #define SQL_SELECT_LEVEL_RANGE2 37
142170 #define SQL_UPDATE_LEVEL_IDX 38
142171 #define SQL_UPDATE_LEVEL 39
142174 ** This function is used to obtain an SQLite prepared statement handle
142175 ** for the statement identified by the second argument. If successful,
142176 ** *pp is set to the requested statement handle and SQLITE_OK returned.
142177 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
142179 ** If argument apVal is not NULL, then it must point to an array with
142180 ** at least as many entries as the requested statement has bound
142181 ** parameters. The values are bound to the statements parameters before
142182 ** returning.
142184 static int fts3SqlStmt(
142185 Fts3Table *p, /* Virtual table handle */
142186 int eStmt, /* One of the SQL_XXX constants above */
142187 sqlite3_stmt **pp, /* OUT: Statement handle */
142188 sqlite3_value **apVal /* Values to bind to statement */
142190 const char *azSql[] = {
142191 /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
142192 /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
142193 /* 2 */ "DELETE FROM %Q.'%q_content'",
142194 /* 3 */ "DELETE FROM %Q.'%q_segments'",
142195 /* 4 */ "DELETE FROM %Q.'%q_segdir'",
142196 /* 5 */ "DELETE FROM %Q.'%q_docsize'",
142197 /* 6 */ "DELETE FROM %Q.'%q_stat'",
142198 /* 7 */ "SELECT %s WHERE rowid=?",
142199 /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
142200 /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
142201 /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
142202 /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
142204 /* Return segments in order from oldest to newest.*/
142205 /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
142206 "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
142207 /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
142208 "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
142209 "ORDER BY level DESC, idx ASC",
142211 /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
142212 /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
142214 /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
142215 /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
142216 /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
142217 /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
142218 /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
142219 /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
142220 /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
142221 /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
142222 /* 24 */ "",
142223 /* 25 */ "",
142225 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
142226 /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
142228 /* This statement is used to determine which level to read the input from
142229 ** when performing an incremental merge. It returns the absolute level number
142230 ** of the oldest level in the db that contains at least ? segments. Or,
142231 ** if no level in the FTS index contains more than ? segments, the statement
142232 ** returns zero rows. */
142233 /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
142234 " ORDER BY (level %% 1024) ASC LIMIT 1",
142236 /* Estimate the upper limit on the number of leaf nodes in a new segment
142237 ** created by merging the oldest :2 segments from absolute level :1. See
142238 ** function sqlite3Fts3Incrmerge() for details. */
142239 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
142240 " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
142242 /* SQL_DELETE_SEGDIR_ENTRY
142243 ** Delete the %_segdir entry on absolute level :1 with index :2. */
142244 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
142246 /* SQL_SHIFT_SEGDIR_ENTRY
142247 ** Modify the idx value for the segment with idx=:3 on absolute level :2
142248 ** to :1. */
142249 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
142251 /* SQL_SELECT_SEGDIR
142252 ** Read a single entry from the %_segdir table. The entry from absolute
142253 ** level :1 with index value :2. */
142254 /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
142255 "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
142257 /* SQL_CHOMP_SEGDIR
142258 ** Update the start_block (:1) and root (:2) fields of the %_segdir
142259 ** entry located on absolute level :3 with index :4. */
142260 /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
142261 "WHERE level = ? AND idx = ?",
142263 /* SQL_SEGMENT_IS_APPENDABLE
142264 ** Return a single row if the segment with end_block=? is appendable. Or
142265 ** no rows otherwise. */
142266 /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
142268 /* SQL_SELECT_INDEXES
142269 ** Return the list of valid segment indexes for absolute level ? */
142270 /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
142272 /* SQL_SELECT_MXLEVEL
142273 ** Return the largest relative level in the FTS index or indexes. */
142274 /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
142276 /* Return segments in order from oldest to newest.*/
142277 /* 37 */ "SELECT level, idx, end_block "
142278 "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
142279 "ORDER BY level DESC, idx ASC",
142281 /* Update statements used while promoting segments */
142282 /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
142283 "WHERE level=? AND idx=?",
142284 /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
142287 int rc = SQLITE_OK;
142288 sqlite3_stmt *pStmt;
142290 assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
142291 assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
142293 pStmt = p->aStmt[eStmt];
142294 if( !pStmt ){
142295 char *zSql;
142296 if( eStmt==SQL_CONTENT_INSERT ){
142297 zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
142298 }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
142299 zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
142300 }else{
142301 zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
142303 if( !zSql ){
142304 rc = SQLITE_NOMEM;
142305 }else{
142306 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
142307 sqlite3_free(zSql);
142308 assert( rc==SQLITE_OK || pStmt==0 );
142309 p->aStmt[eStmt] = pStmt;
142312 if( apVal ){
142313 int i;
142314 int nParam = sqlite3_bind_parameter_count(pStmt);
142315 for(i=0; rc==SQLITE_OK && i<nParam; i++){
142316 rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
142319 *pp = pStmt;
142320 return rc;
142324 static int fts3SelectDocsize(
142325 Fts3Table *pTab, /* FTS3 table handle */
142326 sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
142327 sqlite3_stmt **ppStmt /* OUT: Statement handle */
142329 sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
142330 int rc; /* Return code */
142332 rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
142333 if( rc==SQLITE_OK ){
142334 sqlite3_bind_int64(pStmt, 1, iDocid);
142335 rc = sqlite3_step(pStmt);
142336 if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
142337 rc = sqlite3_reset(pStmt);
142338 if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
142339 pStmt = 0;
142340 }else{
142341 rc = SQLITE_OK;
142345 *ppStmt = pStmt;
142346 return rc;
142349 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
142350 Fts3Table *pTab, /* Fts3 table handle */
142351 sqlite3_stmt **ppStmt /* OUT: Statement handle */
142353 sqlite3_stmt *pStmt = 0;
142354 int rc;
142355 rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
142356 if( rc==SQLITE_OK ){
142357 sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
142358 if( sqlite3_step(pStmt)!=SQLITE_ROW
142359 || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
142361 rc = sqlite3_reset(pStmt);
142362 if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
142363 pStmt = 0;
142366 *ppStmt = pStmt;
142367 return rc;
142370 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
142371 Fts3Table *pTab, /* Fts3 table handle */
142372 sqlite3_int64 iDocid, /* Docid to read size data for */
142373 sqlite3_stmt **ppStmt /* OUT: Statement handle */
142375 return fts3SelectDocsize(pTab, iDocid, ppStmt);
142379 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
142380 ** array apVal[] to the SQL statement identified by eStmt, the statement
142381 ** is executed.
142383 ** Returns SQLITE_OK if the statement is successfully executed, or an
142384 ** SQLite error code otherwise.
142386 static void fts3SqlExec(
142387 int *pRC, /* Result code */
142388 Fts3Table *p, /* The FTS3 table */
142389 int eStmt, /* Index of statement to evaluate */
142390 sqlite3_value **apVal /* Parameters to bind */
142392 sqlite3_stmt *pStmt;
142393 int rc;
142394 if( *pRC ) return;
142395 rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
142396 if( rc==SQLITE_OK ){
142397 sqlite3_step(pStmt);
142398 rc = sqlite3_reset(pStmt);
142400 *pRC = rc;
142405 ** This function ensures that the caller has obtained an exclusive
142406 ** shared-cache table-lock on the %_segdir table. This is required before
142407 ** writing data to the fts3 table. If this lock is not acquired first, then
142408 ** the caller may end up attempting to take this lock as part of committing
142409 ** a transaction, causing SQLite to return SQLITE_LOCKED or
142410 ** LOCKED_SHAREDCACHEto a COMMIT command.
142412 ** It is best to avoid this because if FTS3 returns any error when
142413 ** committing a transaction, the whole transaction will be rolled back.
142414 ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
142415 ** It can still happen if the user locks the underlying tables directly
142416 ** instead of accessing them via FTS.
142418 static int fts3Writelock(Fts3Table *p){
142419 int rc = SQLITE_OK;
142421 if( p->nPendingData==0 ){
142422 sqlite3_stmt *pStmt;
142423 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
142424 if( rc==SQLITE_OK ){
142425 sqlite3_bind_null(pStmt, 1);
142426 sqlite3_step(pStmt);
142427 rc = sqlite3_reset(pStmt);
142431 return rc;
142435 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
142436 ** Within each language id, a separate index is maintained to store the
142437 ** document terms, and each configured prefix size (configured the FTS
142438 ** "prefix=" option). And each index consists of multiple levels ("relative
142439 ** levels").
142441 ** All three of these values (the language id, the specific index and the
142442 ** level within the index) are encoded in 64-bit integer values stored
142443 ** in the %_segdir table on disk. This function is used to convert three
142444 ** separate component values into the single 64-bit integer value that
142445 ** can be used to query the %_segdir table.
142447 ** Specifically, each language-id/index combination is allocated 1024
142448 ** 64-bit integer level values ("absolute levels"). The main terms index
142449 ** for language-id 0 is allocate values 0-1023. The first prefix index
142450 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
142451 ** Language 1 indexes are allocated immediately following language 0.
142453 ** So, for a system with nPrefix prefix indexes configured, the block of
142454 ** absolute levels that corresponds to language-id iLangid and index
142455 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
142457 static sqlite3_int64 getAbsoluteLevel(
142458 Fts3Table *p, /* FTS3 table handle */
142459 int iLangid, /* Language id */
142460 int iIndex, /* Index in p->aIndex[] */
142461 int iLevel /* Level of segments */
142463 sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
142464 assert( iLangid>=0 );
142465 assert( p->nIndex>0 );
142466 assert( iIndex>=0 && iIndex<p->nIndex );
142468 iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
142469 return iBase + iLevel;
142473 ** Set *ppStmt to a statement handle that may be used to iterate through
142474 ** all rows in the %_segdir table, from oldest to newest. If successful,
142475 ** return SQLITE_OK. If an error occurs while preparing the statement,
142476 ** return an SQLite error code.
142478 ** There is only ever one instance of this SQL statement compiled for
142479 ** each FTS3 table.
142481 ** The statement returns the following columns from the %_segdir table:
142483 ** 0: idx
142484 ** 1: start_block
142485 ** 2: leaves_end_block
142486 ** 3: end_block
142487 ** 4: root
142489 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
142490 Fts3Table *p, /* FTS3 table */
142491 int iLangid, /* Language being queried */
142492 int iIndex, /* Index for p->aIndex[] */
142493 int iLevel, /* Level to select (relative level) */
142494 sqlite3_stmt **ppStmt /* OUT: Compiled statement */
142496 int rc;
142497 sqlite3_stmt *pStmt = 0;
142499 assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
142500 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
142501 assert( iIndex>=0 && iIndex<p->nIndex );
142503 if( iLevel<0 ){
142504 /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
142505 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
142506 if( rc==SQLITE_OK ){
142507 sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
142508 sqlite3_bind_int64(pStmt, 2,
142509 getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
142512 }else{
142513 /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
142514 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
142515 if( rc==SQLITE_OK ){
142516 sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
142519 *ppStmt = pStmt;
142520 return rc;
142525 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
142526 ** if successful, or an SQLite error code otherwise.
142528 ** This function also serves to allocate the PendingList structure itself.
142529 ** For example, to create a new PendingList structure containing two
142530 ** varints:
142532 ** PendingList *p = 0;
142533 ** fts3PendingListAppendVarint(&p, 1);
142534 ** fts3PendingListAppendVarint(&p, 2);
142536 static int fts3PendingListAppendVarint(
142537 PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
142538 sqlite3_int64 i /* Value to append to data */
142540 PendingList *p = *pp;
142542 /* Allocate or grow the PendingList as required. */
142543 if( !p ){
142544 p = sqlite3_malloc(sizeof(*p) + 100);
142545 if( !p ){
142546 return SQLITE_NOMEM;
142548 p->nSpace = 100;
142549 p->aData = (char *)&p[1];
142550 p->nData = 0;
142552 else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
142553 int nNew = p->nSpace * 2;
142554 p = sqlite3_realloc(p, sizeof(*p) + nNew);
142555 if( !p ){
142556 sqlite3_free(*pp);
142557 *pp = 0;
142558 return SQLITE_NOMEM;
142560 p->nSpace = nNew;
142561 p->aData = (char *)&p[1];
142564 /* Append the new serialized varint to the end of the list. */
142565 p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
142566 p->aData[p->nData] = '\0';
142567 *pp = p;
142568 return SQLITE_OK;
142572 ** Add a docid/column/position entry to a PendingList structure. Non-zero
142573 ** is returned if the structure is sqlite3_realloced as part of adding
142574 ** the entry. Otherwise, zero.
142576 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
142577 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
142578 ** it is set to SQLITE_OK.
142580 static int fts3PendingListAppend(
142581 PendingList **pp, /* IN/OUT: PendingList structure */
142582 sqlite3_int64 iDocid, /* Docid for entry to add */
142583 sqlite3_int64 iCol, /* Column for entry to add */
142584 sqlite3_int64 iPos, /* Position of term for entry to add */
142585 int *pRc /* OUT: Return code */
142587 PendingList *p = *pp;
142588 int rc = SQLITE_OK;
142590 assert( !p || p->iLastDocid<=iDocid );
142592 if( !p || p->iLastDocid!=iDocid ){
142593 sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
142594 if( p ){
142595 assert( p->nData<p->nSpace );
142596 assert( p->aData[p->nData]==0 );
142597 p->nData++;
142599 if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
142600 goto pendinglistappend_out;
142602 p->iLastCol = -1;
142603 p->iLastPos = 0;
142604 p->iLastDocid = iDocid;
142606 if( iCol>0 && p->iLastCol!=iCol ){
142607 if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
142608 || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
142610 goto pendinglistappend_out;
142612 p->iLastCol = iCol;
142613 p->iLastPos = 0;
142615 if( iCol>=0 ){
142616 assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
142617 rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
142618 if( rc==SQLITE_OK ){
142619 p->iLastPos = iPos;
142623 pendinglistappend_out:
142624 *pRc = rc;
142625 if( p!=*pp ){
142626 *pp = p;
142627 return 1;
142629 return 0;
142633 ** Free a PendingList object allocated by fts3PendingListAppend().
142635 static void fts3PendingListDelete(PendingList *pList){
142636 sqlite3_free(pList);
142640 ** Add an entry to one of the pending-terms hash tables.
142642 static int fts3PendingTermsAddOne(
142643 Fts3Table *p,
142644 int iCol,
142645 int iPos,
142646 Fts3Hash *pHash, /* Pending terms hash table to add entry to */
142647 const char *zToken,
142648 int nToken
142650 PendingList *pList;
142651 int rc = SQLITE_OK;
142653 pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
142654 if( pList ){
142655 p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
142657 if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
142658 if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
142659 /* Malloc failed while inserting the new entry. This can only
142660 ** happen if there was no previous entry for this token.
142662 assert( 0==fts3HashFind(pHash, zToken, nToken) );
142663 sqlite3_free(pList);
142664 rc = SQLITE_NOMEM;
142667 if( rc==SQLITE_OK ){
142668 p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
142670 return rc;
142674 ** Tokenize the nul-terminated string zText and add all tokens to the
142675 ** pending-terms hash-table. The docid used is that currently stored in
142676 ** p->iPrevDocid, and the column is specified by argument iCol.
142678 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
142680 static int fts3PendingTermsAdd(
142681 Fts3Table *p, /* Table into which text will be inserted */
142682 int iLangid, /* Language id to use */
142683 const char *zText, /* Text of document to be inserted */
142684 int iCol, /* Column into which text is being inserted */
142685 u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
142687 int rc;
142688 int iStart = 0;
142689 int iEnd = 0;
142690 int iPos = 0;
142691 int nWord = 0;
142693 char const *zToken;
142694 int nToken = 0;
142696 sqlite3_tokenizer *pTokenizer = p->pTokenizer;
142697 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
142698 sqlite3_tokenizer_cursor *pCsr;
142699 int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
142700 const char**,int*,int*,int*,int*);
142702 assert( pTokenizer && pModule );
142704 /* If the user has inserted a NULL value, this function may be called with
142705 ** zText==0. In this case, add zero token entries to the hash table and
142706 ** return early. */
142707 if( zText==0 ){
142708 *pnWord = 0;
142709 return SQLITE_OK;
142712 rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
142713 if( rc!=SQLITE_OK ){
142714 return rc;
142717 xNext = pModule->xNext;
142718 while( SQLITE_OK==rc
142719 && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
142721 int i;
142722 if( iPos>=nWord ) nWord = iPos+1;
142724 /* Positions cannot be negative; we use -1 as a terminator internally.
142725 ** Tokens must have a non-zero length.
142727 if( iPos<0 || !zToken || nToken<=0 ){
142728 rc = SQLITE_ERROR;
142729 break;
142732 /* Add the term to the terms index */
142733 rc = fts3PendingTermsAddOne(
142734 p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
142737 /* Add the term to each of the prefix indexes that it is not too
142738 ** short for. */
142739 for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
142740 struct Fts3Index *pIndex = &p->aIndex[i];
142741 if( nToken<pIndex->nPrefix ) continue;
142742 rc = fts3PendingTermsAddOne(
142743 p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
142748 pModule->xClose(pCsr);
142749 *pnWord += nWord;
142750 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
142754 ** Calling this function indicates that subsequent calls to
142755 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
142756 ** contents of the document with docid iDocid.
142758 static int fts3PendingTermsDocid(
142759 Fts3Table *p, /* Full-text table handle */
142760 int iLangid, /* Language id of row being written */
142761 sqlite_int64 iDocid /* Docid of row being written */
142763 assert( iLangid>=0 );
142765 /* TODO(shess) Explore whether partially flushing the buffer on
142766 ** forced-flush would provide better performance. I suspect that if
142767 ** we ordered the doclists by size and flushed the largest until the
142768 ** buffer was half empty, that would let the less frequent terms
142769 ** generate longer doclists.
142771 if( iDocid<=p->iPrevDocid
142772 || p->iPrevLangid!=iLangid
142773 || p->nPendingData>p->nMaxPendingData
142775 int rc = sqlite3Fts3PendingTermsFlush(p);
142776 if( rc!=SQLITE_OK ) return rc;
142778 p->iPrevDocid = iDocid;
142779 p->iPrevLangid = iLangid;
142780 return SQLITE_OK;
142784 ** Discard the contents of the pending-terms hash tables.
142786 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
142787 int i;
142788 for(i=0; i<p->nIndex; i++){
142789 Fts3HashElem *pElem;
142790 Fts3Hash *pHash = &p->aIndex[i].hPending;
142791 for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
142792 PendingList *pList = (PendingList *)fts3HashData(pElem);
142793 fts3PendingListDelete(pList);
142795 fts3HashClear(pHash);
142797 p->nPendingData = 0;
142801 ** This function is called by the xUpdate() method as part of an INSERT
142802 ** operation. It adds entries for each term in the new record to the
142803 ** pendingTerms hash table.
142805 ** Argument apVal is the same as the similarly named argument passed to
142806 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
142808 static int fts3InsertTerms(
142809 Fts3Table *p,
142810 int iLangid,
142811 sqlite3_value **apVal,
142812 u32 *aSz
142814 int i; /* Iterator variable */
142815 for(i=2; i<p->nColumn+2; i++){
142816 int iCol = i-2;
142817 if( p->abNotindexed[iCol]==0 ){
142818 const char *zText = (const char *)sqlite3_value_text(apVal[i]);
142819 int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
142820 if( rc!=SQLITE_OK ){
142821 return rc;
142823 aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
142826 return SQLITE_OK;
142830 ** This function is called by the xUpdate() method for an INSERT operation.
142831 ** The apVal parameter is passed a copy of the apVal argument passed by
142832 ** SQLite to the xUpdate() method. i.e:
142834 ** apVal[0] Not used for INSERT.
142835 ** apVal[1] rowid
142836 ** apVal[2] Left-most user-defined column
142837 ** ...
142838 ** apVal[p->nColumn+1] Right-most user-defined column
142839 ** apVal[p->nColumn+2] Hidden column with same name as table
142840 ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
142841 ** apVal[p->nColumn+4] Hidden languageid column
142843 static int fts3InsertData(
142844 Fts3Table *p, /* Full-text table */
142845 sqlite3_value **apVal, /* Array of values to insert */
142846 sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
142848 int rc; /* Return code */
142849 sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
142851 if( p->zContentTbl ){
142852 sqlite3_value *pRowid = apVal[p->nColumn+3];
142853 if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
142854 pRowid = apVal[1];
142856 if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
142857 return SQLITE_CONSTRAINT;
142859 *piDocid = sqlite3_value_int64(pRowid);
142860 return SQLITE_OK;
142863 /* Locate the statement handle used to insert data into the %_content
142864 ** table. The SQL for this statement is:
142866 ** INSERT INTO %_content VALUES(?, ?, ?, ...)
142868 ** The statement features N '?' variables, where N is the number of user
142869 ** defined columns in the FTS3 table, plus one for the docid field.
142871 rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
142872 if( rc==SQLITE_OK && p->zLanguageid ){
142873 rc = sqlite3_bind_int(
142874 pContentInsert, p->nColumn+2,
142875 sqlite3_value_int(apVal[p->nColumn+4])
142878 if( rc!=SQLITE_OK ) return rc;
142880 /* There is a quirk here. The users INSERT statement may have specified
142881 ** a value for the "rowid" field, for the "docid" field, or for both.
142882 ** Which is a problem, since "rowid" and "docid" are aliases for the
142883 ** same value. For example:
142885 ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
142887 ** In FTS3, this is an error. It is an error to specify non-NULL values
142888 ** for both docid and some other rowid alias.
142890 if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
142891 if( SQLITE_NULL==sqlite3_value_type(apVal[0])
142892 && SQLITE_NULL!=sqlite3_value_type(apVal[1])
142894 /* A rowid/docid conflict. */
142895 return SQLITE_ERROR;
142897 rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
142898 if( rc!=SQLITE_OK ) return rc;
142901 /* Execute the statement to insert the record. Set *piDocid to the
142902 ** new docid value.
142904 sqlite3_step(pContentInsert);
142905 rc = sqlite3_reset(pContentInsert);
142907 *piDocid = sqlite3_last_insert_rowid(p->db);
142908 return rc;
142914 ** Remove all data from the FTS3 table. Clear the hash table containing
142915 ** pending terms.
142917 static int fts3DeleteAll(Fts3Table *p, int bContent){
142918 int rc = SQLITE_OK; /* Return code */
142920 /* Discard the contents of the pending-terms hash table. */
142921 sqlite3Fts3PendingTermsClear(p);
142923 /* Delete everything from the shadow tables. Except, leave %_content as
142924 ** is if bContent is false. */
142925 assert( p->zContentTbl==0 || bContent==0 );
142926 if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
142927 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
142928 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
142929 if( p->bHasDocsize ){
142930 fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
142932 if( p->bHasStat ){
142933 fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
142935 return rc;
142941 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
142942 int iLangid = 0;
142943 if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
142944 return iLangid;
142948 ** The first element in the apVal[] array is assumed to contain the docid
142949 ** (an integer) of a row about to be deleted. Remove all terms from the
142950 ** full-text index.
142952 static void fts3DeleteTerms(
142953 int *pRC, /* Result code */
142954 Fts3Table *p, /* The FTS table to delete from */
142955 sqlite3_value *pRowid, /* The docid to be deleted */
142956 u32 *aSz, /* Sizes of deleted document written here */
142957 int *pbFound /* OUT: Set to true if row really does exist */
142959 int rc;
142960 sqlite3_stmt *pSelect;
142962 assert( *pbFound==0 );
142963 if( *pRC ) return;
142964 rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
142965 if( rc==SQLITE_OK ){
142966 if( SQLITE_ROW==sqlite3_step(pSelect) ){
142967 int i;
142968 int iLangid = langidFromSelect(p, pSelect);
142969 rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
142970 for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
142971 int iCol = i-1;
142972 if( p->abNotindexed[iCol]==0 ){
142973 const char *zText = (const char *)sqlite3_column_text(pSelect, i);
142974 rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
142975 aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
142978 if( rc!=SQLITE_OK ){
142979 sqlite3_reset(pSelect);
142980 *pRC = rc;
142981 return;
142983 *pbFound = 1;
142985 rc = sqlite3_reset(pSelect);
142986 }else{
142987 sqlite3_reset(pSelect);
142989 *pRC = rc;
142993 ** Forward declaration to account for the circular dependency between
142994 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
142996 static int fts3SegmentMerge(Fts3Table *, int, int, int);
142999 ** This function allocates a new level iLevel index in the segdir table.
143000 ** Usually, indexes are allocated within a level sequentially starting
143001 ** with 0, so the allocated index is one greater than the value returned
143002 ** by:
143004 ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
143006 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
143007 ** level, they are merged into a single level (iLevel+1) segment and the
143008 ** allocated index is 0.
143010 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
143011 ** returned. Otherwise, an SQLite error code is returned.
143013 static int fts3AllocateSegdirIdx(
143014 Fts3Table *p,
143015 int iLangid, /* Language id */
143016 int iIndex, /* Index for p->aIndex */
143017 int iLevel,
143018 int *piIdx
143020 int rc; /* Return Code */
143021 sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
143022 int iNext = 0; /* Result of query pNextIdx */
143024 assert( iLangid>=0 );
143025 assert( p->nIndex>=1 );
143027 /* Set variable iNext to the next available segdir index at level iLevel. */
143028 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
143029 if( rc==SQLITE_OK ){
143030 sqlite3_bind_int64(
143031 pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
143033 if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
143034 iNext = sqlite3_column_int(pNextIdx, 0);
143036 rc = sqlite3_reset(pNextIdx);
143039 if( rc==SQLITE_OK ){
143040 /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
143041 ** full, merge all segments in level iLevel into a single iLevel+1
143042 ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
143043 ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
143045 if( iNext>=FTS3_MERGE_COUNT ){
143046 fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
143047 rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
143048 *piIdx = 0;
143049 }else{
143050 *piIdx = iNext;
143054 return rc;
143058 ** The %_segments table is declared as follows:
143060 ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
143062 ** This function reads data from a single row of the %_segments table. The
143063 ** specific row is identified by the iBlockid parameter. If paBlob is not
143064 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
143065 ** with the contents of the blob stored in the "block" column of the
143066 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
143067 ** to the size of the blob in bytes before returning.
143069 ** If an error occurs, or the table does not contain the specified row,
143070 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
143071 ** paBlob is non-NULL, then it is the responsibility of the caller to
143072 ** eventually free the returned buffer.
143074 ** This function may leave an open sqlite3_blob* handle in the
143075 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
143076 ** to this function. The handle may be closed by calling the
143077 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
143078 ** performance improvement, but the blob handle should always be closed
143079 ** before control is returned to the user (to prevent a lock being held
143080 ** on the database file for longer than necessary). Thus, any virtual table
143081 ** method (xFilter etc.) that may directly or indirectly call this function
143082 ** must call sqlite3Fts3SegmentsClose() before returning.
143084 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
143085 Fts3Table *p, /* FTS3 table handle */
143086 sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
143087 char **paBlob, /* OUT: Blob data in malloc'd buffer */
143088 int *pnBlob, /* OUT: Size of blob data */
143089 int *pnLoad /* OUT: Bytes actually loaded */
143091 int rc; /* Return code */
143093 /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
143094 assert( pnBlob );
143096 if( p->pSegments ){
143097 rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
143098 }else{
143099 if( 0==p->zSegmentsTbl ){
143100 p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
143101 if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
143103 rc = sqlite3_blob_open(
143104 p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
143108 if( rc==SQLITE_OK ){
143109 int nByte = sqlite3_blob_bytes(p->pSegments);
143110 *pnBlob = nByte;
143111 if( paBlob ){
143112 char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
143113 if( !aByte ){
143114 rc = SQLITE_NOMEM;
143115 }else{
143116 if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
143117 nByte = FTS3_NODE_CHUNKSIZE;
143118 *pnLoad = nByte;
143120 rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
143121 memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
143122 if( rc!=SQLITE_OK ){
143123 sqlite3_free(aByte);
143124 aByte = 0;
143127 *paBlob = aByte;
143131 return rc;
143135 ** Close the blob handle at p->pSegments, if it is open. See comments above
143136 ** the sqlite3Fts3ReadBlock() function for details.
143138 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
143139 sqlite3_blob_close(p->pSegments);
143140 p->pSegments = 0;
143143 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
143144 int nRead; /* Number of bytes to read */
143145 int rc; /* Return code */
143147 nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
143148 rc = sqlite3_blob_read(
143149 pReader->pBlob,
143150 &pReader->aNode[pReader->nPopulate],
143151 nRead,
143152 pReader->nPopulate
143155 if( rc==SQLITE_OK ){
143156 pReader->nPopulate += nRead;
143157 memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
143158 if( pReader->nPopulate==pReader->nNode ){
143159 sqlite3_blob_close(pReader->pBlob);
143160 pReader->pBlob = 0;
143161 pReader->nPopulate = 0;
143164 return rc;
143167 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
143168 int rc = SQLITE_OK;
143169 assert( !pReader->pBlob
143170 || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
143172 while( pReader->pBlob && rc==SQLITE_OK
143173 && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
143175 rc = fts3SegReaderIncrRead(pReader);
143177 return rc;
143181 ** Set an Fts3SegReader cursor to point at EOF.
143183 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
143184 if( !fts3SegReaderIsRootOnly(pSeg) ){
143185 sqlite3_free(pSeg->aNode);
143186 sqlite3_blob_close(pSeg->pBlob);
143187 pSeg->pBlob = 0;
143189 pSeg->aNode = 0;
143193 ** Move the iterator passed as the first argument to the next term in the
143194 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
143195 ** SQLITE_DONE. Otherwise, an SQLite error code.
143197 static int fts3SegReaderNext(
143198 Fts3Table *p,
143199 Fts3SegReader *pReader,
143200 int bIncr
143202 int rc; /* Return code of various sub-routines */
143203 char *pNext; /* Cursor variable */
143204 int nPrefix; /* Number of bytes in term prefix */
143205 int nSuffix; /* Number of bytes in term suffix */
143207 if( !pReader->aDoclist ){
143208 pNext = pReader->aNode;
143209 }else{
143210 pNext = &pReader->aDoclist[pReader->nDoclist];
143213 if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
143215 if( fts3SegReaderIsPending(pReader) ){
143216 Fts3HashElem *pElem = *(pReader->ppNextElem);
143217 if( pElem==0 ){
143218 pReader->aNode = 0;
143219 }else{
143220 PendingList *pList = (PendingList *)fts3HashData(pElem);
143221 pReader->zTerm = (char *)fts3HashKey(pElem);
143222 pReader->nTerm = fts3HashKeysize(pElem);
143223 pReader->nNode = pReader->nDoclist = pList->nData + 1;
143224 pReader->aNode = pReader->aDoclist = pList->aData;
143225 pReader->ppNextElem++;
143226 assert( pReader->aNode );
143228 return SQLITE_OK;
143231 fts3SegReaderSetEof(pReader);
143233 /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
143234 ** blocks have already been traversed. */
143235 assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
143236 if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
143237 return SQLITE_OK;
143240 rc = sqlite3Fts3ReadBlock(
143241 p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
143242 (bIncr ? &pReader->nPopulate : 0)
143244 if( rc!=SQLITE_OK ) return rc;
143245 assert( pReader->pBlob==0 );
143246 if( bIncr && pReader->nPopulate<pReader->nNode ){
143247 pReader->pBlob = p->pSegments;
143248 p->pSegments = 0;
143250 pNext = pReader->aNode;
143253 assert( !fts3SegReaderIsPending(pReader) );
143255 rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
143256 if( rc!=SQLITE_OK ) return rc;
143258 /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
143259 ** safe (no risk of overread) even if the node data is corrupted. */
143260 pNext += fts3GetVarint32(pNext, &nPrefix);
143261 pNext += fts3GetVarint32(pNext, &nSuffix);
143262 if( nPrefix<0 || nSuffix<=0
143263 || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
143265 return FTS_CORRUPT_VTAB;
143268 if( nPrefix+nSuffix>pReader->nTermAlloc ){
143269 int nNew = (nPrefix+nSuffix)*2;
143270 char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
143271 if( !zNew ){
143272 return SQLITE_NOMEM;
143274 pReader->zTerm = zNew;
143275 pReader->nTermAlloc = nNew;
143278 rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
143279 if( rc!=SQLITE_OK ) return rc;
143281 memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
143282 pReader->nTerm = nPrefix+nSuffix;
143283 pNext += nSuffix;
143284 pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
143285 pReader->aDoclist = pNext;
143286 pReader->pOffsetList = 0;
143288 /* Check that the doclist does not appear to extend past the end of the
143289 ** b-tree node. And that the final byte of the doclist is 0x00. If either
143290 ** of these statements is untrue, then the data structure is corrupt.
143292 if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
143293 || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
143295 return FTS_CORRUPT_VTAB;
143297 return SQLITE_OK;
143301 ** Set the SegReader to point to the first docid in the doclist associated
143302 ** with the current term.
143304 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
143305 int rc = SQLITE_OK;
143306 assert( pReader->aDoclist );
143307 assert( !pReader->pOffsetList );
143308 if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
143309 u8 bEof = 0;
143310 pReader->iDocid = 0;
143311 pReader->nOffsetList = 0;
143312 sqlite3Fts3DoclistPrev(0,
143313 pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
143314 &pReader->iDocid, &pReader->nOffsetList, &bEof
143316 }else{
143317 rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
143318 if( rc==SQLITE_OK ){
143319 int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
143320 pReader->pOffsetList = &pReader->aDoclist[n];
143323 return rc;
143327 ** Advance the SegReader to point to the next docid in the doclist
143328 ** associated with the current term.
143330 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
143331 ** *ppOffsetList is set to point to the first column-offset list
143332 ** in the doclist entry (i.e. immediately past the docid varint).
143333 ** *pnOffsetList is set to the length of the set of column-offset
143334 ** lists, not including the nul-terminator byte. For example:
143336 static int fts3SegReaderNextDocid(
143337 Fts3Table *pTab,
143338 Fts3SegReader *pReader, /* Reader to advance to next docid */
143339 char **ppOffsetList, /* OUT: Pointer to current position-list */
143340 int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
143342 int rc = SQLITE_OK;
143343 char *p = pReader->pOffsetList;
143344 char c = 0;
143346 assert( p );
143348 if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
143349 /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
143350 ** Pending-terms doclists are always built up in ascending order, so
143351 ** we have to iterate through them backwards here. */
143352 u8 bEof = 0;
143353 if( ppOffsetList ){
143354 *ppOffsetList = pReader->pOffsetList;
143355 *pnOffsetList = pReader->nOffsetList - 1;
143357 sqlite3Fts3DoclistPrev(0,
143358 pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
143359 &pReader->nOffsetList, &bEof
143361 if( bEof ){
143362 pReader->pOffsetList = 0;
143363 }else{
143364 pReader->pOffsetList = p;
143366 }else{
143367 char *pEnd = &pReader->aDoclist[pReader->nDoclist];
143369 /* Pointer p currently points at the first byte of an offset list. The
143370 ** following block advances it to point one byte past the end of
143371 ** the same offset list. */
143372 while( 1 ){
143374 /* The following line of code (and the "p++" below the while() loop) is
143375 ** normally all that is required to move pointer p to the desired
143376 ** position. The exception is if this node is being loaded from disk
143377 ** incrementally and pointer "p" now points to the first byte past
143378 ** the populated part of pReader->aNode[].
143380 while( *p | c ) c = *p++ & 0x80;
143381 assert( *p==0 );
143383 if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
143384 rc = fts3SegReaderIncrRead(pReader);
143385 if( rc!=SQLITE_OK ) return rc;
143389 /* If required, populate the output variables with a pointer to and the
143390 ** size of the previous offset-list.
143392 if( ppOffsetList ){
143393 *ppOffsetList = pReader->pOffsetList;
143394 *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
143397 /* List may have been edited in place by fts3EvalNearTrim() */
143398 while( p<pEnd && *p==0 ) p++;
143400 /* If there are no more entries in the doclist, set pOffsetList to
143401 ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
143402 ** Fts3SegReader.pOffsetList to point to the next offset list before
143403 ** returning.
143405 if( p>=pEnd ){
143406 pReader->pOffsetList = 0;
143407 }else{
143408 rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
143409 if( rc==SQLITE_OK ){
143410 sqlite3_int64 iDelta;
143411 pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
143412 if( pTab->bDescIdx ){
143413 pReader->iDocid -= iDelta;
143414 }else{
143415 pReader->iDocid += iDelta;
143421 return SQLITE_OK;
143425 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
143426 Fts3Cursor *pCsr,
143427 Fts3MultiSegReader *pMsr,
143428 int *pnOvfl
143430 Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
143431 int nOvfl = 0;
143432 int ii;
143433 int rc = SQLITE_OK;
143434 int pgsz = p->nPgsz;
143436 assert( p->bFts4 );
143437 assert( pgsz>0 );
143439 for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
143440 Fts3SegReader *pReader = pMsr->apSegment[ii];
143441 if( !fts3SegReaderIsPending(pReader)
143442 && !fts3SegReaderIsRootOnly(pReader)
143444 sqlite3_int64 jj;
143445 for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
143446 int nBlob;
143447 rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
143448 if( rc!=SQLITE_OK ) break;
143449 if( (nBlob+35)>pgsz ){
143450 nOvfl += (nBlob + 34)/pgsz;
143455 *pnOvfl = nOvfl;
143456 return rc;
143460 ** Free all allocations associated with the iterator passed as the
143461 ** second argument.
143463 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
143464 if( pReader && !fts3SegReaderIsPending(pReader) ){
143465 sqlite3_free(pReader->zTerm);
143466 if( !fts3SegReaderIsRootOnly(pReader) ){
143467 sqlite3_free(pReader->aNode);
143468 sqlite3_blob_close(pReader->pBlob);
143471 sqlite3_free(pReader);
143475 ** Allocate a new SegReader object.
143477 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
143478 int iAge, /* Segment "age". */
143479 int bLookup, /* True for a lookup only */
143480 sqlite3_int64 iStartLeaf, /* First leaf to traverse */
143481 sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
143482 sqlite3_int64 iEndBlock, /* Final block of segment */
143483 const char *zRoot, /* Buffer containing root node */
143484 int nRoot, /* Size of buffer containing root node */
143485 Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
143487 Fts3SegReader *pReader; /* Newly allocated SegReader object */
143488 int nExtra = 0; /* Bytes to allocate segment root node */
143490 assert( iStartLeaf<=iEndLeaf );
143491 if( iStartLeaf==0 ){
143492 nExtra = nRoot + FTS3_NODE_PADDING;
143495 pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
143496 if( !pReader ){
143497 return SQLITE_NOMEM;
143499 memset(pReader, 0, sizeof(Fts3SegReader));
143500 pReader->iIdx = iAge;
143501 pReader->bLookup = bLookup!=0;
143502 pReader->iStartBlock = iStartLeaf;
143503 pReader->iLeafEndBlock = iEndLeaf;
143504 pReader->iEndBlock = iEndBlock;
143506 if( nExtra ){
143507 /* The entire segment is stored in the root node. */
143508 pReader->aNode = (char *)&pReader[1];
143509 pReader->rootOnly = 1;
143510 pReader->nNode = nRoot;
143511 memcpy(pReader->aNode, zRoot, nRoot);
143512 memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
143513 }else{
143514 pReader->iCurrentBlock = iStartLeaf-1;
143516 *ppReader = pReader;
143517 return SQLITE_OK;
143521 ** This is a comparison function used as a qsort() callback when sorting
143522 ** an array of pending terms by term. This occurs as part of flushing
143523 ** the contents of the pending-terms hash table to the database.
143525 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
143526 char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
143527 char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
143528 int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
143529 int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
143531 int n = (n1<n2 ? n1 : n2);
143532 int c = memcmp(z1, z2, n);
143533 if( c==0 ){
143534 c = n1 - n2;
143536 return c;
143540 ** This function is used to allocate an Fts3SegReader that iterates through
143541 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
143543 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
143544 ** through each term in the pending-terms table. Or, if isPrefixIter is
143545 ** non-zero, it iterates through each term and its prefixes. For example, if
143546 ** the pending terms hash table contains the terms "sqlite", "mysql" and
143547 ** "firebird", then the iterator visits the following 'terms' (in the order
143548 ** shown):
143550 ** f fi fir fire fireb firebi firebir firebird
143551 ** m my mys mysq mysql
143552 ** s sq sql sqli sqlit sqlite
143554 ** Whereas if isPrefixIter is zero, the terms visited are:
143556 ** firebird mysql sqlite
143558 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
143559 Fts3Table *p, /* Virtual table handle */
143560 int iIndex, /* Index for p->aIndex */
143561 const char *zTerm, /* Term to search for */
143562 int nTerm, /* Size of buffer zTerm */
143563 int bPrefix, /* True for a prefix iterator */
143564 Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
143566 Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
143567 Fts3HashElem *pE; /* Iterator variable */
143568 Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
143569 int nElem = 0; /* Size of array at aElem */
143570 int rc = SQLITE_OK; /* Return Code */
143571 Fts3Hash *pHash;
143573 pHash = &p->aIndex[iIndex].hPending;
143574 if( bPrefix ){
143575 int nAlloc = 0; /* Size of allocated array at aElem */
143577 for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
143578 char *zKey = (char *)fts3HashKey(pE);
143579 int nKey = fts3HashKeysize(pE);
143580 if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
143581 if( nElem==nAlloc ){
143582 Fts3HashElem **aElem2;
143583 nAlloc += 16;
143584 aElem2 = (Fts3HashElem **)sqlite3_realloc(
143585 aElem, nAlloc*sizeof(Fts3HashElem *)
143587 if( !aElem2 ){
143588 rc = SQLITE_NOMEM;
143589 nElem = 0;
143590 break;
143592 aElem = aElem2;
143595 aElem[nElem++] = pE;
143599 /* If more than one term matches the prefix, sort the Fts3HashElem
143600 ** objects in term order using qsort(). This uses the same comparison
143601 ** callback as is used when flushing terms to disk.
143603 if( nElem>1 ){
143604 qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
143607 }else{
143608 /* The query is a simple term lookup that matches at most one term in
143609 ** the index. All that is required is a straight hash-lookup.
143611 ** Because the stack address of pE may be accessed via the aElem pointer
143612 ** below, the "Fts3HashElem *pE" must be declared so that it is valid
143613 ** within this entire function, not just this "else{...}" block.
143615 pE = fts3HashFindElem(pHash, zTerm, nTerm);
143616 if( pE ){
143617 aElem = &pE;
143618 nElem = 1;
143622 if( nElem>0 ){
143623 int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
143624 pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
143625 if( !pReader ){
143626 rc = SQLITE_NOMEM;
143627 }else{
143628 memset(pReader, 0, nByte);
143629 pReader->iIdx = 0x7FFFFFFF;
143630 pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
143631 memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
143635 if( bPrefix ){
143636 sqlite3_free(aElem);
143638 *ppReader = pReader;
143639 return rc;
143643 ** Compare the entries pointed to by two Fts3SegReader structures.
143644 ** Comparison is as follows:
143646 ** 1) EOF is greater than not EOF.
143648 ** 2) The current terms (if any) are compared using memcmp(). If one
143649 ** term is a prefix of another, the longer term is considered the
143650 ** larger.
143652 ** 3) By segment age. An older segment is considered larger.
143654 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
143655 int rc;
143656 if( pLhs->aNode && pRhs->aNode ){
143657 int rc2 = pLhs->nTerm - pRhs->nTerm;
143658 if( rc2<0 ){
143659 rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
143660 }else{
143661 rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
143663 if( rc==0 ){
143664 rc = rc2;
143666 }else{
143667 rc = (pLhs->aNode==0) - (pRhs->aNode==0);
143669 if( rc==0 ){
143670 rc = pRhs->iIdx - pLhs->iIdx;
143672 assert( rc!=0 );
143673 return rc;
143677 ** A different comparison function for SegReader structures. In this
143678 ** version, it is assumed that each SegReader points to an entry in
143679 ** a doclist for identical terms. Comparison is made as follows:
143681 ** 1) EOF (end of doclist in this case) is greater than not EOF.
143683 ** 2) By current docid.
143685 ** 3) By segment age. An older segment is considered larger.
143687 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
143688 int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
143689 if( rc==0 ){
143690 if( pLhs->iDocid==pRhs->iDocid ){
143691 rc = pRhs->iIdx - pLhs->iIdx;
143692 }else{
143693 rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
143696 assert( pLhs->aNode && pRhs->aNode );
143697 return rc;
143699 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
143700 int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
143701 if( rc==0 ){
143702 if( pLhs->iDocid==pRhs->iDocid ){
143703 rc = pRhs->iIdx - pLhs->iIdx;
143704 }else{
143705 rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
143708 assert( pLhs->aNode && pRhs->aNode );
143709 return rc;
143713 ** Compare the term that the Fts3SegReader object passed as the first argument
143714 ** points to with the term specified by arguments zTerm and nTerm.
143716 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
143717 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
143718 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
143720 static int fts3SegReaderTermCmp(
143721 Fts3SegReader *pSeg, /* Segment reader object */
143722 const char *zTerm, /* Term to compare to */
143723 int nTerm /* Size of term zTerm in bytes */
143725 int res = 0;
143726 if( pSeg->aNode ){
143727 if( pSeg->nTerm>nTerm ){
143728 res = memcmp(pSeg->zTerm, zTerm, nTerm);
143729 }else{
143730 res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
143732 if( res==0 ){
143733 res = pSeg->nTerm-nTerm;
143736 return res;
143740 ** Argument apSegment is an array of nSegment elements. It is known that
143741 ** the final (nSegment-nSuspect) members are already in sorted order
143742 ** (according to the comparison function provided). This function shuffles
143743 ** the array around until all entries are in sorted order.
143745 static void fts3SegReaderSort(
143746 Fts3SegReader **apSegment, /* Array to sort entries of */
143747 int nSegment, /* Size of apSegment array */
143748 int nSuspect, /* Unsorted entry count */
143749 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
143751 int i; /* Iterator variable */
143753 assert( nSuspect<=nSegment );
143755 if( nSuspect==nSegment ) nSuspect--;
143756 for(i=nSuspect-1; i>=0; i--){
143757 int j;
143758 for(j=i; j<(nSegment-1); j++){
143759 Fts3SegReader *pTmp;
143760 if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
143761 pTmp = apSegment[j+1];
143762 apSegment[j+1] = apSegment[j];
143763 apSegment[j] = pTmp;
143767 #ifndef NDEBUG
143768 /* Check that the list really is sorted now. */
143769 for(i=0; i<(nSuspect-1); i++){
143770 assert( xCmp(apSegment[i], apSegment[i+1])<0 );
143772 #endif
143776 ** Insert a record into the %_segments table.
143778 static int fts3WriteSegment(
143779 Fts3Table *p, /* Virtual table handle */
143780 sqlite3_int64 iBlock, /* Block id for new block */
143781 char *z, /* Pointer to buffer containing block data */
143782 int n /* Size of buffer z in bytes */
143784 sqlite3_stmt *pStmt;
143785 int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
143786 if( rc==SQLITE_OK ){
143787 sqlite3_bind_int64(pStmt, 1, iBlock);
143788 sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
143789 sqlite3_step(pStmt);
143790 rc = sqlite3_reset(pStmt);
143792 return rc;
143796 ** Find the largest relative level number in the table. If successful, set
143797 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
143798 ** set *pnMax to zero and return an SQLite error code.
143800 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
143801 int rc;
143802 int mxLevel = 0;
143803 sqlite3_stmt *pStmt = 0;
143805 rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
143806 if( rc==SQLITE_OK ){
143807 if( SQLITE_ROW==sqlite3_step(pStmt) ){
143808 mxLevel = sqlite3_column_int(pStmt, 0);
143810 rc = sqlite3_reset(pStmt);
143812 *pnMax = mxLevel;
143813 return rc;
143817 ** Insert a record into the %_segdir table.
143819 static int fts3WriteSegdir(
143820 Fts3Table *p, /* Virtual table handle */
143821 sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
143822 int iIdx, /* Value for "idx" field */
143823 sqlite3_int64 iStartBlock, /* Value for "start_block" field */
143824 sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
143825 sqlite3_int64 iEndBlock, /* Value for "end_block" field */
143826 sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
143827 char *zRoot, /* Blob value for "root" field */
143828 int nRoot /* Number of bytes in buffer zRoot */
143830 sqlite3_stmt *pStmt;
143831 int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
143832 if( rc==SQLITE_OK ){
143833 sqlite3_bind_int64(pStmt, 1, iLevel);
143834 sqlite3_bind_int(pStmt, 2, iIdx);
143835 sqlite3_bind_int64(pStmt, 3, iStartBlock);
143836 sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
143837 if( nLeafData==0 ){
143838 sqlite3_bind_int64(pStmt, 5, iEndBlock);
143839 }else{
143840 char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
143841 if( !zEnd ) return SQLITE_NOMEM;
143842 sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
143844 sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
143845 sqlite3_step(pStmt);
143846 rc = sqlite3_reset(pStmt);
143848 return rc;
143852 ** Return the size of the common prefix (if any) shared by zPrev and
143853 ** zNext, in bytes. For example,
143855 ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
143856 ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
143857 ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
143859 static int fts3PrefixCompress(
143860 const char *zPrev, /* Buffer containing previous term */
143861 int nPrev, /* Size of buffer zPrev in bytes */
143862 const char *zNext, /* Buffer containing next term */
143863 int nNext /* Size of buffer zNext in bytes */
143865 int n;
143866 UNUSED_PARAMETER(nNext);
143867 for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
143868 return n;
143872 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
143873 ** (according to memcmp) than the previous term.
143875 static int fts3NodeAddTerm(
143876 Fts3Table *p, /* Virtual table handle */
143877 SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
143878 int isCopyTerm, /* True if zTerm/nTerm is transient */
143879 const char *zTerm, /* Pointer to buffer containing term */
143880 int nTerm /* Size of term in bytes */
143882 SegmentNode *pTree = *ppTree;
143883 int rc;
143884 SegmentNode *pNew;
143886 /* First try to append the term to the current node. Return early if
143887 ** this is possible.
143889 if( pTree ){
143890 int nData = pTree->nData; /* Current size of node in bytes */
143891 int nReq = nData; /* Required space after adding zTerm */
143892 int nPrefix; /* Number of bytes of prefix compression */
143893 int nSuffix; /* Suffix length */
143895 nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
143896 nSuffix = nTerm-nPrefix;
143898 nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
143899 if( nReq<=p->nNodeSize || !pTree->zTerm ){
143901 if( nReq>p->nNodeSize ){
143902 /* An unusual case: this is the first term to be added to the node
143903 ** and the static node buffer (p->nNodeSize bytes) is not large
143904 ** enough. Use a separately malloced buffer instead This wastes
143905 ** p->nNodeSize bytes, but since this scenario only comes about when
143906 ** the database contain two terms that share a prefix of almost 2KB,
143907 ** this is not expected to be a serious problem.
143909 assert( pTree->aData==(char *)&pTree[1] );
143910 pTree->aData = (char *)sqlite3_malloc(nReq);
143911 if( !pTree->aData ){
143912 return SQLITE_NOMEM;
143916 if( pTree->zTerm ){
143917 /* There is no prefix-length field for first term in a node */
143918 nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
143921 nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
143922 memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
143923 pTree->nData = nData + nSuffix;
143924 pTree->nEntry++;
143926 if( isCopyTerm ){
143927 if( pTree->nMalloc<nTerm ){
143928 char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
143929 if( !zNew ){
143930 return SQLITE_NOMEM;
143932 pTree->nMalloc = nTerm*2;
143933 pTree->zMalloc = zNew;
143935 pTree->zTerm = pTree->zMalloc;
143936 memcpy(pTree->zTerm, zTerm, nTerm);
143937 pTree->nTerm = nTerm;
143938 }else{
143939 pTree->zTerm = (char *)zTerm;
143940 pTree->nTerm = nTerm;
143942 return SQLITE_OK;
143946 /* If control flows to here, it was not possible to append zTerm to the
143947 ** current node. Create a new node (a right-sibling of the current node).
143948 ** If this is the first node in the tree, the term is added to it.
143950 ** Otherwise, the term is not added to the new node, it is left empty for
143951 ** now. Instead, the term is inserted into the parent of pTree. If pTree
143952 ** has no parent, one is created here.
143954 pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
143955 if( !pNew ){
143956 return SQLITE_NOMEM;
143958 memset(pNew, 0, sizeof(SegmentNode));
143959 pNew->nData = 1 + FTS3_VARINT_MAX;
143960 pNew->aData = (char *)&pNew[1];
143962 if( pTree ){
143963 SegmentNode *pParent = pTree->pParent;
143964 rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
143965 if( pTree->pParent==0 ){
143966 pTree->pParent = pParent;
143968 pTree->pRight = pNew;
143969 pNew->pLeftmost = pTree->pLeftmost;
143970 pNew->pParent = pParent;
143971 pNew->zMalloc = pTree->zMalloc;
143972 pNew->nMalloc = pTree->nMalloc;
143973 pTree->zMalloc = 0;
143974 }else{
143975 pNew->pLeftmost = pNew;
143976 rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
143979 *ppTree = pNew;
143980 return rc;
143984 ** Helper function for fts3NodeWrite().
143986 static int fts3TreeFinishNode(
143987 SegmentNode *pTree,
143988 int iHeight,
143989 sqlite3_int64 iLeftChild
143991 int nStart;
143992 assert( iHeight>=1 && iHeight<128 );
143993 nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
143994 pTree->aData[nStart] = (char)iHeight;
143995 sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
143996 return nStart;
144000 ** Write the buffer for the segment node pTree and all of its peers to the
144001 ** database. Then call this function recursively to write the parent of
144002 ** pTree and its peers to the database.
144004 ** Except, if pTree is a root node, do not write it to the database. Instead,
144005 ** set output variables *paRoot and *pnRoot to contain the root node.
144007 ** If successful, SQLITE_OK is returned and output variable *piLast is
144008 ** set to the largest blockid written to the database (or zero if no
144009 ** blocks were written to the db). Otherwise, an SQLite error code is
144010 ** returned.
144012 static int fts3NodeWrite(
144013 Fts3Table *p, /* Virtual table handle */
144014 SegmentNode *pTree, /* SegmentNode handle */
144015 int iHeight, /* Height of this node in tree */
144016 sqlite3_int64 iLeaf, /* Block id of first leaf node */
144017 sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
144018 sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
144019 char **paRoot, /* OUT: Data for root node */
144020 int *pnRoot /* OUT: Size of root node in bytes */
144022 int rc = SQLITE_OK;
144024 if( !pTree->pParent ){
144025 /* Root node of the tree. */
144026 int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
144027 *piLast = iFree-1;
144028 *pnRoot = pTree->nData - nStart;
144029 *paRoot = &pTree->aData[nStart];
144030 }else{
144031 SegmentNode *pIter;
144032 sqlite3_int64 iNextFree = iFree;
144033 sqlite3_int64 iNextLeaf = iLeaf;
144034 for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
144035 int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
144036 int nWrite = pIter->nData - nStart;
144038 rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
144039 iNextFree++;
144040 iNextLeaf += (pIter->nEntry+1);
144042 if( rc==SQLITE_OK ){
144043 assert( iNextLeaf==iFree );
144044 rc = fts3NodeWrite(
144045 p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
144050 return rc;
144054 ** Free all memory allocations associated with the tree pTree.
144056 static void fts3NodeFree(SegmentNode *pTree){
144057 if( pTree ){
144058 SegmentNode *p = pTree->pLeftmost;
144059 fts3NodeFree(p->pParent);
144060 while( p ){
144061 SegmentNode *pRight = p->pRight;
144062 if( p->aData!=(char *)&p[1] ){
144063 sqlite3_free(p->aData);
144065 assert( pRight==0 || p->zMalloc==0 );
144066 sqlite3_free(p->zMalloc);
144067 sqlite3_free(p);
144068 p = pRight;
144074 ** Add a term to the segment being constructed by the SegmentWriter object
144075 ** *ppWriter. When adding the first term to a segment, *ppWriter should
144076 ** be passed NULL. This function will allocate a new SegmentWriter object
144077 ** and return it via the input/output variable *ppWriter in this case.
144079 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
144081 static int fts3SegWriterAdd(
144082 Fts3Table *p, /* Virtual table handle */
144083 SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
144084 int isCopyTerm, /* True if buffer zTerm must be copied */
144085 const char *zTerm, /* Pointer to buffer containing term */
144086 int nTerm, /* Size of term in bytes */
144087 const char *aDoclist, /* Pointer to buffer containing doclist */
144088 int nDoclist /* Size of doclist in bytes */
144090 int nPrefix; /* Size of term prefix in bytes */
144091 int nSuffix; /* Size of term suffix in bytes */
144092 int nReq; /* Number of bytes required on leaf page */
144093 int nData;
144094 SegmentWriter *pWriter = *ppWriter;
144096 if( !pWriter ){
144097 int rc;
144098 sqlite3_stmt *pStmt;
144100 /* Allocate the SegmentWriter structure */
144101 pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
144102 if( !pWriter ) return SQLITE_NOMEM;
144103 memset(pWriter, 0, sizeof(SegmentWriter));
144104 *ppWriter = pWriter;
144106 /* Allocate a buffer in which to accumulate data */
144107 pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
144108 if( !pWriter->aData ) return SQLITE_NOMEM;
144109 pWriter->nSize = p->nNodeSize;
144111 /* Find the next free blockid in the %_segments table */
144112 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
144113 if( rc!=SQLITE_OK ) return rc;
144114 if( SQLITE_ROW==sqlite3_step(pStmt) ){
144115 pWriter->iFree = sqlite3_column_int64(pStmt, 0);
144116 pWriter->iFirst = pWriter->iFree;
144118 rc = sqlite3_reset(pStmt);
144119 if( rc!=SQLITE_OK ) return rc;
144121 nData = pWriter->nData;
144123 nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
144124 nSuffix = nTerm-nPrefix;
144126 /* Figure out how many bytes are required by this new entry */
144127 nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
144128 sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
144129 nSuffix + /* Term suffix */
144130 sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
144131 nDoclist; /* Doclist data */
144133 if( nData>0 && nData+nReq>p->nNodeSize ){
144134 int rc;
144136 /* The current leaf node is full. Write it out to the database. */
144137 rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
144138 if( rc!=SQLITE_OK ) return rc;
144139 p->nLeafAdd++;
144141 /* Add the current term to the interior node tree. The term added to
144142 ** the interior tree must:
144144 ** a) be greater than the largest term on the leaf node just written
144145 ** to the database (still available in pWriter->zTerm), and
144147 ** b) be less than or equal to the term about to be added to the new
144148 ** leaf node (zTerm/nTerm).
144150 ** In other words, it must be the prefix of zTerm 1 byte longer than
144151 ** the common prefix (if any) of zTerm and pWriter->zTerm.
144153 assert( nPrefix<nTerm );
144154 rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
144155 if( rc!=SQLITE_OK ) return rc;
144157 nData = 0;
144158 pWriter->nTerm = 0;
144160 nPrefix = 0;
144161 nSuffix = nTerm;
144162 nReq = 1 + /* varint containing prefix size */
144163 sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
144164 nTerm + /* Term suffix */
144165 sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
144166 nDoclist; /* Doclist data */
144169 /* Increase the total number of bytes written to account for the new entry. */
144170 pWriter->nLeafData += nReq;
144172 /* If the buffer currently allocated is too small for this entry, realloc
144173 ** the buffer to make it large enough.
144175 if( nReq>pWriter->nSize ){
144176 char *aNew = sqlite3_realloc(pWriter->aData, nReq);
144177 if( !aNew ) return SQLITE_NOMEM;
144178 pWriter->aData = aNew;
144179 pWriter->nSize = nReq;
144181 assert( nData+nReq<=pWriter->nSize );
144183 /* Append the prefix-compressed term and doclist to the buffer. */
144184 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
144185 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
144186 memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
144187 nData += nSuffix;
144188 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
144189 memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
144190 pWriter->nData = nData + nDoclist;
144192 /* Save the current term so that it can be used to prefix-compress the next.
144193 ** If the isCopyTerm parameter is true, then the buffer pointed to by
144194 ** zTerm is transient, so take a copy of the term data. Otherwise, just
144195 ** store a copy of the pointer.
144197 if( isCopyTerm ){
144198 if( nTerm>pWriter->nMalloc ){
144199 char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
144200 if( !zNew ){
144201 return SQLITE_NOMEM;
144203 pWriter->nMalloc = nTerm*2;
144204 pWriter->zMalloc = zNew;
144205 pWriter->zTerm = zNew;
144207 assert( pWriter->zTerm==pWriter->zMalloc );
144208 memcpy(pWriter->zTerm, zTerm, nTerm);
144209 }else{
144210 pWriter->zTerm = (char *)zTerm;
144212 pWriter->nTerm = nTerm;
144214 return SQLITE_OK;
144218 ** Flush all data associated with the SegmentWriter object pWriter to the
144219 ** database. This function must be called after all terms have been added
144220 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
144221 ** returned. Otherwise, an SQLite error code.
144223 static int fts3SegWriterFlush(
144224 Fts3Table *p, /* Virtual table handle */
144225 SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
144226 sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
144227 int iIdx /* Value for 'idx' column of %_segdir */
144229 int rc; /* Return code */
144230 if( pWriter->pTree ){
144231 sqlite3_int64 iLast = 0; /* Largest block id written to database */
144232 sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
144233 char *zRoot = NULL; /* Pointer to buffer containing root node */
144234 int nRoot = 0; /* Size of buffer zRoot */
144236 iLastLeaf = pWriter->iFree;
144237 rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
144238 if( rc==SQLITE_OK ){
144239 rc = fts3NodeWrite(p, pWriter->pTree, 1,
144240 pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
144242 if( rc==SQLITE_OK ){
144243 rc = fts3WriteSegdir(p, iLevel, iIdx,
144244 pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
144246 }else{
144247 /* The entire tree fits on the root node. Write it to the segdir table. */
144248 rc = fts3WriteSegdir(p, iLevel, iIdx,
144249 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
144251 p->nLeafAdd++;
144252 return rc;
144256 ** Release all memory held by the SegmentWriter object passed as the
144257 ** first argument.
144259 static void fts3SegWriterFree(SegmentWriter *pWriter){
144260 if( pWriter ){
144261 sqlite3_free(pWriter->aData);
144262 sqlite3_free(pWriter->zMalloc);
144263 fts3NodeFree(pWriter->pTree);
144264 sqlite3_free(pWriter);
144269 ** The first value in the apVal[] array is assumed to contain an integer.
144270 ** This function tests if there exist any documents with docid values that
144271 ** are different from that integer. i.e. if deleting the document with docid
144272 ** pRowid would mean the FTS3 table were empty.
144274 ** If successful, *pisEmpty is set to true if the table is empty except for
144275 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
144276 ** error occurs, an SQLite error code is returned.
144278 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
144279 sqlite3_stmt *pStmt;
144280 int rc;
144281 if( p->zContentTbl ){
144282 /* If using the content=xxx option, assume the table is never empty */
144283 *pisEmpty = 0;
144284 rc = SQLITE_OK;
144285 }else{
144286 rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
144287 if( rc==SQLITE_OK ){
144288 if( SQLITE_ROW==sqlite3_step(pStmt) ){
144289 *pisEmpty = sqlite3_column_int(pStmt, 0);
144291 rc = sqlite3_reset(pStmt);
144294 return rc;
144298 ** Set *pnMax to the largest segment level in the database for the index
144299 ** iIndex.
144301 ** Segment levels are stored in the 'level' column of the %_segdir table.
144303 ** Return SQLITE_OK if successful, or an SQLite error code if not.
144305 static int fts3SegmentMaxLevel(
144306 Fts3Table *p,
144307 int iLangid,
144308 int iIndex,
144309 sqlite3_int64 *pnMax
144311 sqlite3_stmt *pStmt;
144312 int rc;
144313 assert( iIndex>=0 && iIndex<p->nIndex );
144315 /* Set pStmt to the compiled version of:
144317 ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
144319 ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
144321 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
144322 if( rc!=SQLITE_OK ) return rc;
144323 sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
144324 sqlite3_bind_int64(pStmt, 2,
144325 getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
144327 if( SQLITE_ROW==sqlite3_step(pStmt) ){
144328 *pnMax = sqlite3_column_int64(pStmt, 0);
144330 return sqlite3_reset(pStmt);
144334 ** iAbsLevel is an absolute level that may be assumed to exist within
144335 ** the database. This function checks if it is the largest level number
144336 ** within its index. Assuming no error occurs, *pbMax is set to 1 if
144337 ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
144338 ** is returned. If an error occurs, an error code is returned and the
144339 ** final value of *pbMax is undefined.
144341 static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
144343 /* Set pStmt to the compiled version of:
144345 ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
144347 ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
144349 sqlite3_stmt *pStmt;
144350 int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
144351 if( rc!=SQLITE_OK ) return rc;
144352 sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
144353 sqlite3_bind_int64(pStmt, 2,
144354 ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
144357 *pbMax = 0;
144358 if( SQLITE_ROW==sqlite3_step(pStmt) ){
144359 *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
144361 return sqlite3_reset(pStmt);
144365 ** Delete all entries in the %_segments table associated with the segment
144366 ** opened with seg-reader pSeg. This function does not affect the contents
144367 ** of the %_segdir table.
144369 static int fts3DeleteSegment(
144370 Fts3Table *p, /* FTS table handle */
144371 Fts3SegReader *pSeg /* Segment to delete */
144373 int rc = SQLITE_OK; /* Return code */
144374 if( pSeg->iStartBlock ){
144375 sqlite3_stmt *pDelete; /* SQL statement to delete rows */
144376 rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
144377 if( rc==SQLITE_OK ){
144378 sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
144379 sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
144380 sqlite3_step(pDelete);
144381 rc = sqlite3_reset(pDelete);
144384 return rc;
144388 ** This function is used after merging multiple segments into a single large
144389 ** segment to delete the old, now redundant, segment b-trees. Specifically,
144390 ** it:
144392 ** 1) Deletes all %_segments entries for the segments associated with
144393 ** each of the SegReader objects in the array passed as the third
144394 ** argument, and
144396 ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
144397 ** entries regardless of level if (iLevel<0).
144399 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
144401 static int fts3DeleteSegdir(
144402 Fts3Table *p, /* Virtual table handle */
144403 int iLangid, /* Language id */
144404 int iIndex, /* Index for p->aIndex */
144405 int iLevel, /* Level of %_segdir entries to delete */
144406 Fts3SegReader **apSegment, /* Array of SegReader objects */
144407 int nReader /* Size of array apSegment */
144409 int rc = SQLITE_OK; /* Return Code */
144410 int i; /* Iterator variable */
144411 sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
144413 for(i=0; rc==SQLITE_OK && i<nReader; i++){
144414 rc = fts3DeleteSegment(p, apSegment[i]);
144416 if( rc!=SQLITE_OK ){
144417 return rc;
144420 assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
144421 if( iLevel==FTS3_SEGCURSOR_ALL ){
144422 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
144423 if( rc==SQLITE_OK ){
144424 sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
144425 sqlite3_bind_int64(pDelete, 2,
144426 getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
144429 }else{
144430 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
144431 if( rc==SQLITE_OK ){
144432 sqlite3_bind_int64(
144433 pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
144438 if( rc==SQLITE_OK ){
144439 sqlite3_step(pDelete);
144440 rc = sqlite3_reset(pDelete);
144443 return rc;
144447 ** When this function is called, buffer *ppList (size *pnList bytes) contains
144448 ** a position list that may (or may not) feature multiple columns. This
144449 ** function adjusts the pointer *ppList and the length *pnList so that they
144450 ** identify the subset of the position list that corresponds to column iCol.
144452 ** If there are no entries in the input position list for column iCol, then
144453 ** *pnList is set to zero before returning.
144455 ** If parameter bZero is non-zero, then any part of the input list following
144456 ** the end of the output list is zeroed before returning.
144458 static void fts3ColumnFilter(
144459 int iCol, /* Column to filter on */
144460 int bZero, /* Zero out anything following *ppList */
144461 char **ppList, /* IN/OUT: Pointer to position list */
144462 int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
144464 char *pList = *ppList;
144465 int nList = *pnList;
144466 char *pEnd = &pList[nList];
144467 int iCurrent = 0;
144468 char *p = pList;
144470 assert( iCol>=0 );
144471 while( 1 ){
144472 char c = 0;
144473 while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
144475 if( iCol==iCurrent ){
144476 nList = (int)(p - pList);
144477 break;
144480 nList -= (int)(p - pList);
144481 pList = p;
144482 if( nList==0 ){
144483 break;
144485 p = &pList[1];
144486 p += fts3GetVarint32(p, &iCurrent);
144489 if( bZero && &pList[nList]!=pEnd ){
144490 memset(&pList[nList], 0, pEnd - &pList[nList]);
144492 *ppList = pList;
144493 *pnList = nList;
144497 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
144498 ** existing data). Grow the buffer if required.
144500 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
144501 ** trying to resize the buffer, return SQLITE_NOMEM.
144503 static int fts3MsrBufferData(
144504 Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
144505 char *pList,
144506 int nList
144508 if( nList>pMsr->nBuffer ){
144509 char *pNew;
144510 pMsr->nBuffer = nList*2;
144511 pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
144512 if( !pNew ) return SQLITE_NOMEM;
144513 pMsr->aBuffer = pNew;
144516 memcpy(pMsr->aBuffer, pList, nList);
144517 return SQLITE_OK;
144520 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
144521 Fts3Table *p, /* Virtual table handle */
144522 Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
144523 sqlite3_int64 *piDocid, /* OUT: Docid value */
144524 char **paPoslist, /* OUT: Pointer to position list */
144525 int *pnPoslist /* OUT: Size of position list in bytes */
144527 int nMerge = pMsr->nAdvance;
144528 Fts3SegReader **apSegment = pMsr->apSegment;
144529 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
144530 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
144533 if( nMerge==0 ){
144534 *paPoslist = 0;
144535 return SQLITE_OK;
144538 while( 1 ){
144539 Fts3SegReader *pSeg;
144540 pSeg = pMsr->apSegment[0];
144542 if( pSeg->pOffsetList==0 ){
144543 *paPoslist = 0;
144544 break;
144545 }else{
144546 int rc;
144547 char *pList;
144548 int nList;
144549 int j;
144550 sqlite3_int64 iDocid = apSegment[0]->iDocid;
144552 rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
144553 j = 1;
144554 while( rc==SQLITE_OK
144555 && j<nMerge
144556 && apSegment[j]->pOffsetList
144557 && apSegment[j]->iDocid==iDocid
144559 rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
144562 if( rc!=SQLITE_OK ) return rc;
144563 fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
144565 if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
144566 rc = fts3MsrBufferData(pMsr, pList, nList+1);
144567 if( rc!=SQLITE_OK ) return rc;
144568 assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
144569 pList = pMsr->aBuffer;
144572 if( pMsr->iColFilter>=0 ){
144573 fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
144576 if( nList>0 ){
144577 *paPoslist = pList;
144578 *piDocid = iDocid;
144579 *pnPoslist = nList;
144580 break;
144585 return SQLITE_OK;
144588 static int fts3SegReaderStart(
144589 Fts3Table *p, /* Virtual table handle */
144590 Fts3MultiSegReader *pCsr, /* Cursor object */
144591 const char *zTerm, /* Term searched for (or NULL) */
144592 int nTerm /* Length of zTerm in bytes */
144594 int i;
144595 int nSeg = pCsr->nSegment;
144597 /* If the Fts3SegFilter defines a specific term (or term prefix) to search
144598 ** for, then advance each segment iterator until it points to a term of
144599 ** equal or greater value than the specified term. This prevents many
144600 ** unnecessary merge/sort operations for the case where single segment
144601 ** b-tree leaf nodes contain more than one term.
144603 for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
144604 int res = 0;
144605 Fts3SegReader *pSeg = pCsr->apSegment[i];
144607 int rc = fts3SegReaderNext(p, pSeg, 0);
144608 if( rc!=SQLITE_OK ) return rc;
144609 }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
144611 if( pSeg->bLookup && res!=0 ){
144612 fts3SegReaderSetEof(pSeg);
144615 fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
144617 return SQLITE_OK;
144620 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
144621 Fts3Table *p, /* Virtual table handle */
144622 Fts3MultiSegReader *pCsr, /* Cursor object */
144623 Fts3SegFilter *pFilter /* Restrictions on range of iteration */
144625 pCsr->pFilter = pFilter;
144626 return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
144629 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
144630 Fts3Table *p, /* Virtual table handle */
144631 Fts3MultiSegReader *pCsr, /* Cursor object */
144632 int iCol, /* Column to match on. */
144633 const char *zTerm, /* Term to iterate through a doclist for */
144634 int nTerm /* Number of bytes in zTerm */
144636 int i;
144637 int rc;
144638 int nSegment = pCsr->nSegment;
144639 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
144640 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
144643 assert( pCsr->pFilter==0 );
144644 assert( zTerm && nTerm>0 );
144646 /* Advance each segment iterator until it points to the term zTerm/nTerm. */
144647 rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
144648 if( rc!=SQLITE_OK ) return rc;
144650 /* Determine how many of the segments actually point to zTerm/nTerm. */
144651 for(i=0; i<nSegment; i++){
144652 Fts3SegReader *pSeg = pCsr->apSegment[i];
144653 if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
144654 break;
144657 pCsr->nAdvance = i;
144659 /* Advance each of the segments to point to the first docid. */
144660 for(i=0; i<pCsr->nAdvance; i++){
144661 rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
144662 if( rc!=SQLITE_OK ) return rc;
144664 fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
144666 assert( iCol<0 || iCol<p->nColumn );
144667 pCsr->iColFilter = iCol;
144669 return SQLITE_OK;
144673 ** This function is called on a MultiSegReader that has been started using
144674 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
144675 ** have been made. Calling this function puts the MultiSegReader in such
144676 ** a state that if the next two calls are:
144678 ** sqlite3Fts3SegReaderStart()
144679 ** sqlite3Fts3SegReaderStep()
144681 ** then the entire doclist for the term is available in
144682 ** MultiSegReader.aDoclist/nDoclist.
144684 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
144685 int i; /* Used to iterate through segment-readers */
144687 assert( pCsr->zTerm==0 );
144688 assert( pCsr->nTerm==0 );
144689 assert( pCsr->aDoclist==0 );
144690 assert( pCsr->nDoclist==0 );
144692 pCsr->nAdvance = 0;
144693 pCsr->bRestart = 1;
144694 for(i=0; i<pCsr->nSegment; i++){
144695 pCsr->apSegment[i]->pOffsetList = 0;
144696 pCsr->apSegment[i]->nOffsetList = 0;
144697 pCsr->apSegment[i]->iDocid = 0;
144700 return SQLITE_OK;
144704 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
144705 Fts3Table *p, /* Virtual table handle */
144706 Fts3MultiSegReader *pCsr /* Cursor object */
144708 int rc = SQLITE_OK;
144710 int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
144711 int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
144712 int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
144713 int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
144714 int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
144715 int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
144717 Fts3SegReader **apSegment = pCsr->apSegment;
144718 int nSegment = pCsr->nSegment;
144719 Fts3SegFilter *pFilter = pCsr->pFilter;
144720 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
144721 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
144724 if( pCsr->nSegment==0 ) return SQLITE_OK;
144727 int nMerge;
144728 int i;
144730 /* Advance the first pCsr->nAdvance entries in the apSegment[] array
144731 ** forward. Then sort the list in order of current term again.
144733 for(i=0; i<pCsr->nAdvance; i++){
144734 Fts3SegReader *pSeg = apSegment[i];
144735 if( pSeg->bLookup ){
144736 fts3SegReaderSetEof(pSeg);
144737 }else{
144738 rc = fts3SegReaderNext(p, pSeg, 0);
144740 if( rc!=SQLITE_OK ) return rc;
144742 fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
144743 pCsr->nAdvance = 0;
144745 /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
144746 assert( rc==SQLITE_OK );
144747 if( apSegment[0]->aNode==0 ) break;
144749 pCsr->nTerm = apSegment[0]->nTerm;
144750 pCsr->zTerm = apSegment[0]->zTerm;
144752 /* If this is a prefix-search, and if the term that apSegment[0] points
144753 ** to does not share a suffix with pFilter->zTerm/nTerm, then all
144754 ** required callbacks have been made. In this case exit early.
144756 ** Similarly, if this is a search for an exact match, and the first term
144757 ** of segment apSegment[0] is not a match, exit early.
144759 if( pFilter->zTerm && !isScan ){
144760 if( pCsr->nTerm<pFilter->nTerm
144761 || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
144762 || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
144764 break;
144768 nMerge = 1;
144769 while( nMerge<nSegment
144770 && apSegment[nMerge]->aNode
144771 && apSegment[nMerge]->nTerm==pCsr->nTerm
144772 && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
144774 nMerge++;
144777 assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
144778 if( nMerge==1
144779 && !isIgnoreEmpty
144780 && !isFirst
144781 && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
144783 pCsr->nDoclist = apSegment[0]->nDoclist;
144784 if( fts3SegReaderIsPending(apSegment[0]) ){
144785 rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
144786 pCsr->aDoclist = pCsr->aBuffer;
144787 }else{
144788 pCsr->aDoclist = apSegment[0]->aDoclist;
144790 if( rc==SQLITE_OK ) rc = SQLITE_ROW;
144791 }else{
144792 int nDoclist = 0; /* Size of doclist */
144793 sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
144795 /* The current term of the first nMerge entries in the array
144796 ** of Fts3SegReader objects is the same. The doclists must be merged
144797 ** and a single term returned with the merged doclist.
144799 for(i=0; i<nMerge; i++){
144800 fts3SegReaderFirstDocid(p, apSegment[i]);
144802 fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
144803 while( apSegment[0]->pOffsetList ){
144804 int j; /* Number of segments that share a docid */
144805 char *pList = 0;
144806 int nList = 0;
144807 int nByte;
144808 sqlite3_int64 iDocid = apSegment[0]->iDocid;
144809 fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
144810 j = 1;
144811 while( j<nMerge
144812 && apSegment[j]->pOffsetList
144813 && apSegment[j]->iDocid==iDocid
144815 fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
144819 if( isColFilter ){
144820 fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
144823 if( !isIgnoreEmpty || nList>0 ){
144825 /* Calculate the 'docid' delta value to write into the merged
144826 ** doclist. */
144827 sqlite3_int64 iDelta;
144828 if( p->bDescIdx && nDoclist>0 ){
144829 iDelta = iPrev - iDocid;
144830 }else{
144831 iDelta = iDocid - iPrev;
144833 assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
144834 assert( nDoclist>0 || iDelta==iDocid );
144836 nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
144837 if( nDoclist+nByte>pCsr->nBuffer ){
144838 char *aNew;
144839 pCsr->nBuffer = (nDoclist+nByte)*2;
144840 aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
144841 if( !aNew ){
144842 return SQLITE_NOMEM;
144844 pCsr->aBuffer = aNew;
144847 if( isFirst ){
144848 char *a = &pCsr->aBuffer[nDoclist];
144849 int nWrite;
144851 nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
144852 if( nWrite ){
144853 iPrev = iDocid;
144854 nDoclist += nWrite;
144856 }else{
144857 nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
144858 iPrev = iDocid;
144859 if( isRequirePos ){
144860 memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
144861 nDoclist += nList;
144862 pCsr->aBuffer[nDoclist++] = '\0';
144867 fts3SegReaderSort(apSegment, nMerge, j, xCmp);
144869 if( nDoclist>0 ){
144870 pCsr->aDoclist = pCsr->aBuffer;
144871 pCsr->nDoclist = nDoclist;
144872 rc = SQLITE_ROW;
144875 pCsr->nAdvance = nMerge;
144876 }while( rc==SQLITE_OK );
144878 return rc;
144882 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
144883 Fts3MultiSegReader *pCsr /* Cursor object */
144885 if( pCsr ){
144886 int i;
144887 for(i=0; i<pCsr->nSegment; i++){
144888 sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
144890 sqlite3_free(pCsr->apSegment);
144891 sqlite3_free(pCsr->aBuffer);
144893 pCsr->nSegment = 0;
144894 pCsr->apSegment = 0;
144895 pCsr->aBuffer = 0;
144900 ** Decode the "end_block" field, selected by column iCol of the SELECT
144901 ** statement passed as the first argument.
144903 ** The "end_block" field may contain either an integer, or a text field
144904 ** containing the text representation of two non-negative integers separated
144905 ** by one or more space (0x20) characters. In the first case, set *piEndBlock
144906 ** to the integer value and *pnByte to zero before returning. In the second,
144907 ** set *piEndBlock to the first value and *pnByte to the second.
144909 static void fts3ReadEndBlockField(
144910 sqlite3_stmt *pStmt,
144911 int iCol,
144912 i64 *piEndBlock,
144913 i64 *pnByte
144915 const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
144916 if( zText ){
144917 int i;
144918 int iMul = 1;
144919 i64 iVal = 0;
144920 for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
144921 iVal = iVal*10 + (zText[i] - '0');
144923 *piEndBlock = iVal;
144924 while( zText[i]==' ' ) i++;
144925 iVal = 0;
144926 if( zText[i]=='-' ){
144928 iMul = -1;
144930 for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
144931 iVal = iVal*10 + (zText[i] - '0');
144933 *pnByte = (iVal * (i64)iMul);
144939 ** A segment of size nByte bytes has just been written to absolute level
144940 ** iAbsLevel. Promote any segments that should be promoted as a result.
144942 static int fts3PromoteSegments(
144943 Fts3Table *p, /* FTS table handle */
144944 sqlite3_int64 iAbsLevel, /* Absolute level just updated */
144945 sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
144947 int rc = SQLITE_OK;
144948 sqlite3_stmt *pRange;
144950 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
144952 if( rc==SQLITE_OK ){
144953 int bOk = 0;
144954 i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
144955 i64 nLimit = (nByte*3)/2;
144957 /* Loop through all entries in the %_segdir table corresponding to
144958 ** segments in this index on levels greater than iAbsLevel. If there is
144959 ** at least one such segment, and it is possible to determine that all
144960 ** such segments are smaller than nLimit bytes in size, they will be
144961 ** promoted to level iAbsLevel. */
144962 sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
144963 sqlite3_bind_int64(pRange, 2, iLast);
144964 while( SQLITE_ROW==sqlite3_step(pRange) ){
144965 i64 nSize = 0, dummy;
144966 fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
144967 if( nSize<=0 || nSize>nLimit ){
144968 /* If nSize==0, then the %_segdir.end_block field does not not
144969 ** contain a size value. This happens if it was written by an
144970 ** old version of FTS. In this case it is not possible to determine
144971 ** the size of the segment, and so segment promotion does not
144972 ** take place. */
144973 bOk = 0;
144974 break;
144976 bOk = 1;
144978 rc = sqlite3_reset(pRange);
144980 if( bOk ){
144981 int iIdx = 0;
144982 sqlite3_stmt *pUpdate1;
144983 sqlite3_stmt *pUpdate2;
144985 if( rc==SQLITE_OK ){
144986 rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
144988 if( rc==SQLITE_OK ){
144989 rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
144992 if( rc==SQLITE_OK ){
144994 /* Loop through all %_segdir entries for segments in this index with
144995 ** levels equal to or greater than iAbsLevel. As each entry is visited,
144996 ** updated it to set (level = -1) and (idx = N), where N is 0 for the
144997 ** oldest segment in the range, 1 for the next oldest, and so on.
144999 ** In other words, move all segments being promoted to level -1,
145000 ** setting the "idx" fields as appropriate to keep them in the same
145001 ** order. The contents of level -1 (which is never used, except
145002 ** transiently here), will be moved back to level iAbsLevel below. */
145003 sqlite3_bind_int64(pRange, 1, iAbsLevel);
145004 while( SQLITE_ROW==sqlite3_step(pRange) ){
145005 sqlite3_bind_int(pUpdate1, 1, iIdx++);
145006 sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
145007 sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
145008 sqlite3_step(pUpdate1);
145009 rc = sqlite3_reset(pUpdate1);
145010 if( rc!=SQLITE_OK ){
145011 sqlite3_reset(pRange);
145012 break;
145016 if( rc==SQLITE_OK ){
145017 rc = sqlite3_reset(pRange);
145020 /* Move level -1 to level iAbsLevel */
145021 if( rc==SQLITE_OK ){
145022 sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
145023 sqlite3_step(pUpdate2);
145024 rc = sqlite3_reset(pUpdate2);
145030 return rc;
145034 ** Merge all level iLevel segments in the database into a single
145035 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
145036 ** single segment with a level equal to the numerically largest level
145037 ** currently present in the database.
145039 ** If this function is called with iLevel<0, but there is only one
145040 ** segment in the database, SQLITE_DONE is returned immediately.
145041 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
145042 ** an SQLite error code is returned.
145044 static int fts3SegmentMerge(
145045 Fts3Table *p,
145046 int iLangid, /* Language id to merge */
145047 int iIndex, /* Index in p->aIndex[] to merge */
145048 int iLevel /* Level to merge */
145050 int rc; /* Return code */
145051 int iIdx = 0; /* Index of new segment */
145052 sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
145053 SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
145054 Fts3SegFilter filter; /* Segment term filter condition */
145055 Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
145056 int bIgnoreEmpty = 0; /* True to ignore empty segments */
145057 i64 iMaxLevel = 0; /* Max level number for this index/langid */
145059 assert( iLevel==FTS3_SEGCURSOR_ALL
145060 || iLevel==FTS3_SEGCURSOR_PENDING
145061 || iLevel>=0
145063 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
145064 assert( iIndex>=0 && iIndex<p->nIndex );
145066 rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
145067 if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
145069 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
145070 rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
145071 if( rc!=SQLITE_OK ) goto finished;
145074 if( iLevel==FTS3_SEGCURSOR_ALL ){
145075 /* This call is to merge all segments in the database to a single
145076 ** segment. The level of the new segment is equal to the numerically
145077 ** greatest segment level currently present in the database for this
145078 ** index. The idx of the new segment is always 0. */
145079 if( csr.nSegment==1 ){
145080 rc = SQLITE_DONE;
145081 goto finished;
145083 iNewLevel = iMaxLevel;
145084 bIgnoreEmpty = 1;
145086 }else{
145087 /* This call is to merge all segments at level iLevel. find the next
145088 ** available segment index at level iLevel+1. The call to
145089 ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
145090 ** a single iLevel+2 segment if necessary. */
145091 assert( FTS3_SEGCURSOR_PENDING==-1 );
145092 iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
145093 rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
145094 bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
145096 if( rc!=SQLITE_OK ) goto finished;
145098 assert( csr.nSegment>0 );
145099 assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
145100 assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
145102 memset(&filter, 0, sizeof(Fts3SegFilter));
145103 filter.flags = FTS3_SEGMENT_REQUIRE_POS;
145104 filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
145106 rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
145107 while( SQLITE_OK==rc ){
145108 rc = sqlite3Fts3SegReaderStep(p, &csr);
145109 if( rc!=SQLITE_ROW ) break;
145110 rc = fts3SegWriterAdd(p, &pWriter, 1,
145111 csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
145113 if( rc!=SQLITE_OK ) goto finished;
145114 assert( pWriter || bIgnoreEmpty );
145116 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
145117 rc = fts3DeleteSegdir(
145118 p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
145120 if( rc!=SQLITE_OK ) goto finished;
145122 if( pWriter ){
145123 rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
145124 if( rc==SQLITE_OK ){
145125 if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
145126 rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
145131 finished:
145132 fts3SegWriterFree(pWriter);
145133 sqlite3Fts3SegReaderFinish(&csr);
145134 return rc;
145139 ** Flush the contents of pendingTerms to level 0 segments.
145141 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
145142 int rc = SQLITE_OK;
145143 int i;
145145 for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
145146 rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
145147 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
145149 sqlite3Fts3PendingTermsClear(p);
145151 /* Determine the auto-incr-merge setting if unknown. If enabled,
145152 ** estimate the number of leaf blocks of content to be written
145154 if( rc==SQLITE_OK && p->bHasStat
145155 && p->nAutoincrmerge==0xff && p->nLeafAdd>0
145157 sqlite3_stmt *pStmt = 0;
145158 rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
145159 if( rc==SQLITE_OK ){
145160 sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
145161 rc = sqlite3_step(pStmt);
145162 if( rc==SQLITE_ROW ){
145163 p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
145164 if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
145165 }else if( rc==SQLITE_DONE ){
145166 p->nAutoincrmerge = 0;
145168 rc = sqlite3_reset(pStmt);
145171 return rc;
145175 ** Encode N integers as varints into a blob.
145177 static void fts3EncodeIntArray(
145178 int N, /* The number of integers to encode */
145179 u32 *a, /* The integer values */
145180 char *zBuf, /* Write the BLOB here */
145181 int *pNBuf /* Write number of bytes if zBuf[] used here */
145183 int i, j;
145184 for(i=j=0; i<N; i++){
145185 j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
145187 *pNBuf = j;
145191 ** Decode a blob of varints into N integers
145193 static void fts3DecodeIntArray(
145194 int N, /* The number of integers to decode */
145195 u32 *a, /* Write the integer values */
145196 const char *zBuf, /* The BLOB containing the varints */
145197 int nBuf /* size of the BLOB */
145199 int i, j;
145200 UNUSED_PARAMETER(nBuf);
145201 for(i=j=0; i<N; i++){
145202 sqlite3_int64 x;
145203 j += sqlite3Fts3GetVarint(&zBuf[j], &x);
145204 assert(j<=nBuf);
145205 a[i] = (u32)(x & 0xffffffff);
145210 ** Insert the sizes (in tokens) for each column of the document
145211 ** with docid equal to p->iPrevDocid. The sizes are encoded as
145212 ** a blob of varints.
145214 static void fts3InsertDocsize(
145215 int *pRC, /* Result code */
145216 Fts3Table *p, /* Table into which to insert */
145217 u32 *aSz /* Sizes of each column, in tokens */
145219 char *pBlob; /* The BLOB encoding of the document size */
145220 int nBlob; /* Number of bytes in the BLOB */
145221 sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
145222 int rc; /* Result code from subfunctions */
145224 if( *pRC ) return;
145225 pBlob = sqlite3_malloc( 10*p->nColumn );
145226 if( pBlob==0 ){
145227 *pRC = SQLITE_NOMEM;
145228 return;
145230 fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
145231 rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
145232 if( rc ){
145233 sqlite3_free(pBlob);
145234 *pRC = rc;
145235 return;
145237 sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
145238 sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
145239 sqlite3_step(pStmt);
145240 *pRC = sqlite3_reset(pStmt);
145244 ** Record 0 of the %_stat table contains a blob consisting of N varints,
145245 ** where N is the number of user defined columns in the fts3 table plus
145246 ** two. If nCol is the number of user defined columns, then values of the
145247 ** varints are set as follows:
145249 ** Varint 0: Total number of rows in the table.
145251 ** Varint 1..nCol: For each column, the total number of tokens stored in
145252 ** the column for all rows of the table.
145254 ** Varint 1+nCol: The total size, in bytes, of all text values in all
145255 ** columns of all rows of the table.
145258 static void fts3UpdateDocTotals(
145259 int *pRC, /* The result code */
145260 Fts3Table *p, /* Table being updated */
145261 u32 *aSzIns, /* Size increases */
145262 u32 *aSzDel, /* Size decreases */
145263 int nChng /* Change in the number of documents */
145265 char *pBlob; /* Storage for BLOB written into %_stat */
145266 int nBlob; /* Size of BLOB written into %_stat */
145267 u32 *a; /* Array of integers that becomes the BLOB */
145268 sqlite3_stmt *pStmt; /* Statement for reading and writing */
145269 int i; /* Loop counter */
145270 int rc; /* Result code from subfunctions */
145272 const int nStat = p->nColumn+2;
145274 if( *pRC ) return;
145275 a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
145276 if( a==0 ){
145277 *pRC = SQLITE_NOMEM;
145278 return;
145280 pBlob = (char*)&a[nStat];
145281 rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
145282 if( rc ){
145283 sqlite3_free(a);
145284 *pRC = rc;
145285 return;
145287 sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
145288 if( sqlite3_step(pStmt)==SQLITE_ROW ){
145289 fts3DecodeIntArray(nStat, a,
145290 sqlite3_column_blob(pStmt, 0),
145291 sqlite3_column_bytes(pStmt, 0));
145292 }else{
145293 memset(a, 0, sizeof(u32)*(nStat) );
145295 rc = sqlite3_reset(pStmt);
145296 if( rc!=SQLITE_OK ){
145297 sqlite3_free(a);
145298 *pRC = rc;
145299 return;
145301 if( nChng<0 && a[0]<(u32)(-nChng) ){
145302 a[0] = 0;
145303 }else{
145304 a[0] += nChng;
145306 for(i=0; i<p->nColumn+1; i++){
145307 u32 x = a[i+1];
145308 if( x+aSzIns[i] < aSzDel[i] ){
145309 x = 0;
145310 }else{
145311 x = x + aSzIns[i] - aSzDel[i];
145313 a[i+1] = x;
145315 fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
145316 rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
145317 if( rc ){
145318 sqlite3_free(a);
145319 *pRC = rc;
145320 return;
145322 sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
145323 sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
145324 sqlite3_step(pStmt);
145325 *pRC = sqlite3_reset(pStmt);
145326 sqlite3_free(a);
145330 ** Merge the entire database so that there is one segment for each
145331 ** iIndex/iLangid combination.
145333 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
145334 int bSeenDone = 0;
145335 int rc;
145336 sqlite3_stmt *pAllLangid = 0;
145338 rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
145339 if( rc==SQLITE_OK ){
145340 int rc2;
145341 sqlite3_bind_int(pAllLangid, 1, p->nIndex);
145342 while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
145343 int i;
145344 int iLangid = sqlite3_column_int(pAllLangid, 0);
145345 for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
145346 rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
145347 if( rc==SQLITE_DONE ){
145348 bSeenDone = 1;
145349 rc = SQLITE_OK;
145353 rc2 = sqlite3_reset(pAllLangid);
145354 if( rc==SQLITE_OK ) rc = rc2;
145357 sqlite3Fts3SegmentsClose(p);
145358 sqlite3Fts3PendingTermsClear(p);
145360 return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
145364 ** This function is called when the user executes the following statement:
145366 ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
145368 ** The entire FTS index is discarded and rebuilt. If the table is one
145369 ** created using the content=xxx option, then the new index is based on
145370 ** the current contents of the xxx table. Otherwise, it is rebuilt based
145371 ** on the contents of the %_content table.
145373 static int fts3DoRebuild(Fts3Table *p){
145374 int rc; /* Return Code */
145376 rc = fts3DeleteAll(p, 0);
145377 if( rc==SQLITE_OK ){
145378 u32 *aSz = 0;
145379 u32 *aSzIns = 0;
145380 u32 *aSzDel = 0;
145381 sqlite3_stmt *pStmt = 0;
145382 int nEntry = 0;
145384 /* Compose and prepare an SQL statement to loop through the content table */
145385 char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
145386 if( !zSql ){
145387 rc = SQLITE_NOMEM;
145388 }else{
145389 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
145390 sqlite3_free(zSql);
145393 if( rc==SQLITE_OK ){
145394 int nByte = sizeof(u32) * (p->nColumn+1)*3;
145395 aSz = (u32 *)sqlite3_malloc(nByte);
145396 if( aSz==0 ){
145397 rc = SQLITE_NOMEM;
145398 }else{
145399 memset(aSz, 0, nByte);
145400 aSzIns = &aSz[p->nColumn+1];
145401 aSzDel = &aSzIns[p->nColumn+1];
145405 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
145406 int iCol;
145407 int iLangid = langidFromSelect(p, pStmt);
145408 rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
145409 memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
145410 for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
145411 if( p->abNotindexed[iCol]==0 ){
145412 const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
145413 rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
145414 aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
145417 if( p->bHasDocsize ){
145418 fts3InsertDocsize(&rc, p, aSz);
145420 if( rc!=SQLITE_OK ){
145421 sqlite3_finalize(pStmt);
145422 pStmt = 0;
145423 }else{
145424 nEntry++;
145425 for(iCol=0; iCol<=p->nColumn; iCol++){
145426 aSzIns[iCol] += aSz[iCol];
145430 if( p->bFts4 ){
145431 fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
145433 sqlite3_free(aSz);
145435 if( pStmt ){
145436 int rc2 = sqlite3_finalize(pStmt);
145437 if( rc==SQLITE_OK ){
145438 rc = rc2;
145443 return rc;
145448 ** This function opens a cursor used to read the input data for an
145449 ** incremental merge operation. Specifically, it opens a cursor to scan
145450 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
145451 ** level iAbsLevel.
145453 static int fts3IncrmergeCsr(
145454 Fts3Table *p, /* FTS3 table handle */
145455 sqlite3_int64 iAbsLevel, /* Absolute level to open */
145456 int nSeg, /* Number of segments to merge */
145457 Fts3MultiSegReader *pCsr /* Cursor object to populate */
145459 int rc; /* Return Code */
145460 sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
145461 int nByte; /* Bytes allocated at pCsr->apSegment[] */
145463 /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
145464 memset(pCsr, 0, sizeof(*pCsr));
145465 nByte = sizeof(Fts3SegReader *) * nSeg;
145466 pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
145468 if( pCsr->apSegment==0 ){
145469 rc = SQLITE_NOMEM;
145470 }else{
145471 memset(pCsr->apSegment, 0, nByte);
145472 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
145474 if( rc==SQLITE_OK ){
145475 int i;
145476 int rc2;
145477 sqlite3_bind_int64(pStmt, 1, iAbsLevel);
145478 assert( pCsr->nSegment==0 );
145479 for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
145480 rc = sqlite3Fts3SegReaderNew(i, 0,
145481 sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
145482 sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
145483 sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
145484 sqlite3_column_blob(pStmt, 4), /* segdir.root */
145485 sqlite3_column_bytes(pStmt, 4), /* segdir.root */
145486 &pCsr->apSegment[i]
145488 pCsr->nSegment++;
145490 rc2 = sqlite3_reset(pStmt);
145491 if( rc==SQLITE_OK ) rc = rc2;
145494 return rc;
145497 typedef struct IncrmergeWriter IncrmergeWriter;
145498 typedef struct NodeWriter NodeWriter;
145499 typedef struct Blob Blob;
145500 typedef struct NodeReader NodeReader;
145503 ** An instance of the following structure is used as a dynamic buffer
145504 ** to build up nodes or other blobs of data in.
145506 ** The function blobGrowBuffer() is used to extend the allocation.
145508 struct Blob {
145509 char *a; /* Pointer to allocation */
145510 int n; /* Number of valid bytes of data in a[] */
145511 int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
145515 ** This structure is used to build up buffers containing segment b-tree
145516 ** nodes (blocks).
145518 struct NodeWriter {
145519 sqlite3_int64 iBlock; /* Current block id */
145520 Blob key; /* Last key written to the current block */
145521 Blob block; /* Current block image */
145525 ** An object of this type contains the state required to create or append
145526 ** to an appendable b-tree segment.
145528 struct IncrmergeWriter {
145529 int nLeafEst; /* Space allocated for leaf blocks */
145530 int nWork; /* Number of leaf pages flushed */
145531 sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
145532 int iIdx; /* Index of *output* segment in iAbsLevel+1 */
145533 sqlite3_int64 iStart; /* Block number of first allocated block */
145534 sqlite3_int64 iEnd; /* Block number of last allocated block */
145535 sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
145536 u8 bNoLeafData; /* If true, store 0 for segment size */
145537 NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
145541 ** An object of the following type is used to read data from a single
145542 ** FTS segment node. See the following functions:
145544 ** nodeReaderInit()
145545 ** nodeReaderNext()
145546 ** nodeReaderRelease()
145548 struct NodeReader {
145549 const char *aNode;
145550 int nNode;
145551 int iOff; /* Current offset within aNode[] */
145553 /* Output variables. Containing the current node entry. */
145554 sqlite3_int64 iChild; /* Pointer to child node */
145555 Blob term; /* Current term */
145556 const char *aDoclist; /* Pointer to doclist */
145557 int nDoclist; /* Size of doclist in bytes */
145561 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
145562 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
145563 ** bytes in size, extend (realloc) it to be so.
145565 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
145566 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
145567 ** to reflect the new size of the pBlob->a[] buffer.
145569 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
145570 if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
145571 int nAlloc = nMin;
145572 char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
145573 if( a ){
145574 pBlob->nAlloc = nAlloc;
145575 pBlob->a = a;
145576 }else{
145577 *pRc = SQLITE_NOMEM;
145583 ** Attempt to advance the node-reader object passed as the first argument to
145584 ** the next entry on the node.
145586 ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
145587 ** Otherwise return SQLITE_OK. If there is no next entry on the node
145588 ** (e.g. because the current entry is the last) set NodeReader->aNode to
145589 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
145590 ** variables for the new entry.
145592 static int nodeReaderNext(NodeReader *p){
145593 int bFirst = (p->term.n==0); /* True for first term on the node */
145594 int nPrefix = 0; /* Bytes to copy from previous term */
145595 int nSuffix = 0; /* Bytes to append to the prefix */
145596 int rc = SQLITE_OK; /* Return code */
145598 assert( p->aNode );
145599 if( p->iChild && bFirst==0 ) p->iChild++;
145600 if( p->iOff>=p->nNode ){
145601 /* EOF */
145602 p->aNode = 0;
145603 }else{
145604 if( bFirst==0 ){
145605 p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
145607 p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
145609 blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
145610 if( rc==SQLITE_OK ){
145611 memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
145612 p->term.n = nPrefix+nSuffix;
145613 p->iOff += nSuffix;
145614 if( p->iChild==0 ){
145615 p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
145616 p->aDoclist = &p->aNode[p->iOff];
145617 p->iOff += p->nDoclist;
145622 assert( p->iOff<=p->nNode );
145624 return rc;
145628 ** Release all dynamic resources held by node-reader object *p.
145630 static void nodeReaderRelease(NodeReader *p){
145631 sqlite3_free(p->term.a);
145635 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
145637 ** If successful, SQLITE_OK is returned and the NodeReader object set to
145638 ** point to the first entry on the node (if any). Otherwise, an SQLite
145639 ** error code is returned.
145641 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
145642 memset(p, 0, sizeof(NodeReader));
145643 p->aNode = aNode;
145644 p->nNode = nNode;
145646 /* Figure out if this is a leaf or an internal node. */
145647 if( p->aNode[0] ){
145648 /* An internal node. */
145649 p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
145650 }else{
145651 p->iOff = 1;
145654 return nodeReaderNext(p);
145658 ** This function is called while writing an FTS segment each time a leaf o
145659 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
145660 ** to be greater than the largest key on the node just written, but smaller
145661 ** than or equal to the first key that will be written to the next leaf
145662 ** node.
145664 ** The block id of the leaf node just written to disk may be found in
145665 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
145667 static int fts3IncrmergePush(
145668 Fts3Table *p, /* Fts3 table handle */
145669 IncrmergeWriter *pWriter, /* Writer object */
145670 const char *zTerm, /* Term to write to internal node */
145671 int nTerm /* Bytes at zTerm */
145673 sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
145674 int iLayer;
145676 assert( nTerm>0 );
145677 for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
145678 sqlite3_int64 iNextPtr = 0;
145679 NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
145680 int rc = SQLITE_OK;
145681 int nPrefix;
145682 int nSuffix;
145683 int nSpace;
145685 /* Figure out how much space the key will consume if it is written to
145686 ** the current node of layer iLayer. Due to the prefix compression,
145687 ** the space required changes depending on which node the key is to
145688 ** be added to. */
145689 nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
145690 nSuffix = nTerm - nPrefix;
145691 nSpace = sqlite3Fts3VarintLen(nPrefix);
145692 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
145694 if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
145695 /* If the current node of layer iLayer contains zero keys, or if adding
145696 ** the key to it will not cause it to grow to larger than nNodeSize
145697 ** bytes in size, write the key here. */
145699 Blob *pBlk = &pNode->block;
145700 if( pBlk->n==0 ){
145701 blobGrowBuffer(pBlk, p->nNodeSize, &rc);
145702 if( rc==SQLITE_OK ){
145703 pBlk->a[0] = (char)iLayer;
145704 pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
145707 blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
145708 blobGrowBuffer(&pNode->key, nTerm, &rc);
145710 if( rc==SQLITE_OK ){
145711 if( pNode->key.n ){
145712 pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
145714 pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
145715 memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
145716 pBlk->n += nSuffix;
145718 memcpy(pNode->key.a, zTerm, nTerm);
145719 pNode->key.n = nTerm;
145721 }else{
145722 /* Otherwise, flush the current node of layer iLayer to disk.
145723 ** Then allocate a new, empty sibling node. The key will be written
145724 ** into the parent of this node. */
145725 rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
145727 assert( pNode->block.nAlloc>=p->nNodeSize );
145728 pNode->block.a[0] = (char)iLayer;
145729 pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
145731 iNextPtr = pNode->iBlock;
145732 pNode->iBlock++;
145733 pNode->key.n = 0;
145736 if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
145737 iPtr = iNextPtr;
145740 assert( 0 );
145741 return 0;
145745 ** Append a term and (optionally) doclist to the FTS segment node currently
145746 ** stored in blob *pNode. The node need not contain any terms, but the
145747 ** header must be written before this function is called.
145749 ** A node header is a single 0x00 byte for a leaf node, or a height varint
145750 ** followed by the left-hand-child varint for an internal node.
145752 ** The term to be appended is passed via arguments zTerm/nTerm. For a
145753 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
145754 ** node, both aDoclist and nDoclist must be passed 0.
145756 ** If the size of the value in blob pPrev is zero, then this is the first
145757 ** term written to the node. Otherwise, pPrev contains a copy of the
145758 ** previous term. Before this function returns, it is updated to contain a
145759 ** copy of zTerm/nTerm.
145761 ** It is assumed that the buffer associated with pNode is already large
145762 ** enough to accommodate the new entry. The buffer associated with pPrev
145763 ** is extended by this function if requrired.
145765 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
145766 ** returned. Otherwise, SQLITE_OK.
145768 static int fts3AppendToNode(
145769 Blob *pNode, /* Current node image to append to */
145770 Blob *pPrev, /* Buffer containing previous term written */
145771 const char *zTerm, /* New term to write */
145772 int nTerm, /* Size of zTerm in bytes */
145773 const char *aDoclist, /* Doclist (or NULL) to write */
145774 int nDoclist /* Size of aDoclist in bytes */
145776 int rc = SQLITE_OK; /* Return code */
145777 int bFirst = (pPrev->n==0); /* True if this is the first term written */
145778 int nPrefix; /* Size of term prefix in bytes */
145779 int nSuffix; /* Size of term suffix in bytes */
145781 /* Node must have already been started. There must be a doclist for a
145782 ** leaf node, and there must not be a doclist for an internal node. */
145783 assert( pNode->n>0 );
145784 assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
145786 blobGrowBuffer(pPrev, nTerm, &rc);
145787 if( rc!=SQLITE_OK ) return rc;
145789 nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
145790 nSuffix = nTerm - nPrefix;
145791 memcpy(pPrev->a, zTerm, nTerm);
145792 pPrev->n = nTerm;
145794 if( bFirst==0 ){
145795 pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
145797 pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
145798 memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
145799 pNode->n += nSuffix;
145801 if( aDoclist ){
145802 pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
145803 memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
145804 pNode->n += nDoclist;
145807 assert( pNode->n<=pNode->nAlloc );
145809 return SQLITE_OK;
145813 ** Append the current term and doclist pointed to by cursor pCsr to the
145814 ** appendable b-tree segment opened for writing by pWriter.
145816 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
145818 static int fts3IncrmergeAppend(
145819 Fts3Table *p, /* Fts3 table handle */
145820 IncrmergeWriter *pWriter, /* Writer object */
145821 Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
145823 const char *zTerm = pCsr->zTerm;
145824 int nTerm = pCsr->nTerm;
145825 const char *aDoclist = pCsr->aDoclist;
145826 int nDoclist = pCsr->nDoclist;
145827 int rc = SQLITE_OK; /* Return code */
145828 int nSpace; /* Total space in bytes required on leaf */
145829 int nPrefix; /* Size of prefix shared with previous term */
145830 int nSuffix; /* Size of suffix (nTerm - nPrefix) */
145831 NodeWriter *pLeaf; /* Object used to write leaf nodes */
145833 pLeaf = &pWriter->aNodeWriter[0];
145834 nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
145835 nSuffix = nTerm - nPrefix;
145837 nSpace = sqlite3Fts3VarintLen(nPrefix);
145838 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
145839 nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
145841 /* If the current block is not empty, and if adding this term/doclist
145842 ** to the current block would make it larger than Fts3Table.nNodeSize
145843 ** bytes, write this block out to the database. */
145844 if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
145845 rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
145846 pWriter->nWork++;
145848 /* Add the current term to the parent node. The term added to the
145849 ** parent must:
145851 ** a) be greater than the largest term on the leaf node just written
145852 ** to the database (still available in pLeaf->key), and
145854 ** b) be less than or equal to the term about to be added to the new
145855 ** leaf node (zTerm/nTerm).
145857 ** In other words, it must be the prefix of zTerm 1 byte longer than
145858 ** the common prefix (if any) of zTerm and pWriter->zTerm.
145860 if( rc==SQLITE_OK ){
145861 rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
145864 /* Advance to the next output block */
145865 pLeaf->iBlock++;
145866 pLeaf->key.n = 0;
145867 pLeaf->block.n = 0;
145869 nSuffix = nTerm;
145870 nSpace = 1;
145871 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
145872 nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
145875 pWriter->nLeafData += nSpace;
145876 blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
145877 if( rc==SQLITE_OK ){
145878 if( pLeaf->block.n==0 ){
145879 pLeaf->block.n = 1;
145880 pLeaf->block.a[0] = '\0';
145882 rc = fts3AppendToNode(
145883 &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
145887 return rc;
145891 ** This function is called to release all dynamic resources held by the
145892 ** merge-writer object pWriter, and if no error has occurred, to flush
145893 ** all outstanding node buffers held by pWriter to disk.
145895 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
145896 ** is made to write any data to disk. Instead, this function serves only
145897 ** to release outstanding resources.
145899 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
145900 ** flushing buffers to disk, *pRc is set to an SQLite error code before
145901 ** returning.
145903 static void fts3IncrmergeRelease(
145904 Fts3Table *p, /* FTS3 table handle */
145905 IncrmergeWriter *pWriter, /* Merge-writer object */
145906 int *pRc /* IN/OUT: Error code */
145908 int i; /* Used to iterate through non-root layers */
145909 int iRoot; /* Index of root in pWriter->aNodeWriter */
145910 NodeWriter *pRoot; /* NodeWriter for root node */
145911 int rc = *pRc; /* Error code */
145913 /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
145914 ** root node. If the segment fits entirely on a single leaf node, iRoot
145915 ** will be set to 0. If the root node is the parent of the leaves, iRoot
145916 ** will be 1. And so on. */
145917 for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
145918 NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
145919 if( pNode->block.n>0 ) break;
145920 assert( *pRc || pNode->block.nAlloc==0 );
145921 assert( *pRc || pNode->key.nAlloc==0 );
145922 sqlite3_free(pNode->block.a);
145923 sqlite3_free(pNode->key.a);
145926 /* Empty output segment. This is a no-op. */
145927 if( iRoot<0 ) return;
145929 /* The entire output segment fits on a single node. Normally, this means
145930 ** the node would be stored as a blob in the "root" column of the %_segdir
145931 ** table. However, this is not permitted in this case. The problem is that
145932 ** space has already been reserved in the %_segments table, and so the
145933 ** start_block and end_block fields of the %_segdir table must be populated.
145934 ** And, by design or by accident, released versions of FTS cannot handle
145935 ** segments that fit entirely on the root node with start_block!=0.
145937 ** Instead, create a synthetic root node that contains nothing but a
145938 ** pointer to the single content node. So that the segment consists of a
145939 ** single leaf and a single interior (root) node.
145941 ** Todo: Better might be to defer allocating space in the %_segments
145942 ** table until we are sure it is needed.
145944 if( iRoot==0 ){
145945 Blob *pBlock = &pWriter->aNodeWriter[1].block;
145946 blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
145947 if( rc==SQLITE_OK ){
145948 pBlock->a[0] = 0x01;
145949 pBlock->n = 1 + sqlite3Fts3PutVarint(
145950 &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
145953 iRoot = 1;
145955 pRoot = &pWriter->aNodeWriter[iRoot];
145957 /* Flush all currently outstanding nodes to disk. */
145958 for(i=0; i<iRoot; i++){
145959 NodeWriter *pNode = &pWriter->aNodeWriter[i];
145960 if( pNode->block.n>0 && rc==SQLITE_OK ){
145961 rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
145963 sqlite3_free(pNode->block.a);
145964 sqlite3_free(pNode->key.a);
145967 /* Write the %_segdir record. */
145968 if( rc==SQLITE_OK ){
145969 rc = fts3WriteSegdir(p,
145970 pWriter->iAbsLevel+1, /* level */
145971 pWriter->iIdx, /* idx */
145972 pWriter->iStart, /* start_block */
145973 pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
145974 pWriter->iEnd, /* end_block */
145975 (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
145976 pRoot->block.a, pRoot->block.n /* root */
145979 sqlite3_free(pRoot->block.a);
145980 sqlite3_free(pRoot->key.a);
145982 *pRc = rc;
145986 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
145987 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
145988 ** the other, it is considered to be smaller than the other.
145990 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
145991 ** if it is greater.
145993 static int fts3TermCmp(
145994 const char *zLhs, int nLhs, /* LHS of comparison */
145995 const char *zRhs, int nRhs /* RHS of comparison */
145997 int nCmp = MIN(nLhs, nRhs);
145998 int res;
146000 res = memcmp(zLhs, zRhs, nCmp);
146001 if( res==0 ) res = nLhs - nRhs;
146003 return res;
146008 ** Query to see if the entry in the %_segments table with blockid iEnd is
146009 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
146010 ** returning. Otherwise, set *pbRes to 0.
146012 ** Or, if an error occurs while querying the database, return an SQLite
146013 ** error code. The final value of *pbRes is undefined in this case.
146015 ** This is used to test if a segment is an "appendable" segment. If it
146016 ** is, then a NULL entry has been inserted into the %_segments table
146017 ** with blockid %_segdir.end_block.
146019 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
146020 int bRes = 0; /* Result to set *pbRes to */
146021 sqlite3_stmt *pCheck = 0; /* Statement to query database with */
146022 int rc; /* Return code */
146024 rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
146025 if( rc==SQLITE_OK ){
146026 sqlite3_bind_int64(pCheck, 1, iEnd);
146027 if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
146028 rc = sqlite3_reset(pCheck);
146031 *pbRes = bRes;
146032 return rc;
146036 ** This function is called when initializing an incremental-merge operation.
146037 ** It checks if the existing segment with index value iIdx at absolute level
146038 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
146039 ** merge-writer object *pWriter is initialized to write to it.
146041 ** An existing segment can be appended to by an incremental merge if:
146043 ** * It was initially created as an appendable segment (with all required
146044 ** space pre-allocated), and
146046 ** * The first key read from the input (arguments zKey and nKey) is
146047 ** greater than the largest key currently stored in the potential
146048 ** output segment.
146050 static int fts3IncrmergeLoad(
146051 Fts3Table *p, /* Fts3 table handle */
146052 sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
146053 int iIdx, /* Index of candidate output segment */
146054 const char *zKey, /* First key to write */
146055 int nKey, /* Number of bytes in nKey */
146056 IncrmergeWriter *pWriter /* Populate this object */
146058 int rc; /* Return code */
146059 sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
146061 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
146062 if( rc==SQLITE_OK ){
146063 sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
146064 sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
146065 sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
146066 const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
146067 int nRoot = 0; /* Size of aRoot[] in bytes */
146068 int rc2; /* Return code from sqlite3_reset() */
146069 int bAppendable = 0; /* Set to true if segment is appendable */
146071 /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
146072 sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
146073 sqlite3_bind_int(pSelect, 2, iIdx);
146074 if( sqlite3_step(pSelect)==SQLITE_ROW ){
146075 iStart = sqlite3_column_int64(pSelect, 1);
146076 iLeafEnd = sqlite3_column_int64(pSelect, 2);
146077 fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
146078 if( pWriter->nLeafData<0 ){
146079 pWriter->nLeafData = pWriter->nLeafData * -1;
146081 pWriter->bNoLeafData = (pWriter->nLeafData==0);
146082 nRoot = sqlite3_column_bytes(pSelect, 4);
146083 aRoot = sqlite3_column_blob(pSelect, 4);
146084 }else{
146085 return sqlite3_reset(pSelect);
146088 /* Check for the zero-length marker in the %_segments table */
146089 rc = fts3IsAppendable(p, iEnd, &bAppendable);
146091 /* Check that zKey/nKey is larger than the largest key the candidate */
146092 if( rc==SQLITE_OK && bAppendable ){
146093 char *aLeaf = 0;
146094 int nLeaf = 0;
146096 rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
146097 if( rc==SQLITE_OK ){
146098 NodeReader reader;
146099 for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
146100 rc==SQLITE_OK && reader.aNode;
146101 rc = nodeReaderNext(&reader)
146103 assert( reader.aNode );
146105 if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
146106 bAppendable = 0;
146108 nodeReaderRelease(&reader);
146110 sqlite3_free(aLeaf);
146113 if( rc==SQLITE_OK && bAppendable ){
146114 /* It is possible to append to this segment. Set up the IncrmergeWriter
146115 ** object to do so. */
146116 int i;
146117 int nHeight = (int)aRoot[0];
146118 NodeWriter *pNode;
146120 pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
146121 pWriter->iStart = iStart;
146122 pWriter->iEnd = iEnd;
146123 pWriter->iAbsLevel = iAbsLevel;
146124 pWriter->iIdx = iIdx;
146126 for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
146127 pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
146130 pNode = &pWriter->aNodeWriter[nHeight];
146131 pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
146132 blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
146133 if( rc==SQLITE_OK ){
146134 memcpy(pNode->block.a, aRoot, nRoot);
146135 pNode->block.n = nRoot;
146138 for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
146139 NodeReader reader;
146140 pNode = &pWriter->aNodeWriter[i];
146142 rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
146143 while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
146144 blobGrowBuffer(&pNode->key, reader.term.n, &rc);
146145 if( rc==SQLITE_OK ){
146146 memcpy(pNode->key.a, reader.term.a, reader.term.n);
146147 pNode->key.n = reader.term.n;
146148 if( i>0 ){
146149 char *aBlock = 0;
146150 int nBlock = 0;
146151 pNode = &pWriter->aNodeWriter[i-1];
146152 pNode->iBlock = reader.iChild;
146153 rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
146154 blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
146155 if( rc==SQLITE_OK ){
146156 memcpy(pNode->block.a, aBlock, nBlock);
146157 pNode->block.n = nBlock;
146159 sqlite3_free(aBlock);
146162 nodeReaderRelease(&reader);
146166 rc2 = sqlite3_reset(pSelect);
146167 if( rc==SQLITE_OK ) rc = rc2;
146170 return rc;
146174 ** Determine the largest segment index value that exists within absolute
146175 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
146176 ** one before returning SQLITE_OK. Or, if there are no segments at all
146177 ** within level iAbsLevel, set *piIdx to zero.
146179 ** If an error occurs, return an SQLite error code. The final value of
146180 ** *piIdx is undefined in this case.
146182 static int fts3IncrmergeOutputIdx(
146183 Fts3Table *p, /* FTS Table handle */
146184 sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
146185 int *piIdx /* OUT: Next free index at iAbsLevel+1 */
146187 int rc;
146188 sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
146190 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
146191 if( rc==SQLITE_OK ){
146192 sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
146193 sqlite3_step(pOutputIdx);
146194 *piIdx = sqlite3_column_int(pOutputIdx, 0);
146195 rc = sqlite3_reset(pOutputIdx);
146198 return rc;
146202 ** Allocate an appendable output segment on absolute level iAbsLevel+1
146203 ** with idx value iIdx.
146205 ** In the %_segdir table, a segment is defined by the values in three
146206 ** columns:
146208 ** start_block
146209 ** leaves_end_block
146210 ** end_block
146212 ** When an appendable segment is allocated, it is estimated that the
146213 ** maximum number of leaf blocks that may be required is the sum of the
146214 ** number of leaf blocks consumed by the input segments, plus the number
146215 ** of input segments, multiplied by two. This value is stored in stack
146216 ** variable nLeafEst.
146218 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
146219 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
146220 ** array of leaf nodes starts at the first block allocated. The array
146221 ** of interior nodes that are parents of the leaf nodes start at block
146222 ** (start_block + (1 + end_block - start_block) / 16). And so on.
146224 ** In the actual code below, the value "16" is replaced with the
146225 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
146227 static int fts3IncrmergeWriter(
146228 Fts3Table *p, /* Fts3 table handle */
146229 sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
146230 int iIdx, /* Index of new output segment */
146231 Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
146232 IncrmergeWriter *pWriter /* Populate this object */
146234 int rc; /* Return Code */
146235 int i; /* Iterator variable */
146236 int nLeafEst = 0; /* Blocks allocated for leaf nodes */
146237 sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
146238 sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
146240 /* Calculate nLeafEst. */
146241 rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
146242 if( rc==SQLITE_OK ){
146243 sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
146244 sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
146245 if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
146246 nLeafEst = sqlite3_column_int(pLeafEst, 0);
146248 rc = sqlite3_reset(pLeafEst);
146250 if( rc!=SQLITE_OK ) return rc;
146252 /* Calculate the first block to use in the output segment */
146253 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
146254 if( rc==SQLITE_OK ){
146255 if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
146256 pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
146257 pWriter->iEnd = pWriter->iStart - 1;
146258 pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
146260 rc = sqlite3_reset(pFirstBlock);
146262 if( rc!=SQLITE_OK ) return rc;
146264 /* Insert the marker in the %_segments table to make sure nobody tries
146265 ** to steal the space just allocated. This is also used to identify
146266 ** appendable segments. */
146267 rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
146268 if( rc!=SQLITE_OK ) return rc;
146270 pWriter->iAbsLevel = iAbsLevel;
146271 pWriter->nLeafEst = nLeafEst;
146272 pWriter->iIdx = iIdx;
146274 /* Set up the array of NodeWriter objects */
146275 for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
146276 pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
146278 return SQLITE_OK;
146282 ** Remove an entry from the %_segdir table. This involves running the
146283 ** following two statements:
146285 ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
146286 ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
146288 ** The DELETE statement removes the specific %_segdir level. The UPDATE
146289 ** statement ensures that the remaining segments have contiguously allocated
146290 ** idx values.
146292 static int fts3RemoveSegdirEntry(
146293 Fts3Table *p, /* FTS3 table handle */
146294 sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
146295 int iIdx /* Index of %_segdir entry to delete */
146297 int rc; /* Return code */
146298 sqlite3_stmt *pDelete = 0; /* DELETE statement */
146300 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
146301 if( rc==SQLITE_OK ){
146302 sqlite3_bind_int64(pDelete, 1, iAbsLevel);
146303 sqlite3_bind_int(pDelete, 2, iIdx);
146304 sqlite3_step(pDelete);
146305 rc = sqlite3_reset(pDelete);
146308 return rc;
146312 ** One or more segments have just been removed from absolute level iAbsLevel.
146313 ** Update the 'idx' values of the remaining segments in the level so that
146314 ** the idx values are a contiguous sequence starting from 0.
146316 static int fts3RepackSegdirLevel(
146317 Fts3Table *p, /* FTS3 table handle */
146318 sqlite3_int64 iAbsLevel /* Absolute level to repack */
146320 int rc; /* Return code */
146321 int *aIdx = 0; /* Array of remaining idx values */
146322 int nIdx = 0; /* Valid entries in aIdx[] */
146323 int nAlloc = 0; /* Allocated size of aIdx[] */
146324 int i; /* Iterator variable */
146325 sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
146326 sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
146328 rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
146329 if( rc==SQLITE_OK ){
146330 int rc2;
146331 sqlite3_bind_int64(pSelect, 1, iAbsLevel);
146332 while( SQLITE_ROW==sqlite3_step(pSelect) ){
146333 if( nIdx>=nAlloc ){
146334 int *aNew;
146335 nAlloc += 16;
146336 aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
146337 if( !aNew ){
146338 rc = SQLITE_NOMEM;
146339 break;
146341 aIdx = aNew;
146343 aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
146345 rc2 = sqlite3_reset(pSelect);
146346 if( rc==SQLITE_OK ) rc = rc2;
146349 if( rc==SQLITE_OK ){
146350 rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
146352 if( rc==SQLITE_OK ){
146353 sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
146356 assert( p->bIgnoreSavepoint==0 );
146357 p->bIgnoreSavepoint = 1;
146358 for(i=0; rc==SQLITE_OK && i<nIdx; i++){
146359 if( aIdx[i]!=i ){
146360 sqlite3_bind_int(pUpdate, 3, aIdx[i]);
146361 sqlite3_bind_int(pUpdate, 1, i);
146362 sqlite3_step(pUpdate);
146363 rc = sqlite3_reset(pUpdate);
146366 p->bIgnoreSavepoint = 0;
146368 sqlite3_free(aIdx);
146369 return rc;
146372 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
146373 pNode->a[0] = (char)iHeight;
146374 if( iChild ){
146375 assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
146376 pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
146377 }else{
146378 assert( pNode->nAlloc>=1 );
146379 pNode->n = 1;
146384 ** The first two arguments are a pointer to and the size of a segment b-tree
146385 ** node. The node may be a leaf or an internal node.
146387 ** This function creates a new node image in blob object *pNew by copying
146388 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
146389 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
146391 static int fts3TruncateNode(
146392 const char *aNode, /* Current node image */
146393 int nNode, /* Size of aNode in bytes */
146394 Blob *pNew, /* OUT: Write new node image here */
146395 const char *zTerm, /* Omit all terms smaller than this */
146396 int nTerm, /* Size of zTerm in bytes */
146397 sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
146399 NodeReader reader; /* Reader object */
146400 Blob prev = {0, 0, 0}; /* Previous term written to new node */
146401 int rc = SQLITE_OK; /* Return code */
146402 int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
146404 /* Allocate required output space */
146405 blobGrowBuffer(pNew, nNode, &rc);
146406 if( rc!=SQLITE_OK ) return rc;
146407 pNew->n = 0;
146409 /* Populate new node buffer */
146410 for(rc = nodeReaderInit(&reader, aNode, nNode);
146411 rc==SQLITE_OK && reader.aNode;
146412 rc = nodeReaderNext(&reader)
146414 if( pNew->n==0 ){
146415 int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
146416 if( res<0 || (bLeaf==0 && res==0) ) continue;
146417 fts3StartNode(pNew, (int)aNode[0], reader.iChild);
146418 *piBlock = reader.iChild;
146420 rc = fts3AppendToNode(
146421 pNew, &prev, reader.term.a, reader.term.n,
146422 reader.aDoclist, reader.nDoclist
146424 if( rc!=SQLITE_OK ) break;
146426 if( pNew->n==0 ){
146427 fts3StartNode(pNew, (int)aNode[0], reader.iChild);
146428 *piBlock = reader.iChild;
146430 assert( pNew->n<=pNew->nAlloc );
146432 nodeReaderRelease(&reader);
146433 sqlite3_free(prev.a);
146434 return rc;
146438 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
146439 ** level iAbsLevel. This may involve deleting entries from the %_segments
146440 ** table, and modifying existing entries in both the %_segments and %_segdir
146441 ** tables.
146443 ** SQLITE_OK is returned if the segment is updated successfully. Or an
146444 ** SQLite error code otherwise.
146446 static int fts3TruncateSegment(
146447 Fts3Table *p, /* FTS3 table handle */
146448 sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
146449 int iIdx, /* Index within level of segment to modify */
146450 const char *zTerm, /* Remove terms smaller than this */
146451 int nTerm /* Number of bytes in buffer zTerm */
146453 int rc = SQLITE_OK; /* Return code */
146454 Blob root = {0,0,0}; /* New root page image */
146455 Blob block = {0,0,0}; /* Buffer used for any other block */
146456 sqlite3_int64 iBlock = 0; /* Block id */
146457 sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
146458 sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
146459 sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
146461 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
146462 if( rc==SQLITE_OK ){
146463 int rc2; /* sqlite3_reset() return code */
146464 sqlite3_bind_int64(pFetch, 1, iAbsLevel);
146465 sqlite3_bind_int(pFetch, 2, iIdx);
146466 if( SQLITE_ROW==sqlite3_step(pFetch) ){
146467 const char *aRoot = sqlite3_column_blob(pFetch, 4);
146468 int nRoot = sqlite3_column_bytes(pFetch, 4);
146469 iOldStart = sqlite3_column_int64(pFetch, 1);
146470 rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
146472 rc2 = sqlite3_reset(pFetch);
146473 if( rc==SQLITE_OK ) rc = rc2;
146476 while( rc==SQLITE_OK && iBlock ){
146477 char *aBlock = 0;
146478 int nBlock = 0;
146479 iNewStart = iBlock;
146481 rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
146482 if( rc==SQLITE_OK ){
146483 rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
146485 if( rc==SQLITE_OK ){
146486 rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
146488 sqlite3_free(aBlock);
146491 /* Variable iNewStart now contains the first valid leaf node. */
146492 if( rc==SQLITE_OK && iNewStart ){
146493 sqlite3_stmt *pDel = 0;
146494 rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
146495 if( rc==SQLITE_OK ){
146496 sqlite3_bind_int64(pDel, 1, iOldStart);
146497 sqlite3_bind_int64(pDel, 2, iNewStart-1);
146498 sqlite3_step(pDel);
146499 rc = sqlite3_reset(pDel);
146503 if( rc==SQLITE_OK ){
146504 sqlite3_stmt *pChomp = 0;
146505 rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
146506 if( rc==SQLITE_OK ){
146507 sqlite3_bind_int64(pChomp, 1, iNewStart);
146508 sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
146509 sqlite3_bind_int64(pChomp, 3, iAbsLevel);
146510 sqlite3_bind_int(pChomp, 4, iIdx);
146511 sqlite3_step(pChomp);
146512 rc = sqlite3_reset(pChomp);
146516 sqlite3_free(root.a);
146517 sqlite3_free(block.a);
146518 return rc;
146522 ** This function is called after an incrmental-merge operation has run to
146523 ** merge (or partially merge) two or more segments from absolute level
146524 ** iAbsLevel.
146526 ** Each input segment is either removed from the db completely (if all of
146527 ** its data was copied to the output segment by the incrmerge operation)
146528 ** or modified in place so that it no longer contains those entries that
146529 ** have been duplicated in the output segment.
146531 static int fts3IncrmergeChomp(
146532 Fts3Table *p, /* FTS table handle */
146533 sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
146534 Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
146535 int *pnRem /* Number of segments not deleted */
146537 int i;
146538 int nRem = 0;
146539 int rc = SQLITE_OK;
146541 for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
146542 Fts3SegReader *pSeg = 0;
146543 int j;
146545 /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
146546 ** somewhere in the pCsr->apSegment[] array. */
146547 for(j=0; ALWAYS(j<pCsr->nSegment); j++){
146548 pSeg = pCsr->apSegment[j];
146549 if( pSeg->iIdx==i ) break;
146551 assert( j<pCsr->nSegment && pSeg->iIdx==i );
146553 if( pSeg->aNode==0 ){
146554 /* Seg-reader is at EOF. Remove the entire input segment. */
146555 rc = fts3DeleteSegment(p, pSeg);
146556 if( rc==SQLITE_OK ){
146557 rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
146559 *pnRem = 0;
146560 }else{
146561 /* The incremental merge did not copy all the data from this
146562 ** segment to the upper level. The segment is modified in place
146563 ** so that it contains no keys smaller than zTerm/nTerm. */
146564 const char *zTerm = pSeg->zTerm;
146565 int nTerm = pSeg->nTerm;
146566 rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
146567 nRem++;
146571 if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
146572 rc = fts3RepackSegdirLevel(p, iAbsLevel);
146575 *pnRem = nRem;
146576 return rc;
146580 ** Store an incr-merge hint in the database.
146582 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
146583 sqlite3_stmt *pReplace = 0;
146584 int rc; /* Return code */
146586 rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
146587 if( rc==SQLITE_OK ){
146588 sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
146589 sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
146590 sqlite3_step(pReplace);
146591 rc = sqlite3_reset(pReplace);
146594 return rc;
146598 ** Load an incr-merge hint from the database. The incr-merge hint, if one
146599 ** exists, is stored in the rowid==1 row of the %_stat table.
146601 ** If successful, populate blob *pHint with the value read from the %_stat
146602 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
146603 ** SQLite error code.
146605 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
146606 sqlite3_stmt *pSelect = 0;
146607 int rc;
146609 pHint->n = 0;
146610 rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
146611 if( rc==SQLITE_OK ){
146612 int rc2;
146613 sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
146614 if( SQLITE_ROW==sqlite3_step(pSelect) ){
146615 const char *aHint = sqlite3_column_blob(pSelect, 0);
146616 int nHint = sqlite3_column_bytes(pSelect, 0);
146617 if( aHint ){
146618 blobGrowBuffer(pHint, nHint, &rc);
146619 if( rc==SQLITE_OK ){
146620 memcpy(pHint->a, aHint, nHint);
146621 pHint->n = nHint;
146625 rc2 = sqlite3_reset(pSelect);
146626 if( rc==SQLITE_OK ) rc = rc2;
146629 return rc;
146633 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
146634 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
146635 ** consists of two varints, the absolute level number of the input segments
146636 ** and the number of input segments.
146638 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
146639 ** set *pRc to an SQLite error code before returning.
146641 static void fts3IncrmergeHintPush(
146642 Blob *pHint, /* Hint blob to append to */
146643 i64 iAbsLevel, /* First varint to store in hint */
146644 int nInput, /* Second varint to store in hint */
146645 int *pRc /* IN/OUT: Error code */
146647 blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
146648 if( *pRc==SQLITE_OK ){
146649 pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
146650 pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
146655 ** Read the last entry (most recently pushed) from the hint blob *pHint
146656 ** and then remove the entry. Write the two values read to *piAbsLevel and
146657 ** *pnInput before returning.
146659 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
146660 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
146662 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
146663 const int nHint = pHint->n;
146664 int i;
146666 i = pHint->n-2;
146667 while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
146668 while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
146670 pHint->n = i;
146671 i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
146672 i += fts3GetVarint32(&pHint->a[i], pnInput);
146673 if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
146675 return SQLITE_OK;
146680 ** Attempt an incremental merge that writes nMerge leaf blocks.
146682 ** Incremental merges happen nMin segments at a time. The segments
146683 ** to be merged are the nMin oldest segments (the ones with the smallest
146684 ** values for the _segdir.idx field) in the highest level that contains
146685 ** at least nMin segments. Multiple merges might occur in an attempt to
146686 ** write the quota of nMerge leaf blocks.
146688 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
146689 int rc; /* Return code */
146690 int nRem = nMerge; /* Number of leaf pages yet to be written */
146691 Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
146692 Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
146693 IncrmergeWriter *pWriter; /* Writer object */
146694 int nSeg = 0; /* Number of input segments */
146695 sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
146696 Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
146697 int bDirtyHint = 0; /* True if blob 'hint' has been modified */
146699 /* Allocate space for the cursor, filter and writer objects */
146700 const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
146701 pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
146702 if( !pWriter ) return SQLITE_NOMEM;
146703 pFilter = (Fts3SegFilter *)&pWriter[1];
146704 pCsr = (Fts3MultiSegReader *)&pFilter[1];
146706 rc = fts3IncrmergeHintLoad(p, &hint);
146707 while( rc==SQLITE_OK && nRem>0 ){
146708 const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
146709 sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
146710 int bUseHint = 0; /* True if attempting to append */
146711 int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
146713 /* Search the %_segdir table for the absolute level with the smallest
146714 ** relative level number that contains at least nMin segments, if any.
146715 ** If one is found, set iAbsLevel to the absolute level number and
146716 ** nSeg to nMin. If no level with at least nMin segments can be found,
146717 ** set nSeg to -1.
146719 rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
146720 sqlite3_bind_int(pFindLevel, 1, nMin);
146721 if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
146722 iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
146723 nSeg = nMin;
146724 }else{
146725 nSeg = -1;
146727 rc = sqlite3_reset(pFindLevel);
146729 /* If the hint read from the %_stat table is not empty, check if the
146730 ** last entry in it specifies a relative level smaller than or equal
146731 ** to the level identified by the block above (if any). If so, this
146732 ** iteration of the loop will work on merging at the hinted level.
146734 if( rc==SQLITE_OK && hint.n ){
146735 int nHint = hint.n;
146736 sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
146737 int nHintSeg = 0; /* Hint number of segments */
146739 rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
146740 if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
146741 iAbsLevel = iHintAbsLevel;
146742 nSeg = nHintSeg;
146743 bUseHint = 1;
146744 bDirtyHint = 1;
146745 }else{
146746 /* This undoes the effect of the HintPop() above - so that no entry
146747 ** is removed from the hint blob. */
146748 hint.n = nHint;
146752 /* If nSeg is less that zero, then there is no level with at least
146753 ** nMin segments and no hint in the %_stat table. No work to do.
146754 ** Exit early in this case. */
146755 if( nSeg<0 ) break;
146757 /* Open a cursor to iterate through the contents of the oldest nSeg
146758 ** indexes of absolute level iAbsLevel. If this cursor is opened using
146759 ** the 'hint' parameters, it is possible that there are less than nSeg
146760 ** segments available in level iAbsLevel. In this case, no work is
146761 ** done on iAbsLevel - fall through to the next iteration of the loop
146762 ** to start work on some other level. */
146763 memset(pWriter, 0, nAlloc);
146764 pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
146766 if( rc==SQLITE_OK ){
146767 rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
146768 assert( bUseHint==1 || bUseHint==0 );
146769 if( iIdx==0 || (bUseHint && iIdx==1) ){
146770 int bIgnore = 0;
146771 rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
146772 if( bIgnore ){
146773 pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
146778 if( rc==SQLITE_OK ){
146779 rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
146781 if( SQLITE_OK==rc && pCsr->nSegment==nSeg
146782 && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
146783 && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
146785 if( bUseHint && iIdx>0 ){
146786 const char *zKey = pCsr->zTerm;
146787 int nKey = pCsr->nTerm;
146788 rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
146789 }else{
146790 rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
146793 if( rc==SQLITE_OK && pWriter->nLeafEst ){
146794 fts3LogMerge(nSeg, iAbsLevel);
146796 rc = fts3IncrmergeAppend(p, pWriter, pCsr);
146797 if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
146798 if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
146799 }while( rc==SQLITE_ROW );
146801 /* Update or delete the input segments */
146802 if( rc==SQLITE_OK ){
146803 nRem -= (1 + pWriter->nWork);
146804 rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
146805 if( nSeg!=0 ){
146806 bDirtyHint = 1;
146807 fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
146812 if( nSeg!=0 ){
146813 pWriter->nLeafData = pWriter->nLeafData * -1;
146815 fts3IncrmergeRelease(p, pWriter, &rc);
146816 if( nSeg==0 && pWriter->bNoLeafData==0 ){
146817 fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
146821 sqlite3Fts3SegReaderFinish(pCsr);
146824 /* Write the hint values into the %_stat table for the next incr-merger */
146825 if( bDirtyHint && rc==SQLITE_OK ){
146826 rc = fts3IncrmergeHintStore(p, &hint);
146829 sqlite3_free(pWriter);
146830 sqlite3_free(hint.a);
146831 return rc;
146835 ** Convert the text beginning at *pz into an integer and return
146836 ** its value. Advance *pz to point to the first character past
146837 ** the integer.
146839 static int fts3Getint(const char **pz){
146840 const char *z = *pz;
146841 int i = 0;
146842 while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
146843 *pz = z;
146844 return i;
146848 ** Process statements of the form:
146850 ** INSERT INTO table(table) VALUES('merge=A,B');
146852 ** A and B are integers that decode to be the number of leaf pages
146853 ** written for the merge, and the minimum number of segments on a level
146854 ** before it will be selected for a merge, respectively.
146856 static int fts3DoIncrmerge(
146857 Fts3Table *p, /* FTS3 table handle */
146858 const char *zParam /* Nul-terminated string containing "A,B" */
146860 int rc;
146861 int nMin = (FTS3_MERGE_COUNT / 2);
146862 int nMerge = 0;
146863 const char *z = zParam;
146865 /* Read the first integer value */
146866 nMerge = fts3Getint(&z);
146868 /* If the first integer value is followed by a ',', read the second
146869 ** integer value. */
146870 if( z[0]==',' && z[1]!='\0' ){
146872 nMin = fts3Getint(&z);
146875 if( z[0]!='\0' || nMin<2 ){
146876 rc = SQLITE_ERROR;
146877 }else{
146878 rc = SQLITE_OK;
146879 if( !p->bHasStat ){
146880 assert( p->bFts4==0 );
146881 sqlite3Fts3CreateStatTable(&rc, p);
146883 if( rc==SQLITE_OK ){
146884 rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
146886 sqlite3Fts3SegmentsClose(p);
146888 return rc;
146892 ** Process statements of the form:
146894 ** INSERT INTO table(table) VALUES('automerge=X');
146896 ** where X is an integer. X==0 means to turn automerge off. X!=0 means
146897 ** turn it on. The setting is persistent.
146899 static int fts3DoAutoincrmerge(
146900 Fts3Table *p, /* FTS3 table handle */
146901 const char *zParam /* Nul-terminated string containing boolean */
146903 int rc = SQLITE_OK;
146904 sqlite3_stmt *pStmt = 0;
146905 p->nAutoincrmerge = fts3Getint(&zParam);
146906 if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
146907 p->nAutoincrmerge = 8;
146909 if( !p->bHasStat ){
146910 assert( p->bFts4==0 );
146911 sqlite3Fts3CreateStatTable(&rc, p);
146912 if( rc ) return rc;
146914 rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
146915 if( rc ) return rc;
146916 sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
146917 sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
146918 sqlite3_step(pStmt);
146919 rc = sqlite3_reset(pStmt);
146920 return rc;
146924 ** Return a 64-bit checksum for the FTS index entry specified by the
146925 ** arguments to this function.
146927 static u64 fts3ChecksumEntry(
146928 const char *zTerm, /* Pointer to buffer containing term */
146929 int nTerm, /* Size of zTerm in bytes */
146930 int iLangid, /* Language id for current row */
146931 int iIndex, /* Index (0..Fts3Table.nIndex-1) */
146932 i64 iDocid, /* Docid for current row. */
146933 int iCol, /* Column number */
146934 int iPos /* Position */
146936 int i;
146937 u64 ret = (u64)iDocid;
146939 ret += (ret<<3) + iLangid;
146940 ret += (ret<<3) + iIndex;
146941 ret += (ret<<3) + iCol;
146942 ret += (ret<<3) + iPos;
146943 for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
146945 return ret;
146949 ** Return a checksum of all entries in the FTS index that correspond to
146950 ** language id iLangid. The checksum is calculated by XORing the checksums
146951 ** of each individual entry (see fts3ChecksumEntry()) together.
146953 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
146954 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
146955 ** return value is undefined in this case.
146957 static u64 fts3ChecksumIndex(
146958 Fts3Table *p, /* FTS3 table handle */
146959 int iLangid, /* Language id to return cksum for */
146960 int iIndex, /* Index to cksum (0..p->nIndex-1) */
146961 int *pRc /* OUT: Return code */
146963 Fts3SegFilter filter;
146964 Fts3MultiSegReader csr;
146965 int rc;
146966 u64 cksum = 0;
146968 assert( *pRc==SQLITE_OK );
146970 memset(&filter, 0, sizeof(filter));
146971 memset(&csr, 0, sizeof(csr));
146972 filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
146973 filter.flags |= FTS3_SEGMENT_SCAN;
146975 rc = sqlite3Fts3SegReaderCursor(
146976 p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
146978 if( rc==SQLITE_OK ){
146979 rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
146982 if( rc==SQLITE_OK ){
146983 while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
146984 char *pCsr = csr.aDoclist;
146985 char *pEnd = &pCsr[csr.nDoclist];
146987 i64 iDocid = 0;
146988 i64 iCol = 0;
146989 i64 iPos = 0;
146991 pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
146992 while( pCsr<pEnd ){
146993 i64 iVal = 0;
146994 pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
146995 if( pCsr<pEnd ){
146996 if( iVal==0 || iVal==1 ){
146997 iCol = 0;
146998 iPos = 0;
146999 if( iVal ){
147000 pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
147001 }else{
147002 pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
147003 iDocid += iVal;
147005 }else{
147006 iPos += (iVal - 2);
147007 cksum = cksum ^ fts3ChecksumEntry(
147008 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
147009 (int)iCol, (int)iPos
147016 sqlite3Fts3SegReaderFinish(&csr);
147018 *pRc = rc;
147019 return cksum;
147023 ** Check if the contents of the FTS index match the current contents of the
147024 ** content table. If no error occurs and the contents do match, set *pbOk
147025 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
147026 ** to false before returning.
147028 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
147029 ** code. The final value of *pbOk is undefined in this case.
147031 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
147032 int rc = SQLITE_OK; /* Return code */
147033 u64 cksum1 = 0; /* Checksum based on FTS index contents */
147034 u64 cksum2 = 0; /* Checksum based on %_content contents */
147035 sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
147037 /* This block calculates the checksum according to the FTS index. */
147038 rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
147039 if( rc==SQLITE_OK ){
147040 int rc2;
147041 sqlite3_bind_int(pAllLangid, 1, p->nIndex);
147042 while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
147043 int iLangid = sqlite3_column_int(pAllLangid, 0);
147044 int i;
147045 for(i=0; i<p->nIndex; i++){
147046 cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
147049 rc2 = sqlite3_reset(pAllLangid);
147050 if( rc==SQLITE_OK ) rc = rc2;
147053 /* This block calculates the checksum according to the %_content table */
147054 rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
147055 if( rc==SQLITE_OK ){
147056 sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
147057 sqlite3_stmt *pStmt = 0;
147058 char *zSql;
147060 zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
147061 if( !zSql ){
147062 rc = SQLITE_NOMEM;
147063 }else{
147064 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
147065 sqlite3_free(zSql);
147068 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
147069 i64 iDocid = sqlite3_column_int64(pStmt, 0);
147070 int iLang = langidFromSelect(p, pStmt);
147071 int iCol;
147073 for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
147074 if( p->abNotindexed[iCol]==0 ){
147075 const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
147076 int nText = sqlite3_column_bytes(pStmt, iCol+1);
147077 sqlite3_tokenizer_cursor *pT = 0;
147079 rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
147080 while( rc==SQLITE_OK ){
147081 char const *zToken; /* Buffer containing token */
147082 int nToken = 0; /* Number of bytes in token */
147083 int iDum1 = 0, iDum2 = 0; /* Dummy variables */
147084 int iPos = 0; /* Position of token in zText */
147086 rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
147087 if( rc==SQLITE_OK ){
147088 int i;
147089 cksum2 = cksum2 ^ fts3ChecksumEntry(
147090 zToken, nToken, iLang, 0, iDocid, iCol, iPos
147092 for(i=1; i<p->nIndex; i++){
147093 if( p->aIndex[i].nPrefix<=nToken ){
147094 cksum2 = cksum2 ^ fts3ChecksumEntry(
147095 zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
147101 if( pT ) pModule->xClose(pT);
147102 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
147107 sqlite3_finalize(pStmt);
147110 *pbOk = (cksum1==cksum2);
147111 return rc;
147115 ** Run the integrity-check. If no error occurs and the current contents of
147116 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
147117 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
147119 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
147120 ** error code.
147122 ** The integrity-check works as follows. For each token and indexed token
147123 ** prefix in the document set, a 64-bit checksum is calculated (by code
147124 ** in fts3ChecksumEntry()) based on the following:
147126 ** + The index number (0 for the main index, 1 for the first prefix
147127 ** index etc.),
147128 ** + The token (or token prefix) text itself,
147129 ** + The language-id of the row it appears in,
147130 ** + The docid of the row it appears in,
147131 ** + The column it appears in, and
147132 ** + The tokens position within that column.
147134 ** The checksums for all entries in the index are XORed together to create
147135 ** a single checksum for the entire index.
147137 ** The integrity-check code calculates the same checksum in two ways:
147139 ** 1. By scanning the contents of the FTS index, and
147140 ** 2. By scanning and tokenizing the content table.
147142 ** If the two checksums are identical, the integrity-check is deemed to have
147143 ** passed.
147145 static int fts3DoIntegrityCheck(
147146 Fts3Table *p /* FTS3 table handle */
147148 int rc;
147149 int bOk = 0;
147150 rc = fts3IntegrityCheck(p, &bOk);
147151 if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
147152 return rc;
147156 ** Handle a 'special' INSERT of the form:
147158 ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
147160 ** Argument pVal contains the result of <expr>. Currently the only
147161 ** meaningful value to insert is the text 'optimize'.
147163 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
147164 int rc; /* Return Code */
147165 const char *zVal = (const char *)sqlite3_value_text(pVal);
147166 int nVal = sqlite3_value_bytes(pVal);
147168 if( !zVal ){
147169 return SQLITE_NOMEM;
147170 }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
147171 rc = fts3DoOptimize(p, 0);
147172 }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
147173 rc = fts3DoRebuild(p);
147174 }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
147175 rc = fts3DoIntegrityCheck(p);
147176 }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
147177 rc = fts3DoIncrmerge(p, &zVal[6]);
147178 }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
147179 rc = fts3DoAutoincrmerge(p, &zVal[10]);
147180 #ifdef SQLITE_TEST
147181 }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
147182 p->nNodeSize = atoi(&zVal[9]);
147183 rc = SQLITE_OK;
147184 }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
147185 p->nMaxPendingData = atoi(&zVal[11]);
147186 rc = SQLITE_OK;
147187 }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
147188 p->bNoIncrDoclist = atoi(&zVal[21]);
147189 rc = SQLITE_OK;
147190 #endif
147191 }else{
147192 rc = SQLITE_ERROR;
147195 return rc;
147198 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
147200 ** Delete all cached deferred doclists. Deferred doclists are cached
147201 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
147203 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
147204 Fts3DeferredToken *pDef;
147205 for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
147206 fts3PendingListDelete(pDef->pList);
147207 pDef->pList = 0;
147212 ** Free all entries in the pCsr->pDeffered list. Entries are added to
147213 ** this list using sqlite3Fts3DeferToken().
147215 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
147216 Fts3DeferredToken *pDef;
147217 Fts3DeferredToken *pNext;
147218 for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
147219 pNext = pDef->pNext;
147220 fts3PendingListDelete(pDef->pList);
147221 sqlite3_free(pDef);
147223 pCsr->pDeferred = 0;
147227 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
147228 ** based on the row that pCsr currently points to.
147230 ** A deferred-doclist is like any other doclist with position information
147231 ** included, except that it only contains entries for a single row of the
147232 ** table, not for all rows.
147234 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
147235 int rc = SQLITE_OK; /* Return code */
147236 if( pCsr->pDeferred ){
147237 int i; /* Used to iterate through table columns */
147238 sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
147239 Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
147241 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
147242 sqlite3_tokenizer *pT = p->pTokenizer;
147243 sqlite3_tokenizer_module const *pModule = pT->pModule;
147245 assert( pCsr->isRequireSeek==0 );
147246 iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
147248 for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
147249 if( p->abNotindexed[i]==0 ){
147250 const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
147251 sqlite3_tokenizer_cursor *pTC = 0;
147253 rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
147254 while( rc==SQLITE_OK ){
147255 char const *zToken; /* Buffer containing token */
147256 int nToken = 0; /* Number of bytes in token */
147257 int iDum1 = 0, iDum2 = 0; /* Dummy variables */
147258 int iPos = 0; /* Position of token in zText */
147260 rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
147261 for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
147262 Fts3PhraseToken *pPT = pDef->pToken;
147263 if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
147264 && (pPT->bFirst==0 || iPos==0)
147265 && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
147266 && (0==memcmp(zToken, pPT->z, pPT->n))
147268 fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
147272 if( pTC ) pModule->xClose(pTC);
147273 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
147277 for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
147278 if( pDef->pList ){
147279 rc = fts3PendingListAppendVarint(&pDef->pList, 0);
147284 return rc;
147287 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
147288 Fts3DeferredToken *p,
147289 char **ppData,
147290 int *pnData
147292 char *pRet;
147293 int nSkip;
147294 sqlite3_int64 dummy;
147296 *ppData = 0;
147297 *pnData = 0;
147299 if( p->pList==0 ){
147300 return SQLITE_OK;
147303 pRet = (char *)sqlite3_malloc(p->pList->nData);
147304 if( !pRet ) return SQLITE_NOMEM;
147306 nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
147307 *pnData = p->pList->nData - nSkip;
147308 *ppData = pRet;
147310 memcpy(pRet, &p->pList->aData[nSkip], *pnData);
147311 return SQLITE_OK;
147315 ** Add an entry for token pToken to the pCsr->pDeferred list.
147317 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
147318 Fts3Cursor *pCsr, /* Fts3 table cursor */
147319 Fts3PhraseToken *pToken, /* Token to defer */
147320 int iCol /* Column that token must appear in (or -1) */
147322 Fts3DeferredToken *pDeferred;
147323 pDeferred = sqlite3_malloc(sizeof(*pDeferred));
147324 if( !pDeferred ){
147325 return SQLITE_NOMEM;
147327 memset(pDeferred, 0, sizeof(*pDeferred));
147328 pDeferred->pToken = pToken;
147329 pDeferred->pNext = pCsr->pDeferred;
147330 pDeferred->iCol = iCol;
147331 pCsr->pDeferred = pDeferred;
147333 assert( pToken->pDeferred==0 );
147334 pToken->pDeferred = pDeferred;
147336 return SQLITE_OK;
147338 #endif
147341 ** SQLite value pRowid contains the rowid of a row that may or may not be
147342 ** present in the FTS3 table. If it is, delete it and adjust the contents
147343 ** of subsiduary data structures accordingly.
147345 static int fts3DeleteByRowid(
147346 Fts3Table *p,
147347 sqlite3_value *pRowid,
147348 int *pnChng, /* IN/OUT: Decrement if row is deleted */
147349 u32 *aSzDel
147351 int rc = SQLITE_OK; /* Return code */
147352 int bFound = 0; /* True if *pRowid really is in the table */
147354 fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
147355 if( bFound && rc==SQLITE_OK ){
147356 int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
147357 rc = fts3IsEmpty(p, pRowid, &isEmpty);
147358 if( rc==SQLITE_OK ){
147359 if( isEmpty ){
147360 /* Deleting this row means the whole table is empty. In this case
147361 ** delete the contents of all three tables and throw away any
147362 ** data in the pendingTerms hash table. */
147363 rc = fts3DeleteAll(p, 1);
147364 *pnChng = 0;
147365 memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
147366 }else{
147367 *pnChng = *pnChng - 1;
147368 if( p->zContentTbl==0 ){
147369 fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
147371 if( p->bHasDocsize ){
147372 fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
147378 return rc;
147382 ** This function does the work for the xUpdate method of FTS3 virtual
147383 ** tables. The schema of the virtual table being:
147385 ** CREATE TABLE <table name>(
147386 ** <user columns>,
147387 ** <table name> HIDDEN,
147388 ** docid HIDDEN,
147389 ** <langid> HIDDEN
147390 ** );
147394 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
147395 sqlite3_vtab *pVtab, /* FTS3 vtab object */
147396 int nArg, /* Size of argument array */
147397 sqlite3_value **apVal, /* Array of arguments */
147398 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
147400 Fts3Table *p = (Fts3Table *)pVtab;
147401 int rc = SQLITE_OK; /* Return Code */
147402 int isRemove = 0; /* True for an UPDATE or DELETE */
147403 u32 *aSzIns = 0; /* Sizes of inserted documents */
147404 u32 *aSzDel = 0; /* Sizes of deleted documents */
147405 int nChng = 0; /* Net change in number of documents */
147406 int bInsertDone = 0;
147408 /* At this point it must be known if the %_stat table exists or not.
147409 ** So bHasStat may not be 2. */
147410 assert( p->bHasStat==0 || p->bHasStat==1 );
147412 assert( p->pSegments==0 );
147413 assert(
147414 nArg==1 /* DELETE operations */
147415 || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
147418 /* Check for a "special" INSERT operation. One of the form:
147420 ** INSERT INTO xyz(xyz) VALUES('command');
147422 if( nArg>1
147423 && sqlite3_value_type(apVal[0])==SQLITE_NULL
147424 && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
147426 rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
147427 goto update_out;
147430 if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
147431 rc = SQLITE_CONSTRAINT;
147432 goto update_out;
147435 /* Allocate space to hold the change in document sizes */
147436 aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
147437 if( aSzDel==0 ){
147438 rc = SQLITE_NOMEM;
147439 goto update_out;
147441 aSzIns = &aSzDel[p->nColumn+1];
147442 memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
147444 rc = fts3Writelock(p);
147445 if( rc!=SQLITE_OK ) goto update_out;
147447 /* If this is an INSERT operation, or an UPDATE that modifies the rowid
147448 ** value, then this operation requires constraint handling.
147450 ** If the on-conflict mode is REPLACE, this means that the existing row
147451 ** should be deleted from the database before inserting the new row. Or,
147452 ** if the on-conflict mode is other than REPLACE, then this method must
147453 ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
147454 ** modify the database file.
147456 if( nArg>1 && p->zContentTbl==0 ){
147457 /* Find the value object that holds the new rowid value. */
147458 sqlite3_value *pNewRowid = apVal[3+p->nColumn];
147459 if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
147460 pNewRowid = apVal[1];
147463 if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
147464 sqlite3_value_type(apVal[0])==SQLITE_NULL
147465 || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
147467 /* The new rowid is not NULL (in this case the rowid will be
147468 ** automatically assigned and there is no chance of a conflict), and
147469 ** the statement is either an INSERT or an UPDATE that modifies the
147470 ** rowid column. So if the conflict mode is REPLACE, then delete any
147471 ** existing row with rowid=pNewRowid.
147473 ** Or, if the conflict mode is not REPLACE, insert the new record into
147474 ** the %_content table. If we hit the duplicate rowid constraint (or any
147475 ** other error) while doing so, return immediately.
147477 ** This branch may also run if pNewRowid contains a value that cannot
147478 ** be losslessly converted to an integer. In this case, the eventual
147479 ** call to fts3InsertData() (either just below or further on in this
147480 ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
147481 ** invoked, it will delete zero rows (since no row will have
147482 ** docid=$pNewRowid if $pNewRowid is not an integer value).
147484 if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
147485 rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
147486 }else{
147487 rc = fts3InsertData(p, apVal, pRowid);
147488 bInsertDone = 1;
147492 if( rc!=SQLITE_OK ){
147493 goto update_out;
147496 /* If this is a DELETE or UPDATE operation, remove the old record. */
147497 if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
147498 assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
147499 rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
147500 isRemove = 1;
147503 /* If this is an INSERT or UPDATE operation, insert the new record. */
147504 if( nArg>1 && rc==SQLITE_OK ){
147505 int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
147506 if( bInsertDone==0 ){
147507 rc = fts3InsertData(p, apVal, pRowid);
147508 if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
147509 rc = FTS_CORRUPT_VTAB;
147512 if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
147513 rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
147515 if( rc==SQLITE_OK ){
147516 assert( p->iPrevDocid==*pRowid );
147517 rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
147519 if( p->bHasDocsize ){
147520 fts3InsertDocsize(&rc, p, aSzIns);
147522 nChng++;
147525 if( p->bFts4 ){
147526 fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
147529 update_out:
147530 sqlite3_free(aSzDel);
147531 sqlite3Fts3SegmentsClose(p);
147532 return rc;
147536 ** Flush any data in the pending-terms hash table to disk. If successful,
147537 ** merge all segments in the database (including the new segment, if
147538 ** there was any data to flush) into a single segment.
147540 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
147541 int rc;
147542 rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
147543 if( rc==SQLITE_OK ){
147544 rc = fts3DoOptimize(p, 1);
147545 if( rc==SQLITE_OK || rc==SQLITE_DONE ){
147546 int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
147547 if( rc2!=SQLITE_OK ) rc = rc2;
147548 }else{
147549 sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
147550 sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
147553 sqlite3Fts3SegmentsClose(p);
147554 return rc;
147557 #endif
147559 /************** End of fts3_write.c ******************************************/
147560 /************** Begin file fts3_snippet.c ************************************/
147562 ** 2009 Oct 23
147564 ** The author disclaims copyright to this source code. In place of
147565 ** a legal notice, here is a blessing:
147567 ** May you do good and not evil.
147568 ** May you find forgiveness for yourself and forgive others.
147569 ** May you share freely, never taking more than you give.
147571 ******************************************************************************
147574 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
147576 /* #include <string.h> */
147577 /* #include <assert.h> */
147580 ** Characters that may appear in the second argument to matchinfo().
147582 #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
147583 #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
147584 #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
147585 #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
147586 #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
147587 #define FTS3_MATCHINFO_LCS 's' /* nCol values */
147588 #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
147591 ** The default value for the second argument to matchinfo().
147593 #define FTS3_MATCHINFO_DEFAULT "pcx"
147597 ** Used as an fts3ExprIterate() context when loading phrase doclists to
147598 ** Fts3Expr.aDoclist[]/nDoclist.
147600 typedef struct LoadDoclistCtx LoadDoclistCtx;
147601 struct LoadDoclistCtx {
147602 Fts3Cursor *pCsr; /* FTS3 Cursor */
147603 int nPhrase; /* Number of phrases seen so far */
147604 int nToken; /* Number of tokens seen so far */
147608 ** The following types are used as part of the implementation of the
147609 ** fts3BestSnippet() routine.
147611 typedef struct SnippetIter SnippetIter;
147612 typedef struct SnippetPhrase SnippetPhrase;
147613 typedef struct SnippetFragment SnippetFragment;
147615 struct SnippetIter {
147616 Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
147617 int iCol; /* Extract snippet from this column */
147618 int nSnippet; /* Requested snippet length (in tokens) */
147619 int nPhrase; /* Number of phrases in query */
147620 SnippetPhrase *aPhrase; /* Array of size nPhrase */
147621 int iCurrent; /* First token of current snippet */
147624 struct SnippetPhrase {
147625 int nToken; /* Number of tokens in phrase */
147626 char *pList; /* Pointer to start of phrase position list */
147627 int iHead; /* Next value in position list */
147628 char *pHead; /* Position list data following iHead */
147629 int iTail; /* Next value in trailing position list */
147630 char *pTail; /* Position list data following iTail */
147633 struct SnippetFragment {
147634 int iCol; /* Column snippet is extracted from */
147635 int iPos; /* Index of first token in snippet */
147636 u64 covered; /* Mask of query phrases covered */
147637 u64 hlmask; /* Mask of snippet terms to highlight */
147641 ** This type is used as an fts3ExprIterate() context object while
147642 ** accumulating the data returned by the matchinfo() function.
147644 typedef struct MatchInfo MatchInfo;
147645 struct MatchInfo {
147646 Fts3Cursor *pCursor; /* FTS3 Cursor */
147647 int nCol; /* Number of columns in table */
147648 int nPhrase; /* Number of matchable phrases in query */
147649 sqlite3_int64 nDoc; /* Number of docs in database */
147650 u32 *aMatchinfo; /* Pre-allocated buffer */
147656 ** The snippet() and offsets() functions both return text values. An instance
147657 ** of the following structure is used to accumulate those values while the
147658 ** functions are running. See fts3StringAppend() for details.
147660 typedef struct StrBuffer StrBuffer;
147661 struct StrBuffer {
147662 char *z; /* Pointer to buffer containing string */
147663 int n; /* Length of z in bytes (excl. nul-term) */
147664 int nAlloc; /* Allocated size of buffer z in bytes */
147669 ** This function is used to help iterate through a position-list. A position
147670 ** list is a list of unique integers, sorted from smallest to largest. Each
147671 ** element of the list is represented by an FTS3 varint that takes the value
147672 ** of the difference between the current element and the previous one plus
147673 ** two. For example, to store the position-list:
147675 ** 4 9 113
147677 ** the three varints:
147679 ** 6 7 106
147681 ** are encoded.
147683 ** When this function is called, *pp points to the start of an element of
147684 ** the list. *piPos contains the value of the previous entry in the list.
147685 ** After it returns, *piPos contains the value of the next element of the
147686 ** list and *pp is advanced to the following varint.
147688 static void fts3GetDeltaPosition(char **pp, int *piPos){
147689 int iVal;
147690 *pp += fts3GetVarint32(*pp, &iVal);
147691 *piPos += (iVal-2);
147695 ** Helper function for fts3ExprIterate() (see below).
147697 static int fts3ExprIterate2(
147698 Fts3Expr *pExpr, /* Expression to iterate phrases of */
147699 int *piPhrase, /* Pointer to phrase counter */
147700 int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
147701 void *pCtx /* Second argument to pass to callback */
147703 int rc; /* Return code */
147704 int eType = pExpr->eType; /* Type of expression node pExpr */
147706 if( eType!=FTSQUERY_PHRASE ){
147707 assert( pExpr->pLeft && pExpr->pRight );
147708 rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
147709 if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
147710 rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
147712 }else{
147713 rc = x(pExpr, *piPhrase, pCtx);
147714 (*piPhrase)++;
147716 return rc;
147720 ** Iterate through all phrase nodes in an FTS3 query, except those that
147721 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
147722 ** For each phrase node found, the supplied callback function is invoked.
147724 ** If the callback function returns anything other than SQLITE_OK,
147725 ** the iteration is abandoned and the error code returned immediately.
147726 ** Otherwise, SQLITE_OK is returned after a callback has been made for
147727 ** all eligible phrase nodes.
147729 static int fts3ExprIterate(
147730 Fts3Expr *pExpr, /* Expression to iterate phrases of */
147731 int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
147732 void *pCtx /* Second argument to pass to callback */
147734 int iPhrase = 0; /* Variable used as the phrase counter */
147735 return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
147739 ** This is an fts3ExprIterate() callback used while loading the doclists
147740 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
147741 ** fts3ExprLoadDoclists().
147743 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
147744 int rc = SQLITE_OK;
147745 Fts3Phrase *pPhrase = pExpr->pPhrase;
147746 LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
147748 UNUSED_PARAMETER(iPhrase);
147750 p->nPhrase++;
147751 p->nToken += pPhrase->nToken;
147753 return rc;
147757 ** Load the doclists for each phrase in the query associated with FTS3 cursor
147758 ** pCsr.
147760 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
147761 ** phrases in the expression (all phrases except those directly or
147762 ** indirectly descended from the right-hand-side of a NOT operator). If
147763 ** pnToken is not NULL, then it is set to the number of tokens in all
147764 ** matchable phrases of the expression.
147766 static int fts3ExprLoadDoclists(
147767 Fts3Cursor *pCsr, /* Fts3 cursor for current query */
147768 int *pnPhrase, /* OUT: Number of phrases in query */
147769 int *pnToken /* OUT: Number of tokens in query */
147771 int rc; /* Return Code */
147772 LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
147773 sCtx.pCsr = pCsr;
147774 rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
147775 if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
147776 if( pnToken ) *pnToken = sCtx.nToken;
147777 return rc;
147780 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
147781 (*(int *)ctx)++;
147782 UNUSED_PARAMETER(pExpr);
147783 UNUSED_PARAMETER(iPhrase);
147784 return SQLITE_OK;
147786 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
147787 int nPhrase = 0;
147788 (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
147789 return nPhrase;
147793 ** Advance the position list iterator specified by the first two
147794 ** arguments so that it points to the first element with a value greater
147795 ** than or equal to parameter iNext.
147797 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
147798 char *pIter = *ppIter;
147799 if( pIter ){
147800 int iIter = *piIter;
147802 while( iIter<iNext ){
147803 if( 0==(*pIter & 0xFE) ){
147804 iIter = -1;
147805 pIter = 0;
147806 break;
147808 fts3GetDeltaPosition(&pIter, &iIter);
147811 *piIter = iIter;
147812 *ppIter = pIter;
147817 ** Advance the snippet iterator to the next candidate snippet.
147819 static int fts3SnippetNextCandidate(SnippetIter *pIter){
147820 int i; /* Loop counter */
147822 if( pIter->iCurrent<0 ){
147823 /* The SnippetIter object has just been initialized. The first snippet
147824 ** candidate always starts at offset 0 (even if this candidate has a
147825 ** score of 0.0).
147827 pIter->iCurrent = 0;
147829 /* Advance the 'head' iterator of each phrase to the first offset that
147830 ** is greater than or equal to (iNext+nSnippet).
147832 for(i=0; i<pIter->nPhrase; i++){
147833 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
147834 fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
147836 }else{
147837 int iStart;
147838 int iEnd = 0x7FFFFFFF;
147840 for(i=0; i<pIter->nPhrase; i++){
147841 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
147842 if( pPhrase->pHead && pPhrase->iHead<iEnd ){
147843 iEnd = pPhrase->iHead;
147846 if( iEnd==0x7FFFFFFF ){
147847 return 1;
147850 pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
147851 for(i=0; i<pIter->nPhrase; i++){
147852 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
147853 fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
147854 fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
147858 return 0;
147862 ** Retrieve information about the current candidate snippet of snippet
147863 ** iterator pIter.
147865 static void fts3SnippetDetails(
147866 SnippetIter *pIter, /* Snippet iterator */
147867 u64 mCovered, /* Bitmask of phrases already covered */
147868 int *piToken, /* OUT: First token of proposed snippet */
147869 int *piScore, /* OUT: "Score" for this snippet */
147870 u64 *pmCover, /* OUT: Bitmask of phrases covered */
147871 u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
147873 int iStart = pIter->iCurrent; /* First token of snippet */
147874 int iScore = 0; /* Score of this snippet */
147875 int i; /* Loop counter */
147876 u64 mCover = 0; /* Mask of phrases covered by this snippet */
147877 u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
147879 for(i=0; i<pIter->nPhrase; i++){
147880 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
147881 if( pPhrase->pTail ){
147882 char *pCsr = pPhrase->pTail;
147883 int iCsr = pPhrase->iTail;
147885 while( iCsr<(iStart+pIter->nSnippet) ){
147886 int j;
147887 u64 mPhrase = (u64)1 << i;
147888 u64 mPos = (u64)1 << (iCsr - iStart);
147889 assert( iCsr>=iStart );
147890 if( (mCover|mCovered)&mPhrase ){
147891 iScore++;
147892 }else{
147893 iScore += 1000;
147895 mCover |= mPhrase;
147897 for(j=0; j<pPhrase->nToken; j++){
147898 mHighlight |= (mPos>>j);
147901 if( 0==(*pCsr & 0x0FE) ) break;
147902 fts3GetDeltaPosition(&pCsr, &iCsr);
147907 /* Set the output variables before returning. */
147908 *piToken = iStart;
147909 *piScore = iScore;
147910 *pmCover = mCover;
147911 *pmHighlight = mHighlight;
147915 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
147916 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
147918 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
147919 SnippetIter *p = (SnippetIter *)ctx;
147920 SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
147921 char *pCsr;
147922 int rc;
147924 pPhrase->nToken = pExpr->pPhrase->nToken;
147925 rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
147926 assert( rc==SQLITE_OK || pCsr==0 );
147927 if( pCsr ){
147928 int iFirst = 0;
147929 pPhrase->pList = pCsr;
147930 fts3GetDeltaPosition(&pCsr, &iFirst);
147931 assert( iFirst>=0 );
147932 pPhrase->pHead = pCsr;
147933 pPhrase->pTail = pCsr;
147934 pPhrase->iHead = iFirst;
147935 pPhrase->iTail = iFirst;
147936 }else{
147937 assert( rc!=SQLITE_OK || (
147938 pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
147942 return rc;
147946 ** Select the fragment of text consisting of nFragment contiguous tokens
147947 ** from column iCol that represent the "best" snippet. The best snippet
147948 ** is the snippet with the highest score, where scores are calculated
147949 ** by adding:
147951 ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
147953 ** (b) +1000 points for the first occurrence of each matchable phrase in
147954 ** the snippet for which the corresponding mCovered bit is not set.
147956 ** The selected snippet parameters are stored in structure *pFragment before
147957 ** returning. The score of the selected snippet is stored in *piScore
147958 ** before returning.
147960 static int fts3BestSnippet(
147961 int nSnippet, /* Desired snippet length */
147962 Fts3Cursor *pCsr, /* Cursor to create snippet for */
147963 int iCol, /* Index of column to create snippet from */
147964 u64 mCovered, /* Mask of phrases already covered */
147965 u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
147966 SnippetFragment *pFragment, /* OUT: Best snippet found */
147967 int *piScore /* OUT: Score of snippet pFragment */
147969 int rc; /* Return Code */
147970 int nList; /* Number of phrases in expression */
147971 SnippetIter sIter; /* Iterates through snippet candidates */
147972 int nByte; /* Number of bytes of space to allocate */
147973 int iBestScore = -1; /* Best snippet score found so far */
147974 int i; /* Loop counter */
147976 memset(&sIter, 0, sizeof(sIter));
147978 /* Iterate through the phrases in the expression to count them. The same
147979 ** callback makes sure the doclists are loaded for each phrase.
147981 rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
147982 if( rc!=SQLITE_OK ){
147983 return rc;
147986 /* Now that it is known how many phrases there are, allocate and zero
147987 ** the required space using malloc().
147989 nByte = sizeof(SnippetPhrase) * nList;
147990 sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
147991 if( !sIter.aPhrase ){
147992 return SQLITE_NOMEM;
147994 memset(sIter.aPhrase, 0, nByte);
147996 /* Initialize the contents of the SnippetIter object. Then iterate through
147997 ** the set of phrases in the expression to populate the aPhrase[] array.
147999 sIter.pCsr = pCsr;
148000 sIter.iCol = iCol;
148001 sIter.nSnippet = nSnippet;
148002 sIter.nPhrase = nList;
148003 sIter.iCurrent = -1;
148004 (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
148006 /* Set the *pmSeen output variable. */
148007 for(i=0; i<nList; i++){
148008 if( sIter.aPhrase[i].pHead ){
148009 *pmSeen |= (u64)1 << i;
148013 /* Loop through all candidate snippets. Store the best snippet in
148014 ** *pFragment. Store its associated 'score' in iBestScore.
148016 pFragment->iCol = iCol;
148017 while( !fts3SnippetNextCandidate(&sIter) ){
148018 int iPos;
148019 int iScore;
148020 u64 mCover;
148021 u64 mHighlight;
148022 fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
148023 assert( iScore>=0 );
148024 if( iScore>iBestScore ){
148025 pFragment->iPos = iPos;
148026 pFragment->hlmask = mHighlight;
148027 pFragment->covered = mCover;
148028 iBestScore = iScore;
148032 sqlite3_free(sIter.aPhrase);
148033 *piScore = iBestScore;
148034 return SQLITE_OK;
148039 ** Append a string to the string-buffer passed as the first argument.
148041 ** If nAppend is negative, then the length of the string zAppend is
148042 ** determined using strlen().
148044 static int fts3StringAppend(
148045 StrBuffer *pStr, /* Buffer to append to */
148046 const char *zAppend, /* Pointer to data to append to buffer */
148047 int nAppend /* Size of zAppend in bytes (or -1) */
148049 if( nAppend<0 ){
148050 nAppend = (int)strlen(zAppend);
148053 /* If there is insufficient space allocated at StrBuffer.z, use realloc()
148054 ** to grow the buffer until so that it is big enough to accomadate the
148055 ** appended data.
148057 if( pStr->n+nAppend+1>=pStr->nAlloc ){
148058 int nAlloc = pStr->nAlloc+nAppend+100;
148059 char *zNew = sqlite3_realloc(pStr->z, nAlloc);
148060 if( !zNew ){
148061 return SQLITE_NOMEM;
148063 pStr->z = zNew;
148064 pStr->nAlloc = nAlloc;
148066 assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
148068 /* Append the data to the string buffer. */
148069 memcpy(&pStr->z[pStr->n], zAppend, nAppend);
148070 pStr->n += nAppend;
148071 pStr->z[pStr->n] = '\0';
148073 return SQLITE_OK;
148077 ** The fts3BestSnippet() function often selects snippets that end with a
148078 ** query term. That is, the final term of the snippet is always a term
148079 ** that requires highlighting. For example, if 'X' is a highlighted term
148080 ** and '.' is a non-highlighted term, BestSnippet() may select:
148082 ** ........X.....X
148084 ** This function "shifts" the beginning of the snippet forward in the
148085 ** document so that there are approximately the same number of
148086 ** non-highlighted terms to the right of the final highlighted term as there
148087 ** are to the left of the first highlighted term. For example, to this:
148089 ** ....X.....X....
148091 ** This is done as part of extracting the snippet text, not when selecting
148092 ** the snippet. Snippet selection is done based on doclists only, so there
148093 ** is no way for fts3BestSnippet() to know whether or not the document
148094 ** actually contains terms that follow the final highlighted term.
148096 static int fts3SnippetShift(
148097 Fts3Table *pTab, /* FTS3 table snippet comes from */
148098 int iLangid, /* Language id to use in tokenizing */
148099 int nSnippet, /* Number of tokens desired for snippet */
148100 const char *zDoc, /* Document text to extract snippet from */
148101 int nDoc, /* Size of buffer zDoc in bytes */
148102 int *piPos, /* IN/OUT: First token of snippet */
148103 u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
148105 u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
148107 if( hlmask ){
148108 int nLeft; /* Tokens to the left of first highlight */
148109 int nRight; /* Tokens to the right of last highlight */
148110 int nDesired; /* Ideal number of tokens to shift forward */
148112 for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
148113 for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
148114 nDesired = (nLeft-nRight)/2;
148116 /* Ideally, the start of the snippet should be pushed forward in the
148117 ** document nDesired tokens. This block checks if there are actually
148118 ** nDesired tokens to the right of the snippet. If so, *piPos and
148119 ** *pHlMask are updated to shift the snippet nDesired tokens to the
148120 ** right. Otherwise, the snippet is shifted by the number of tokens
148121 ** available.
148123 if( nDesired>0 ){
148124 int nShift; /* Number of tokens to shift snippet by */
148125 int iCurrent = 0; /* Token counter */
148126 int rc; /* Return Code */
148127 sqlite3_tokenizer_module *pMod;
148128 sqlite3_tokenizer_cursor *pC;
148129 pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
148131 /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
148132 ** or more tokens in zDoc/nDoc.
148134 rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
148135 if( rc!=SQLITE_OK ){
148136 return rc;
148138 while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
148139 const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
148140 rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
148142 pMod->xClose(pC);
148143 if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
148145 nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
148146 assert( nShift<=nDesired );
148147 if( nShift>0 ){
148148 *piPos += nShift;
148149 *pHlmask = hlmask >> nShift;
148153 return SQLITE_OK;
148157 ** Extract the snippet text for fragment pFragment from cursor pCsr and
148158 ** append it to string buffer pOut.
148160 static int fts3SnippetText(
148161 Fts3Cursor *pCsr, /* FTS3 Cursor */
148162 SnippetFragment *pFragment, /* Snippet to extract */
148163 int iFragment, /* Fragment number */
148164 int isLast, /* True for final fragment in snippet */
148165 int nSnippet, /* Number of tokens in extracted snippet */
148166 const char *zOpen, /* String inserted before highlighted term */
148167 const char *zClose, /* String inserted after highlighted term */
148168 const char *zEllipsis, /* String inserted between snippets */
148169 StrBuffer *pOut /* Write output here */
148171 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148172 int rc; /* Return code */
148173 const char *zDoc; /* Document text to extract snippet from */
148174 int nDoc; /* Size of zDoc in bytes */
148175 int iCurrent = 0; /* Current token number of document */
148176 int iEnd = 0; /* Byte offset of end of current token */
148177 int isShiftDone = 0; /* True after snippet is shifted */
148178 int iPos = pFragment->iPos; /* First token of snippet */
148179 u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
148180 int iCol = pFragment->iCol+1; /* Query column to extract text from */
148181 sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
148182 sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
148184 zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
148185 if( zDoc==0 ){
148186 if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
148187 return SQLITE_NOMEM;
148189 return SQLITE_OK;
148191 nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
148193 /* Open a token cursor on the document. */
148194 pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
148195 rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
148196 if( rc!=SQLITE_OK ){
148197 return rc;
148200 while( rc==SQLITE_OK ){
148201 const char *ZDUMMY; /* Dummy argument used with tokenizer */
148202 int DUMMY1 = -1; /* Dummy argument used with tokenizer */
148203 int iBegin = 0; /* Offset in zDoc of start of token */
148204 int iFin = 0; /* Offset in zDoc of end of token */
148205 int isHighlight = 0; /* True for highlighted terms */
148207 /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
148208 ** in the FTS code the variable that the third argument to xNext points to
148209 ** is initialized to zero before the first (*but not necessarily
148210 ** subsequent*) call to xNext(). This is done for a particular application
148211 ** that needs to know whether or not the tokenizer is being used for
148212 ** snippet generation or for some other purpose.
148214 ** Extreme care is required when writing code to depend on this
148215 ** initialization. It is not a documented part of the tokenizer interface.
148216 ** If a tokenizer is used directly by any code outside of FTS, this
148217 ** convention might not be respected. */
148218 rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
148219 if( rc!=SQLITE_OK ){
148220 if( rc==SQLITE_DONE ){
148221 /* Special case - the last token of the snippet is also the last token
148222 ** of the column. Append any punctuation that occurred between the end
148223 ** of the previous token and the end of the document to the output.
148224 ** Then break out of the loop. */
148225 rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
148227 break;
148229 if( iCurrent<iPos ){ continue; }
148231 if( !isShiftDone ){
148232 int n = nDoc - iBegin;
148233 rc = fts3SnippetShift(
148234 pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
148236 isShiftDone = 1;
148238 /* Now that the shift has been done, check if the initial "..." are
148239 ** required. They are required if (a) this is not the first fragment,
148240 ** or (b) this fragment does not begin at position 0 of its column.
148242 if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
148243 rc = fts3StringAppend(pOut, zEllipsis, -1);
148245 if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
148248 if( iCurrent>=(iPos+nSnippet) ){
148249 if( isLast ){
148250 rc = fts3StringAppend(pOut, zEllipsis, -1);
148252 break;
148255 /* Set isHighlight to true if this term should be highlighted. */
148256 isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
148258 if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
148259 if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
148260 if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
148261 if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
148263 iEnd = iFin;
148266 pMod->xClose(pC);
148267 return rc;
148272 ** This function is used to count the entries in a column-list (a
148273 ** delta-encoded list of term offsets within a single column of a single
148274 ** row). When this function is called, *ppCollist should point to the
148275 ** beginning of the first varint in the column-list (the varint that
148276 ** contains the position of the first matching term in the column data).
148277 ** Before returning, *ppCollist is set to point to the first byte after
148278 ** the last varint in the column-list (either the 0x00 signifying the end
148279 ** of the position-list, or the 0x01 that precedes the column number of
148280 ** the next column in the position-list).
148282 ** The number of elements in the column-list is returned.
148284 static int fts3ColumnlistCount(char **ppCollist){
148285 char *pEnd = *ppCollist;
148286 char c = 0;
148287 int nEntry = 0;
148289 /* A column-list is terminated by either a 0x01 or 0x00. */
148290 while( 0xFE & (*pEnd | c) ){
148291 c = *pEnd++ & 0x80;
148292 if( !c ) nEntry++;
148295 *ppCollist = pEnd;
148296 return nEntry;
148300 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
148301 ** for a single query.
148303 ** fts3ExprIterate() callback to load the 'global' elements of a
148304 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
148305 ** of the matchinfo array that are constant for all rows returned by the
148306 ** current query.
148308 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
148309 ** function populates Matchinfo.aMatchinfo[] as follows:
148311 ** for(iCol=0; iCol<nCol; iCol++){
148312 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
148313 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
148316 ** where X is the number of matches for phrase iPhrase is column iCol of all
148317 ** rows of the table. Y is the number of rows for which column iCol contains
148318 ** at least one instance of phrase iPhrase.
148320 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
148321 ** Y values are set to nDoc, where nDoc is the number of documents in the
148322 ** file system. This is done because the full-text index doclist is required
148323 ** to calculate these values properly, and the full-text index doclist is
148324 ** not available for deferred tokens.
148326 static int fts3ExprGlobalHitsCb(
148327 Fts3Expr *pExpr, /* Phrase expression node */
148328 int iPhrase, /* Phrase number (numbered from zero) */
148329 void *pCtx /* Pointer to MatchInfo structure */
148331 MatchInfo *p = (MatchInfo *)pCtx;
148332 return sqlite3Fts3EvalPhraseStats(
148333 p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
148338 ** fts3ExprIterate() callback used to collect the "local" part of the
148339 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
148340 ** array that are different for each row returned by the query.
148342 static int fts3ExprLocalHitsCb(
148343 Fts3Expr *pExpr, /* Phrase expression node */
148344 int iPhrase, /* Phrase number */
148345 void *pCtx /* Pointer to MatchInfo structure */
148347 int rc = SQLITE_OK;
148348 MatchInfo *p = (MatchInfo *)pCtx;
148349 int iStart = iPhrase * p->nCol * 3;
148350 int i;
148352 for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
148353 char *pCsr;
148354 rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
148355 if( pCsr ){
148356 p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
148357 }else{
148358 p->aMatchinfo[iStart+i*3] = 0;
148362 return rc;
148365 static int fts3MatchinfoCheck(
148366 Fts3Table *pTab,
148367 char cArg,
148368 char **pzErr
148370 if( (cArg==FTS3_MATCHINFO_NPHRASE)
148371 || (cArg==FTS3_MATCHINFO_NCOL)
148372 || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
148373 || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
148374 || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
148375 || (cArg==FTS3_MATCHINFO_LCS)
148376 || (cArg==FTS3_MATCHINFO_HITS)
148378 return SQLITE_OK;
148380 *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
148381 return SQLITE_ERROR;
148384 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
148385 int nVal; /* Number of integers output by cArg */
148387 switch( cArg ){
148388 case FTS3_MATCHINFO_NDOC:
148389 case FTS3_MATCHINFO_NPHRASE:
148390 case FTS3_MATCHINFO_NCOL:
148391 nVal = 1;
148392 break;
148394 case FTS3_MATCHINFO_AVGLENGTH:
148395 case FTS3_MATCHINFO_LENGTH:
148396 case FTS3_MATCHINFO_LCS:
148397 nVal = pInfo->nCol;
148398 break;
148400 default:
148401 assert( cArg==FTS3_MATCHINFO_HITS );
148402 nVal = pInfo->nCol * pInfo->nPhrase * 3;
148403 break;
148406 return nVal;
148409 static int fts3MatchinfoSelectDoctotal(
148410 Fts3Table *pTab,
148411 sqlite3_stmt **ppStmt,
148412 sqlite3_int64 *pnDoc,
148413 const char **paLen
148415 sqlite3_stmt *pStmt;
148416 const char *a;
148417 sqlite3_int64 nDoc;
148419 if( !*ppStmt ){
148420 int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
148421 if( rc!=SQLITE_OK ) return rc;
148423 pStmt = *ppStmt;
148424 assert( sqlite3_data_count(pStmt)==1 );
148426 a = sqlite3_column_blob(pStmt, 0);
148427 a += sqlite3Fts3GetVarint(a, &nDoc);
148428 if( nDoc==0 ) return FTS_CORRUPT_VTAB;
148429 *pnDoc = (u32)nDoc;
148431 if( paLen ) *paLen = a;
148432 return SQLITE_OK;
148436 ** An instance of the following structure is used to store state while
148437 ** iterating through a multi-column position-list corresponding to the
148438 ** hits for a single phrase on a single row in order to calculate the
148439 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
148441 typedef struct LcsIterator LcsIterator;
148442 struct LcsIterator {
148443 Fts3Expr *pExpr; /* Pointer to phrase expression */
148444 int iPosOffset; /* Tokens count up to end of this phrase */
148445 char *pRead; /* Cursor used to iterate through aDoclist */
148446 int iPos; /* Current position */
148450 ** If LcsIterator.iCol is set to the following value, the iterator has
148451 ** finished iterating through all offsets for all columns.
148453 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
148455 static int fts3MatchinfoLcsCb(
148456 Fts3Expr *pExpr, /* Phrase expression node */
148457 int iPhrase, /* Phrase number (numbered from zero) */
148458 void *pCtx /* Pointer to MatchInfo structure */
148460 LcsIterator *aIter = (LcsIterator *)pCtx;
148461 aIter[iPhrase].pExpr = pExpr;
148462 return SQLITE_OK;
148466 ** Advance the iterator passed as an argument to the next position. Return
148467 ** 1 if the iterator is at EOF or if it now points to the start of the
148468 ** position list for the next column.
148470 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
148471 char *pRead = pIter->pRead;
148472 sqlite3_int64 iRead;
148473 int rc = 0;
148475 pRead += sqlite3Fts3GetVarint(pRead, &iRead);
148476 if( iRead==0 || iRead==1 ){
148477 pRead = 0;
148478 rc = 1;
148479 }else{
148480 pIter->iPos += (int)(iRead-2);
148483 pIter->pRead = pRead;
148484 return rc;
148488 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
148490 ** If the call is successful, the longest-common-substring lengths for each
148491 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
148492 ** array before returning. SQLITE_OK is returned in this case.
148494 ** Otherwise, if an error occurs, an SQLite error code is returned and the
148495 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
148496 ** undefined.
148498 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
148499 LcsIterator *aIter;
148500 int i;
148501 int iCol;
148502 int nToken = 0;
148504 /* Allocate and populate the array of LcsIterator objects. The array
148505 ** contains one element for each matchable phrase in the query.
148507 aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
148508 if( !aIter ) return SQLITE_NOMEM;
148509 memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
148510 (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
148512 for(i=0; i<pInfo->nPhrase; i++){
148513 LcsIterator *pIter = &aIter[i];
148514 nToken -= pIter->pExpr->pPhrase->nToken;
148515 pIter->iPosOffset = nToken;
148518 for(iCol=0; iCol<pInfo->nCol; iCol++){
148519 int nLcs = 0; /* LCS value for this column */
148520 int nLive = 0; /* Number of iterators in aIter not at EOF */
148522 for(i=0; i<pInfo->nPhrase; i++){
148523 int rc;
148524 LcsIterator *pIt = &aIter[i];
148525 rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
148526 if( rc!=SQLITE_OK ) return rc;
148527 if( pIt->pRead ){
148528 pIt->iPos = pIt->iPosOffset;
148529 fts3LcsIteratorAdvance(&aIter[i]);
148530 nLive++;
148534 while( nLive>0 ){
148535 LcsIterator *pAdv = 0; /* The iterator to advance by one position */
148536 int nThisLcs = 0; /* LCS for the current iterator positions */
148538 for(i=0; i<pInfo->nPhrase; i++){
148539 LcsIterator *pIter = &aIter[i];
148540 if( pIter->pRead==0 ){
148541 /* This iterator is already at EOF for this column. */
148542 nThisLcs = 0;
148543 }else{
148544 if( pAdv==0 || pIter->iPos<pAdv->iPos ){
148545 pAdv = pIter;
148547 if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
148548 nThisLcs++;
148549 }else{
148550 nThisLcs = 1;
148552 if( nThisLcs>nLcs ) nLcs = nThisLcs;
148555 if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
148558 pInfo->aMatchinfo[iCol] = nLcs;
148561 sqlite3_free(aIter);
148562 return SQLITE_OK;
148566 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
148567 ** be returned by the matchinfo() function. Argument zArg contains the
148568 ** format string passed as the second argument to matchinfo (or the
148569 ** default value "pcx" if no second argument was specified). The format
148570 ** string has already been validated and the pInfo->aMatchinfo[] array
148571 ** is guaranteed to be large enough for the output.
148573 ** If bGlobal is true, then populate all fields of the matchinfo() output.
148574 ** If it is false, then assume that those fields that do not change between
148575 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
148576 ** have already been populated.
148578 ** Return SQLITE_OK if successful, or an SQLite error code if an error
148579 ** occurs. If a value other than SQLITE_OK is returned, the state the
148580 ** pInfo->aMatchinfo[] buffer is left in is undefined.
148582 static int fts3MatchinfoValues(
148583 Fts3Cursor *pCsr, /* FTS3 cursor object */
148584 int bGlobal, /* True to grab the global stats */
148585 MatchInfo *pInfo, /* Matchinfo context object */
148586 const char *zArg /* Matchinfo format string */
148588 int rc = SQLITE_OK;
148589 int i;
148590 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148591 sqlite3_stmt *pSelect = 0;
148593 for(i=0; rc==SQLITE_OK && zArg[i]; i++){
148595 switch( zArg[i] ){
148596 case FTS3_MATCHINFO_NPHRASE:
148597 if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
148598 break;
148600 case FTS3_MATCHINFO_NCOL:
148601 if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
148602 break;
148604 case FTS3_MATCHINFO_NDOC:
148605 if( bGlobal ){
148606 sqlite3_int64 nDoc = 0;
148607 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
148608 pInfo->aMatchinfo[0] = (u32)nDoc;
148610 break;
148612 case FTS3_MATCHINFO_AVGLENGTH:
148613 if( bGlobal ){
148614 sqlite3_int64 nDoc; /* Number of rows in table */
148615 const char *a; /* Aggregate column length array */
148617 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
148618 if( rc==SQLITE_OK ){
148619 int iCol;
148620 for(iCol=0; iCol<pInfo->nCol; iCol++){
148621 u32 iVal;
148622 sqlite3_int64 nToken;
148623 a += sqlite3Fts3GetVarint(a, &nToken);
148624 iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
148625 pInfo->aMatchinfo[iCol] = iVal;
148629 break;
148631 case FTS3_MATCHINFO_LENGTH: {
148632 sqlite3_stmt *pSelectDocsize = 0;
148633 rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
148634 if( rc==SQLITE_OK ){
148635 int iCol;
148636 const char *a = sqlite3_column_blob(pSelectDocsize, 0);
148637 for(iCol=0; iCol<pInfo->nCol; iCol++){
148638 sqlite3_int64 nToken;
148639 a += sqlite3Fts3GetVarint(a, &nToken);
148640 pInfo->aMatchinfo[iCol] = (u32)nToken;
148643 sqlite3_reset(pSelectDocsize);
148644 break;
148647 case FTS3_MATCHINFO_LCS:
148648 rc = fts3ExprLoadDoclists(pCsr, 0, 0);
148649 if( rc==SQLITE_OK ){
148650 rc = fts3MatchinfoLcs(pCsr, pInfo);
148652 break;
148654 default: {
148655 Fts3Expr *pExpr;
148656 assert( zArg[i]==FTS3_MATCHINFO_HITS );
148657 pExpr = pCsr->pExpr;
148658 rc = fts3ExprLoadDoclists(pCsr, 0, 0);
148659 if( rc!=SQLITE_OK ) break;
148660 if( bGlobal ){
148661 if( pCsr->pDeferred ){
148662 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
148663 if( rc!=SQLITE_OK ) break;
148665 rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
148666 if( rc!=SQLITE_OK ) break;
148668 (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
148669 break;
148673 pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
148676 sqlite3_reset(pSelect);
148677 return rc;
148682 ** Populate pCsr->aMatchinfo[] with data for the current row. The
148683 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
148685 static int fts3GetMatchinfo(
148686 Fts3Cursor *pCsr, /* FTS3 Cursor object */
148687 const char *zArg /* Second argument to matchinfo() function */
148689 MatchInfo sInfo;
148690 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148691 int rc = SQLITE_OK;
148692 int bGlobal = 0; /* Collect 'global' stats as well as local */
148694 memset(&sInfo, 0, sizeof(MatchInfo));
148695 sInfo.pCursor = pCsr;
148696 sInfo.nCol = pTab->nColumn;
148698 /* If there is cached matchinfo() data, but the format string for the
148699 ** cache does not match the format string for this request, discard
148700 ** the cached data. */
148701 if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
148702 assert( pCsr->aMatchinfo );
148703 sqlite3_free(pCsr->aMatchinfo);
148704 pCsr->zMatchinfo = 0;
148705 pCsr->aMatchinfo = 0;
148708 /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
148709 ** matchinfo function has been called for this query. In this case
148710 ** allocate the array used to accumulate the matchinfo data and
148711 ** initialize those elements that are constant for every row.
148713 if( pCsr->aMatchinfo==0 ){
148714 int nMatchinfo = 0; /* Number of u32 elements in match-info */
148715 int nArg; /* Bytes in zArg */
148716 int i; /* Used to iterate through zArg */
148718 /* Determine the number of phrases in the query */
148719 pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
148720 sInfo.nPhrase = pCsr->nPhrase;
148722 /* Determine the number of integers in the buffer returned by this call. */
148723 for(i=0; zArg[i]; i++){
148724 nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
148727 /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
148728 nArg = (int)strlen(zArg);
148729 pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
148730 if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
148732 pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
148733 pCsr->nMatchinfo = nMatchinfo;
148734 memcpy(pCsr->zMatchinfo, zArg, nArg+1);
148735 memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
148736 pCsr->isMatchinfoNeeded = 1;
148737 bGlobal = 1;
148740 sInfo.aMatchinfo = pCsr->aMatchinfo;
148741 sInfo.nPhrase = pCsr->nPhrase;
148742 if( pCsr->isMatchinfoNeeded ){
148743 rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
148744 pCsr->isMatchinfoNeeded = 0;
148747 return rc;
148751 ** Implementation of snippet() function.
148753 SQLITE_PRIVATE void sqlite3Fts3Snippet(
148754 sqlite3_context *pCtx, /* SQLite function call context */
148755 Fts3Cursor *pCsr, /* Cursor object */
148756 const char *zStart, /* Snippet start text - "<b>" */
148757 const char *zEnd, /* Snippet end text - "</b>" */
148758 const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
148759 int iCol, /* Extract snippet from this column */
148760 int nToken /* Approximate number of tokens in snippet */
148762 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148763 int rc = SQLITE_OK;
148764 int i;
148765 StrBuffer res = {0, 0, 0};
148767 /* The returned text includes up to four fragments of text extracted from
148768 ** the data in the current row. The first iteration of the for(...) loop
148769 ** below attempts to locate a single fragment of text nToken tokens in
148770 ** size that contains at least one instance of all phrases in the query
148771 ** expression that appear in the current row. If such a fragment of text
148772 ** cannot be found, the second iteration of the loop attempts to locate
148773 ** a pair of fragments, and so on.
148775 int nSnippet = 0; /* Number of fragments in this snippet */
148776 SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
148777 int nFToken = -1; /* Number of tokens in each fragment */
148779 if( !pCsr->pExpr ){
148780 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
148781 return;
148784 for(nSnippet=1; 1; nSnippet++){
148786 int iSnip; /* Loop counter 0..nSnippet-1 */
148787 u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
148788 u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
148790 if( nToken>=0 ){
148791 nFToken = (nToken+nSnippet-1) / nSnippet;
148792 }else{
148793 nFToken = -1 * nToken;
148796 for(iSnip=0; iSnip<nSnippet; iSnip++){
148797 int iBestScore = -1; /* Best score of columns checked so far */
148798 int iRead; /* Used to iterate through columns */
148799 SnippetFragment *pFragment = &aSnippet[iSnip];
148801 memset(pFragment, 0, sizeof(*pFragment));
148803 /* Loop through all columns of the table being considered for snippets.
148804 ** If the iCol argument to this function was negative, this means all
148805 ** columns of the FTS3 table. Otherwise, only column iCol is considered.
148807 for(iRead=0; iRead<pTab->nColumn; iRead++){
148808 SnippetFragment sF = {0, 0, 0, 0};
148809 int iS;
148810 if( iCol>=0 && iRead!=iCol ) continue;
148812 /* Find the best snippet of nFToken tokens in column iRead. */
148813 rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
148814 if( rc!=SQLITE_OK ){
148815 goto snippet_out;
148817 if( iS>iBestScore ){
148818 *pFragment = sF;
148819 iBestScore = iS;
148823 mCovered |= pFragment->covered;
148826 /* If all query phrases seen by fts3BestSnippet() are present in at least
148827 ** one of the nSnippet snippet fragments, break out of the loop.
148829 assert( (mCovered&mSeen)==mCovered );
148830 if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
148833 assert( nFToken>0 );
148835 for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
148836 rc = fts3SnippetText(pCsr, &aSnippet[i],
148837 i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
148841 snippet_out:
148842 sqlite3Fts3SegmentsClose(pTab);
148843 if( rc!=SQLITE_OK ){
148844 sqlite3_result_error_code(pCtx, rc);
148845 sqlite3_free(res.z);
148846 }else{
148847 sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
148852 typedef struct TermOffset TermOffset;
148853 typedef struct TermOffsetCtx TermOffsetCtx;
148855 struct TermOffset {
148856 char *pList; /* Position-list */
148857 int iPos; /* Position just read from pList */
148858 int iOff; /* Offset of this term from read positions */
148861 struct TermOffsetCtx {
148862 Fts3Cursor *pCsr;
148863 int iCol; /* Column of table to populate aTerm for */
148864 int iTerm;
148865 sqlite3_int64 iDocid;
148866 TermOffset *aTerm;
148870 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
148872 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
148873 TermOffsetCtx *p = (TermOffsetCtx *)ctx;
148874 int nTerm; /* Number of tokens in phrase */
148875 int iTerm; /* For looping through nTerm phrase terms */
148876 char *pList; /* Pointer to position list for phrase */
148877 int iPos = 0; /* First position in position-list */
148878 int rc;
148880 UNUSED_PARAMETER(iPhrase);
148881 rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
148882 nTerm = pExpr->pPhrase->nToken;
148883 if( pList ){
148884 fts3GetDeltaPosition(&pList, &iPos);
148885 assert( iPos>=0 );
148888 for(iTerm=0; iTerm<nTerm; iTerm++){
148889 TermOffset *pT = &p->aTerm[p->iTerm++];
148890 pT->iOff = nTerm-iTerm-1;
148891 pT->pList = pList;
148892 pT->iPos = iPos;
148895 return rc;
148899 ** Implementation of offsets() function.
148901 SQLITE_PRIVATE void sqlite3Fts3Offsets(
148902 sqlite3_context *pCtx, /* SQLite function call context */
148903 Fts3Cursor *pCsr /* Cursor object */
148905 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148906 sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
148907 int rc; /* Return Code */
148908 int nToken; /* Number of tokens in query */
148909 int iCol; /* Column currently being processed */
148910 StrBuffer res = {0, 0, 0}; /* Result string */
148911 TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
148913 if( !pCsr->pExpr ){
148914 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
148915 return;
148918 memset(&sCtx, 0, sizeof(sCtx));
148919 assert( pCsr->isRequireSeek==0 );
148921 /* Count the number of terms in the query */
148922 rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
148923 if( rc!=SQLITE_OK ) goto offsets_out;
148925 /* Allocate the array of TermOffset iterators. */
148926 sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
148927 if( 0==sCtx.aTerm ){
148928 rc = SQLITE_NOMEM;
148929 goto offsets_out;
148931 sCtx.iDocid = pCsr->iPrevId;
148932 sCtx.pCsr = pCsr;
148934 /* Loop through the table columns, appending offset information to
148935 ** string-buffer res for each column.
148937 for(iCol=0; iCol<pTab->nColumn; iCol++){
148938 sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
148939 const char *ZDUMMY; /* Dummy argument used with xNext() */
148940 int NDUMMY = 0; /* Dummy argument used with xNext() */
148941 int iStart = 0;
148942 int iEnd = 0;
148943 int iCurrent = 0;
148944 const char *zDoc;
148945 int nDoc;
148947 /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
148948 ** no way that this operation can fail, so the return code from
148949 ** fts3ExprIterate() can be discarded.
148951 sCtx.iCol = iCol;
148952 sCtx.iTerm = 0;
148953 (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
148955 /* Retreive the text stored in column iCol. If an SQL NULL is stored
148956 ** in column iCol, jump immediately to the next iteration of the loop.
148957 ** If an OOM occurs while retrieving the data (this can happen if SQLite
148958 ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
148959 ** to the caller.
148961 zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
148962 nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
148963 if( zDoc==0 ){
148964 if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
148965 continue;
148967 rc = SQLITE_NOMEM;
148968 goto offsets_out;
148971 /* Initialize a tokenizer iterator to iterate through column iCol. */
148972 rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
148973 zDoc, nDoc, &pC
148975 if( rc!=SQLITE_OK ) goto offsets_out;
148977 rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
148978 while( rc==SQLITE_OK ){
148979 int i; /* Used to loop through terms */
148980 int iMinPos = 0x7FFFFFFF; /* Position of next token */
148981 TermOffset *pTerm = 0; /* TermOffset associated with next token */
148983 for(i=0; i<nToken; i++){
148984 TermOffset *pT = &sCtx.aTerm[i];
148985 if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
148986 iMinPos = pT->iPos-pT->iOff;
148987 pTerm = pT;
148991 if( !pTerm ){
148992 /* All offsets for this column have been gathered. */
148993 rc = SQLITE_DONE;
148994 }else{
148995 assert( iCurrent<=iMinPos );
148996 if( 0==(0xFE&*pTerm->pList) ){
148997 pTerm->pList = 0;
148998 }else{
148999 fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
149001 while( rc==SQLITE_OK && iCurrent<iMinPos ){
149002 rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
149004 if( rc==SQLITE_OK ){
149005 char aBuffer[64];
149006 sqlite3_snprintf(sizeof(aBuffer), aBuffer,
149007 "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
149009 rc = fts3StringAppend(&res, aBuffer, -1);
149010 }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
149011 rc = FTS_CORRUPT_VTAB;
149015 if( rc==SQLITE_DONE ){
149016 rc = SQLITE_OK;
149019 pMod->xClose(pC);
149020 if( rc!=SQLITE_OK ) goto offsets_out;
149023 offsets_out:
149024 sqlite3_free(sCtx.aTerm);
149025 assert( rc!=SQLITE_DONE );
149026 sqlite3Fts3SegmentsClose(pTab);
149027 if( rc!=SQLITE_OK ){
149028 sqlite3_result_error_code(pCtx, rc);
149029 sqlite3_free(res.z);
149030 }else{
149031 sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
149033 return;
149037 ** Implementation of matchinfo() function.
149039 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
149040 sqlite3_context *pContext, /* Function call context */
149041 Fts3Cursor *pCsr, /* FTS3 table cursor */
149042 const char *zArg /* Second arg to matchinfo() function */
149044 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
149045 int rc;
149046 int i;
149047 const char *zFormat;
149049 if( zArg ){
149050 for(i=0; zArg[i]; i++){
149051 char *zErr = 0;
149052 if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
149053 sqlite3_result_error(pContext, zErr, -1);
149054 sqlite3_free(zErr);
149055 return;
149058 zFormat = zArg;
149059 }else{
149060 zFormat = FTS3_MATCHINFO_DEFAULT;
149063 if( !pCsr->pExpr ){
149064 sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
149065 return;
149068 /* Retrieve matchinfo() data. */
149069 rc = fts3GetMatchinfo(pCsr, zFormat);
149070 sqlite3Fts3SegmentsClose(pTab);
149072 if( rc!=SQLITE_OK ){
149073 sqlite3_result_error_code(pContext, rc);
149074 }else{
149075 int n = pCsr->nMatchinfo * sizeof(u32);
149076 sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
149080 #endif
149082 /************** End of fts3_snippet.c ****************************************/
149083 /************** Begin file fts3_unicode.c ************************************/
149085 ** 2012 May 24
149087 ** The author disclaims copyright to this source code. In place of
149088 ** a legal notice, here is a blessing:
149090 ** May you do good and not evil.
149091 ** May you find forgiveness for yourself and forgive others.
149092 ** May you share freely, never taking more than you give.
149094 ******************************************************************************
149096 ** Implementation of the "unicode" full-text-search tokenizer.
149099 #ifndef SQLITE_DISABLE_FTS3_UNICODE
149101 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
149103 /* #include <assert.h> */
149104 /* #include <stdlib.h> */
149105 /* #include <stdio.h> */
149106 /* #include <string.h> */
149110 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
149111 ** from the sqlite3 source file utf.c. If this file is compiled as part
149112 ** of the amalgamation, they are not required.
149114 #ifndef SQLITE_AMALGAMATION
149116 static const unsigned char sqlite3Utf8Trans1[] = {
149117 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
149118 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
149119 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
149120 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
149121 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
149122 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
149123 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
149124 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
149127 #define READ_UTF8(zIn, zTerm, c) \
149128 c = *(zIn++); \
149129 if( c>=0xc0 ){ \
149130 c = sqlite3Utf8Trans1[c-0xc0]; \
149131 while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
149132 c = (c<<6) + (0x3f & *(zIn++)); \
149134 if( c<0x80 \
149135 || (c&0xFFFFF800)==0xD800 \
149136 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
149139 #define WRITE_UTF8(zOut, c) { \
149140 if( c<0x00080 ){ \
149141 *zOut++ = (u8)(c&0xFF); \
149143 else if( c<0x00800 ){ \
149144 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
149145 *zOut++ = 0x80 + (u8)(c & 0x3F); \
149147 else if( c<0x10000 ){ \
149148 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
149149 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
149150 *zOut++ = 0x80 + (u8)(c & 0x3F); \
149151 }else{ \
149152 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
149153 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
149154 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
149155 *zOut++ = 0x80 + (u8)(c & 0x3F); \
149159 #endif /* ifndef SQLITE_AMALGAMATION */
149161 typedef struct unicode_tokenizer unicode_tokenizer;
149162 typedef struct unicode_cursor unicode_cursor;
149164 struct unicode_tokenizer {
149165 sqlite3_tokenizer base;
149166 int bRemoveDiacritic;
149167 int nException;
149168 int *aiException;
149171 struct unicode_cursor {
149172 sqlite3_tokenizer_cursor base;
149173 const unsigned char *aInput; /* Input text being tokenized */
149174 int nInput; /* Size of aInput[] in bytes */
149175 int iOff; /* Current offset within aInput[] */
149176 int iToken; /* Index of next token to be returned */
149177 char *zToken; /* storage for current token */
149178 int nAlloc; /* space allocated at zToken */
149183 ** Destroy a tokenizer allocated by unicodeCreate().
149185 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
149186 if( pTokenizer ){
149187 unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
149188 sqlite3_free(p->aiException);
149189 sqlite3_free(p);
149191 return SQLITE_OK;
149195 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
149196 ** statement has specified that the tokenizer for this table shall consider
149197 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
149198 ** token characters (if bAlnum==1).
149200 ** For each codepoint in the zIn/nIn string, this function checks if the
149201 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
149202 ** If so, no action is taken. Otherwise, the codepoint is added to the
149203 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
149204 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
149205 ** codepoints in the aiException[] array.
149207 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
149208 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
149209 ** It is not possible to change the behavior of the tokenizer with respect
149210 ** to these codepoints.
149212 static int unicodeAddExceptions(
149213 unicode_tokenizer *p, /* Tokenizer to add exceptions to */
149214 int bAlnum, /* Replace Isalnum() return value with this */
149215 const char *zIn, /* Array of characters to make exceptions */
149216 int nIn /* Length of z in bytes */
149218 const unsigned char *z = (const unsigned char *)zIn;
149219 const unsigned char *zTerm = &z[nIn];
149220 int iCode;
149221 int nEntry = 0;
149223 assert( bAlnum==0 || bAlnum==1 );
149225 while( z<zTerm ){
149226 READ_UTF8(z, zTerm, iCode);
149227 assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
149228 if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
149229 && sqlite3FtsUnicodeIsdiacritic(iCode)==0
149231 nEntry++;
149235 if( nEntry ){
149236 int *aNew; /* New aiException[] array */
149237 int nNew; /* Number of valid entries in array aNew[] */
149239 aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
149240 if( aNew==0 ) return SQLITE_NOMEM;
149241 nNew = p->nException;
149243 z = (const unsigned char *)zIn;
149244 while( z<zTerm ){
149245 READ_UTF8(z, zTerm, iCode);
149246 if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
149247 && sqlite3FtsUnicodeIsdiacritic(iCode)==0
149249 int i, j;
149250 for(i=0; i<nNew && aNew[i]<iCode; i++);
149251 for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
149252 aNew[i] = iCode;
149253 nNew++;
149256 p->aiException = aNew;
149257 p->nException = nNew;
149260 return SQLITE_OK;
149264 ** Return true if the p->aiException[] array contains the value iCode.
149266 static int unicodeIsException(unicode_tokenizer *p, int iCode){
149267 if( p->nException>0 ){
149268 int *a = p->aiException;
149269 int iLo = 0;
149270 int iHi = p->nException-1;
149272 while( iHi>=iLo ){
149273 int iTest = (iHi + iLo) / 2;
149274 if( iCode==a[iTest] ){
149275 return 1;
149276 }else if( iCode>a[iTest] ){
149277 iLo = iTest+1;
149278 }else{
149279 iHi = iTest-1;
149284 return 0;
149288 ** Return true if, for the purposes of tokenization, codepoint iCode is
149289 ** considered a token character (not a separator).
149291 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
149292 assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
149293 return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
149297 ** Create a new tokenizer instance.
149299 static int unicodeCreate(
149300 int nArg, /* Size of array argv[] */
149301 const char * const *azArg, /* Tokenizer creation arguments */
149302 sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
149304 unicode_tokenizer *pNew; /* New tokenizer object */
149305 int i;
149306 int rc = SQLITE_OK;
149308 pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
149309 if( pNew==NULL ) return SQLITE_NOMEM;
149310 memset(pNew, 0, sizeof(unicode_tokenizer));
149311 pNew->bRemoveDiacritic = 1;
149313 for(i=0; rc==SQLITE_OK && i<nArg; i++){
149314 const char *z = azArg[i];
149315 int n = (int)strlen(z);
149317 if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
149318 pNew->bRemoveDiacritic = 1;
149320 else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
149321 pNew->bRemoveDiacritic = 0;
149323 else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
149324 rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
149326 else if( n>=11 && memcmp("separators=", z, 11)==0 ){
149327 rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
149329 else{
149330 /* Unrecognized argument */
149331 rc = SQLITE_ERROR;
149335 if( rc!=SQLITE_OK ){
149336 unicodeDestroy((sqlite3_tokenizer *)pNew);
149337 pNew = 0;
149339 *pp = (sqlite3_tokenizer *)pNew;
149340 return rc;
149344 ** Prepare to begin tokenizing a particular string. The input
149345 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
149346 ** used to incrementally tokenize this string is returned in
149347 ** *ppCursor.
149349 static int unicodeOpen(
149350 sqlite3_tokenizer *p, /* The tokenizer */
149351 const char *aInput, /* Input string */
149352 int nInput, /* Size of string aInput in bytes */
149353 sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
149355 unicode_cursor *pCsr;
149357 pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
149358 if( pCsr==0 ){
149359 return SQLITE_NOMEM;
149361 memset(pCsr, 0, sizeof(unicode_cursor));
149363 pCsr->aInput = (const unsigned char *)aInput;
149364 if( aInput==0 ){
149365 pCsr->nInput = 0;
149366 }else if( nInput<0 ){
149367 pCsr->nInput = (int)strlen(aInput);
149368 }else{
149369 pCsr->nInput = nInput;
149372 *pp = &pCsr->base;
149373 UNUSED_PARAMETER(p);
149374 return SQLITE_OK;
149378 ** Close a tokenization cursor previously opened by a call to
149379 ** simpleOpen() above.
149381 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
149382 unicode_cursor *pCsr = (unicode_cursor *) pCursor;
149383 sqlite3_free(pCsr->zToken);
149384 sqlite3_free(pCsr);
149385 return SQLITE_OK;
149389 ** Extract the next token from a tokenization cursor. The cursor must
149390 ** have been opened by a prior call to simpleOpen().
149392 static int unicodeNext(
149393 sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
149394 const char **paToken, /* OUT: Token text */
149395 int *pnToken, /* OUT: Number of bytes at *paToken */
149396 int *piStart, /* OUT: Starting offset of token */
149397 int *piEnd, /* OUT: Ending offset of token */
149398 int *piPos /* OUT: Position integer of token */
149400 unicode_cursor *pCsr = (unicode_cursor *)pC;
149401 unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
149402 int iCode = 0;
149403 char *zOut;
149404 const unsigned char *z = &pCsr->aInput[pCsr->iOff];
149405 const unsigned char *zStart = z;
149406 const unsigned char *zEnd;
149407 const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
149409 /* Scan past any delimiter characters before the start of the next token.
149410 ** Return SQLITE_DONE early if this takes us all the way to the end of
149411 ** the input. */
149412 while( z<zTerm ){
149413 READ_UTF8(z, zTerm, iCode);
149414 if( unicodeIsAlnum(p, iCode) ) break;
149415 zStart = z;
149417 if( zStart>=zTerm ) return SQLITE_DONE;
149419 zOut = pCsr->zToken;
149421 int iOut;
149423 /* Grow the output buffer if required. */
149424 if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
149425 char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
149426 if( !zNew ) return SQLITE_NOMEM;
149427 zOut = &zNew[zOut - pCsr->zToken];
149428 pCsr->zToken = zNew;
149429 pCsr->nAlloc += 64;
149432 /* Write the folded case of the last character read to the output */
149433 zEnd = z;
149434 iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
149435 if( iOut ){
149436 WRITE_UTF8(zOut, iOut);
149439 /* If the cursor is not at EOF, read the next character */
149440 if( z>=zTerm ) break;
149441 READ_UTF8(z, zTerm, iCode);
149442 }while( unicodeIsAlnum(p, iCode)
149443 || sqlite3FtsUnicodeIsdiacritic(iCode)
149446 /* Set the output variables and return. */
149447 pCsr->iOff = (int)(z - pCsr->aInput);
149448 *paToken = pCsr->zToken;
149449 *pnToken = (int)(zOut - pCsr->zToken);
149450 *piStart = (int)(zStart - pCsr->aInput);
149451 *piEnd = (int)(zEnd - pCsr->aInput);
149452 *piPos = pCsr->iToken++;
149453 return SQLITE_OK;
149457 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
149458 ** structure for the unicode tokenizer.
149460 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
149461 static const sqlite3_tokenizer_module module = {
149463 unicodeCreate,
149464 unicodeDestroy,
149465 unicodeOpen,
149466 unicodeClose,
149467 unicodeNext,
149470 *ppModule = &module;
149473 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
149474 #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
149476 /************** End of fts3_unicode.c ****************************************/
149477 /************** Begin file fts3_unicode2.c ***********************************/
149479 ** 2012 May 25
149481 ** The author disclaims copyright to this source code. In place of
149482 ** a legal notice, here is a blessing:
149484 ** May you do good and not evil.
149485 ** May you find forgiveness for yourself and forgive others.
149486 ** May you share freely, never taking more than you give.
149488 ******************************************************************************
149492 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
149495 #ifndef SQLITE_DISABLE_FTS3_UNICODE
149496 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
149498 /* #include <assert.h> */
149501 ** Return true if the argument corresponds to a unicode codepoint
149502 ** classified as either a letter or a number. Otherwise false.
149504 ** The results are undefined if the value passed to this function
149505 ** is less than zero.
149507 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
149508 /* Each unsigned integer in the following array corresponds to a contiguous
149509 ** range of unicode codepoints that are not either letters or numbers (i.e.
149510 ** codepoints for which this function should return 0).
149512 ** The most significant 22 bits in each 32-bit value contain the first
149513 ** codepoint in the range. The least significant 10 bits are used to store
149514 ** the size of the range (always at least 1). In other words, the value
149515 ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
149516 ** C. It is not possible to represent a range larger than 1023 codepoints
149517 ** using this format.
149519 static const unsigned int aEntry[] = {
149520 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
149521 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
149522 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
149523 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
149524 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
149525 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
149526 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
149527 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
149528 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
149529 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
149530 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
149531 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
149532 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
149533 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
149534 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
149535 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
149536 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
149537 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
149538 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
149539 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
149540 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
149541 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
149542 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
149543 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
149544 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
149545 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
149546 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
149547 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
149548 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
149549 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
149550 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
149551 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
149552 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
149553 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
149554 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
149555 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
149556 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
149557 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
149558 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
149559 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
149560 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
149561 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
149562 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
149563 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
149564 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
149565 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
149566 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
149567 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
149568 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
149569 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
149570 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
149571 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
149572 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
149573 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
149574 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
149575 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
149576 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
149577 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
149578 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
149579 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
149580 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
149581 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
149582 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
149583 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
149584 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
149585 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
149586 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
149587 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
149588 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
149589 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
149590 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
149591 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
149592 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
149593 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
149594 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
149595 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
149596 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
149597 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
149598 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
149599 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
149600 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
149601 0x380400F0,
149603 static const unsigned int aAscii[4] = {
149604 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
149607 if( c<128 ){
149608 return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
149609 }else if( c<(1<<22) ){
149610 unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
149611 int iRes = 0;
149612 int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
149613 int iLo = 0;
149614 while( iHi>=iLo ){
149615 int iTest = (iHi + iLo) / 2;
149616 if( key >= aEntry[iTest] ){
149617 iRes = iTest;
149618 iLo = iTest+1;
149619 }else{
149620 iHi = iTest-1;
149623 assert( aEntry[0]<key );
149624 assert( key>=aEntry[iRes] );
149625 return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
149627 return 1;
149632 ** If the argument is a codepoint corresponding to a lowercase letter
149633 ** in the ASCII range with a diacritic added, return the codepoint
149634 ** of the ASCII letter only. For example, if passed 235 - "LATIN
149635 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
149636 ** E"). The resuls of passing a codepoint that corresponds to an
149637 ** uppercase letter are undefined.
149639 static int remove_diacritic(int c){
149640 unsigned short aDia[] = {
149641 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
149642 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
149643 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
149644 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
149645 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
149646 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
149647 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
149648 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
149649 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
149650 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
149651 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
149652 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
149653 62924, 63050, 63082, 63274, 63390,
149655 char aChar[] = {
149656 '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
149657 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
149658 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
149659 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
149660 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
149661 '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
149662 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
149663 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
149664 'e', 'i', 'o', 'u', 'y',
149667 unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
149668 int iRes = 0;
149669 int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
149670 int iLo = 0;
149671 while( iHi>=iLo ){
149672 int iTest = (iHi + iLo) / 2;
149673 if( key >= aDia[iTest] ){
149674 iRes = iTest;
149675 iLo = iTest+1;
149676 }else{
149677 iHi = iTest-1;
149680 assert( key>=aDia[iRes] );
149681 return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
149686 ** Return true if the argument interpreted as a unicode codepoint
149687 ** is a diacritical modifier character.
149689 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
149690 unsigned int mask0 = 0x08029FDF;
149691 unsigned int mask1 = 0x000361F8;
149692 if( c<768 || c>817 ) return 0;
149693 return (c < 768+32) ?
149694 (mask0 & (1 << (c-768))) :
149695 (mask1 & (1 << (c-768-32)));
149700 ** Interpret the argument as a unicode codepoint. If the codepoint
149701 ** is an upper case character that has a lower case equivalent,
149702 ** return the codepoint corresponding to the lower case version.
149703 ** Otherwise, return a copy of the argument.
149705 ** The results are undefined if the value passed to this function
149706 ** is less than zero.
149708 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
149709 /* Each entry in the following array defines a rule for folding a range
149710 ** of codepoints to lower case. The rule applies to a range of nRange
149711 ** codepoints starting at codepoint iCode.
149713 ** If the least significant bit in flags is clear, then the rule applies
149714 ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
149715 ** need to be folded). Or, if it is set, then the rule only applies to
149716 ** every second codepoint in the range, starting with codepoint C.
149718 ** The 7 most significant bits in flags are an index into the aiOff[]
149719 ** array. If a specific codepoint C does require folding, then its lower
149720 ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
149722 ** The contents of this array are generated by parsing the CaseFolding.txt
149723 ** file distributed as part of the "Unicode Character Database". See
149724 ** http://www.unicode.org for details.
149726 static const struct TableEntry {
149727 unsigned short iCode;
149728 unsigned char flags;
149729 unsigned char nRange;
149730 } aEntry[] = {
149731 {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
149732 {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
149733 {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
149734 {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
149735 {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
149736 {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
149737 {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
149738 {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
149739 {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
149740 {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
149741 {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
149742 {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
149743 {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
149744 {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
149745 {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
149746 {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
149747 {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
149748 {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
149749 {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
149750 {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
149751 {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
149752 {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
149753 {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
149754 {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
149755 {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
149756 {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
149757 {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
149758 {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
149759 {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
149760 {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
149761 {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
149762 {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
149763 {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
149764 {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
149765 {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
149766 {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
149767 {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
149768 {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
149769 {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
149770 {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
149771 {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
149772 {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
149773 {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
149774 {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
149775 {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
149776 {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
149777 {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
149778 {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
149779 {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
149780 {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
149781 {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
149782 {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
149783 {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
149784 {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
149785 {65313, 14, 26},
149787 static const unsigned short aiOff[] = {
149788 1, 2, 8, 15, 16, 26, 28, 32,
149789 37, 38, 40, 48, 63, 64, 69, 71,
149790 79, 80, 116, 202, 203, 205, 206, 207,
149791 209, 210, 211, 213, 214, 217, 218, 219,
149792 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
149793 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
149794 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
149795 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
149796 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
149797 65514, 65521, 65527, 65528, 65529,
149800 int ret = c;
149802 assert( c>=0 );
149803 assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
149805 if( c<128 ){
149806 if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
149807 }else if( c<65536 ){
149808 int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
149809 int iLo = 0;
149810 int iRes = -1;
149812 while( iHi>=iLo ){
149813 int iTest = (iHi + iLo) / 2;
149814 int cmp = (c - aEntry[iTest].iCode);
149815 if( cmp>=0 ){
149816 iRes = iTest;
149817 iLo = iTest+1;
149818 }else{
149819 iHi = iTest-1;
149822 assert( iRes<0 || c>=aEntry[iRes].iCode );
149824 if( iRes>=0 ){
149825 const struct TableEntry *p = &aEntry[iRes];
149826 if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
149827 ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
149828 assert( ret>0 );
149832 if( bRemoveDiacritic ) ret = remove_diacritic(ret);
149835 else if( c>=66560 && c<66600 ){
149836 ret = c + 40;
149839 return ret;
149841 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
149842 #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
149844 /************** End of fts3_unicode2.c ***************************************/
149845 /************** Begin file rtree.c *******************************************/
149847 ** 2001 September 15
149849 ** The author disclaims copyright to this source code. In place of
149850 ** a legal notice, here is a blessing:
149852 ** May you do good and not evil.
149853 ** May you find forgiveness for yourself and forgive others.
149854 ** May you share freely, never taking more than you give.
149856 *************************************************************************
149857 ** This file contains code for implementations of the r-tree and r*-tree
149858 ** algorithms packaged as an SQLite virtual table module.
149862 ** Database Format of R-Tree Tables
149863 ** --------------------------------
149865 ** The data structure for a single virtual r-tree table is stored in three
149866 ** native SQLite tables declared as follows. In each case, the '%' character
149867 ** in the table name is replaced with the user-supplied name of the r-tree
149868 ** table.
149870 ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
149871 ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
149872 ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
149874 ** The data for each node of the r-tree structure is stored in the %_node
149875 ** table. For each node that is not the root node of the r-tree, there is
149876 ** an entry in the %_parent table associating the node with its parent.
149877 ** And for each row of data in the table, there is an entry in the %_rowid
149878 ** table that maps from the entries rowid to the id of the node that it
149879 ** is stored on.
149881 ** The root node of an r-tree always exists, even if the r-tree table is
149882 ** empty. The nodeno of the root node is always 1. All other nodes in the
149883 ** table must be the same size as the root node. The content of each node
149884 ** is formatted as follows:
149886 ** 1. If the node is the root node (node 1), then the first 2 bytes
149887 ** of the node contain the tree depth as a big-endian integer.
149888 ** For non-root nodes, the first 2 bytes are left unused.
149890 ** 2. The next 2 bytes contain the number of entries currently
149891 ** stored in the node.
149893 ** 3. The remainder of the node contains the node entries. Each entry
149894 ** consists of a single 8-byte integer followed by an even number
149895 ** of 4-byte coordinates. For leaf nodes the integer is the rowid
149896 ** of a record. For internal nodes it is the node number of a
149897 ** child page.
149900 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
149902 #ifndef SQLITE_CORE
149903 SQLITE_EXTENSION_INIT1
149904 #else
149905 #endif
149907 /* #include <string.h> */
149908 /* #include <assert.h> */
149909 /* #include <stdio.h> */
149911 #ifndef SQLITE_AMALGAMATION
149912 #include "sqlite3rtree.h"
149913 typedef sqlite3_int64 i64;
149914 typedef unsigned char u8;
149915 typedef unsigned short u16;
149916 typedef unsigned int u32;
149917 #endif
149919 /* The following macro is used to suppress compiler warnings.
149921 #ifndef UNUSED_PARAMETER
149922 # define UNUSED_PARAMETER(x) (void)(x)
149923 #endif
149925 typedef struct Rtree Rtree;
149926 typedef struct RtreeCursor RtreeCursor;
149927 typedef struct RtreeNode RtreeNode;
149928 typedef struct RtreeCell RtreeCell;
149929 typedef struct RtreeConstraint RtreeConstraint;
149930 typedef struct RtreeMatchArg RtreeMatchArg;
149931 typedef struct RtreeGeomCallback RtreeGeomCallback;
149932 typedef union RtreeCoord RtreeCoord;
149933 typedef struct RtreeSearchPoint RtreeSearchPoint;
149935 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
149936 #define RTREE_MAX_DIMENSIONS 5
149938 /* Size of hash table Rtree.aHash. This hash table is not expected to
149939 ** ever contain very many entries, so a fixed number of buckets is
149940 ** used.
149942 #define HASHSIZE 97
149944 /* The xBestIndex method of this virtual table requires an estimate of
149945 ** the number of rows in the virtual table to calculate the costs of
149946 ** various strategies. If possible, this estimate is loaded from the
149947 ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
149948 ** Otherwise, if no sqlite_stat1 entry is available, use
149949 ** RTREE_DEFAULT_ROWEST.
149951 #define RTREE_DEFAULT_ROWEST 1048576
149952 #define RTREE_MIN_ROWEST 100
149955 ** An rtree virtual-table object.
149957 struct Rtree {
149958 sqlite3_vtab base; /* Base class. Must be first */
149959 sqlite3 *db; /* Host database connection */
149960 int iNodeSize; /* Size in bytes of each node in the node table */
149961 u8 nDim; /* Number of dimensions */
149962 u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
149963 u8 nBytesPerCell; /* Bytes consumed per cell */
149964 int iDepth; /* Current depth of the r-tree structure */
149965 char *zDb; /* Name of database containing r-tree table */
149966 char *zName; /* Name of r-tree table */
149967 int nBusy; /* Current number of users of this structure */
149968 i64 nRowEst; /* Estimated number of rows in this table */
149970 /* List of nodes removed during a CondenseTree operation. List is
149971 ** linked together via the pointer normally used for hash chains -
149972 ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
149973 ** headed by the node (leaf nodes have RtreeNode.iNode==0).
149975 RtreeNode *pDeleted;
149976 int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
149978 /* Statements to read/write/delete a record from xxx_node */
149979 sqlite3_stmt *pReadNode;
149980 sqlite3_stmt *pWriteNode;
149981 sqlite3_stmt *pDeleteNode;
149983 /* Statements to read/write/delete a record from xxx_rowid */
149984 sqlite3_stmt *pReadRowid;
149985 sqlite3_stmt *pWriteRowid;
149986 sqlite3_stmt *pDeleteRowid;
149988 /* Statements to read/write/delete a record from xxx_parent */
149989 sqlite3_stmt *pReadParent;
149990 sqlite3_stmt *pWriteParent;
149991 sqlite3_stmt *pDeleteParent;
149993 RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
149996 /* Possible values for Rtree.eCoordType: */
149997 #define RTREE_COORD_REAL32 0
149998 #define RTREE_COORD_INT32 1
150001 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
150002 ** only deal with integer coordinates. No floating point operations
150003 ** will be done.
150005 #ifdef SQLITE_RTREE_INT_ONLY
150006 typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
150007 typedef int RtreeValue; /* Low accuracy coordinate */
150008 # define RTREE_ZERO 0
150009 #else
150010 typedef double RtreeDValue; /* High accuracy coordinate */
150011 typedef float RtreeValue; /* Low accuracy coordinate */
150012 # define RTREE_ZERO 0.0
150013 #endif
150016 ** When doing a search of an r-tree, instances of the following structure
150017 ** record intermediate results from the tree walk.
150019 ** The id is always a node-id. For iLevel>=1 the id is the node-id of
150020 ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
150021 ** the id is of the parent node and the cell that RtreeSearchPoint
150022 ** represents is the iCell-th entry in the parent node.
150024 struct RtreeSearchPoint {
150025 RtreeDValue rScore; /* The score for this node. Smallest goes first. */
150026 sqlite3_int64 id; /* Node ID */
150027 u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
150028 u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
150029 u8 iCell; /* Cell index within the node */
150033 ** The minimum number of cells allowed for a node is a third of the
150034 ** maximum. In Gutman's notation:
150036 ** m = M/3
150038 ** If an R*-tree "Reinsert" operation is required, the same number of
150039 ** cells are removed from the overfull node and reinserted into the tree.
150041 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
150042 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
150043 #define RTREE_MAXCELLS 51
150046 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
150047 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
150048 ** Therefore all non-root nodes must contain at least 3 entries. Since
150049 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
150050 ** 40 or less.
150052 #define RTREE_MAX_DEPTH 40
150056 ** Number of entries in the cursor RtreeNode cache. The first entry is
150057 ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
150058 ** entries cache the RtreeNode for the first elements of the priority queue.
150060 #define RTREE_CACHE_SZ 5
150063 ** An rtree cursor object.
150065 struct RtreeCursor {
150066 sqlite3_vtab_cursor base; /* Base class. Must be first */
150067 u8 atEOF; /* True if at end of search */
150068 u8 bPoint; /* True if sPoint is valid */
150069 int iStrategy; /* Copy of idxNum search parameter */
150070 int nConstraint; /* Number of entries in aConstraint */
150071 RtreeConstraint *aConstraint; /* Search constraints. */
150072 int nPointAlloc; /* Number of slots allocated for aPoint[] */
150073 int nPoint; /* Number of slots used in aPoint[] */
150074 int mxLevel; /* iLevel value for root of the tree */
150075 RtreeSearchPoint *aPoint; /* Priority queue for search points */
150076 RtreeSearchPoint sPoint; /* Cached next search point */
150077 RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
150078 u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
150081 /* Return the Rtree of a RtreeCursor */
150082 #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
150085 ** A coordinate can be either a floating point number or a integer. All
150086 ** coordinates within a single R-Tree are always of the same time.
150088 union RtreeCoord {
150089 RtreeValue f; /* Floating point value */
150090 int i; /* Integer value */
150091 u32 u; /* Unsigned for byte-order conversions */
150095 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
150096 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
150097 ** variable pRtree points to the Rtree structure associated with the
150098 ** RtreeCoord.
150100 #ifdef SQLITE_RTREE_INT_ONLY
150101 # define DCOORD(coord) ((RtreeDValue)coord.i)
150102 #else
150103 # define DCOORD(coord) ( \
150104 (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
150105 ((double)coord.f) : \
150106 ((double)coord.i) \
150108 #endif
150111 ** A search constraint.
150113 struct RtreeConstraint {
150114 int iCoord; /* Index of constrained coordinate */
150115 int op; /* Constraining operation */
150116 union {
150117 RtreeDValue rValue; /* Constraint value. */
150118 int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
150119 int (*xQueryFunc)(sqlite3_rtree_query_info*);
150121 sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
150124 /* Possible values for RtreeConstraint.op */
150125 #define RTREE_EQ 0x41 /* A */
150126 #define RTREE_LE 0x42 /* B */
150127 #define RTREE_LT 0x43 /* C */
150128 #define RTREE_GE 0x44 /* D */
150129 #define RTREE_GT 0x45 /* E */
150130 #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
150131 #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
150135 ** An rtree structure node.
150137 struct RtreeNode {
150138 RtreeNode *pParent; /* Parent node */
150139 i64 iNode; /* The node number */
150140 int nRef; /* Number of references to this node */
150141 int isDirty; /* True if the node needs to be written to disk */
150142 u8 *zData; /* Content of the node, as should be on disk */
150143 RtreeNode *pNext; /* Next node in this hash collision chain */
150146 /* Return the number of cells in a node */
150147 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
150150 ** A single cell from a node, deserialized
150152 struct RtreeCell {
150153 i64 iRowid; /* Node or entry ID */
150154 RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
150159 ** This object becomes the sqlite3_user_data() for the SQL functions
150160 ** that are created by sqlite3_rtree_geometry_callback() and
150161 ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
150162 ** operators in order to constrain a search.
150164 ** xGeom and xQueryFunc are the callback functions. Exactly one of
150165 ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
150166 ** SQL function was created using sqlite3_rtree_geometry_callback() or
150167 ** sqlite3_rtree_query_callback().
150169 ** This object is deleted automatically by the destructor mechanism in
150170 ** sqlite3_create_function_v2().
150172 struct RtreeGeomCallback {
150173 int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
150174 int (*xQueryFunc)(sqlite3_rtree_query_info*);
150175 void (*xDestructor)(void*);
150176 void *pContext;
150181 ** Value for the first field of every RtreeMatchArg object. The MATCH
150182 ** operator tests that the first field of a blob operand matches this
150183 ** value to avoid operating on invalid blobs (which could cause a segfault).
150185 #define RTREE_GEOMETRY_MAGIC 0x891245AB
150188 ** An instance of this structure (in the form of a BLOB) is returned by
150189 ** the SQL functions that sqlite3_rtree_geometry_callback() and
150190 ** sqlite3_rtree_query_callback() create, and is read as the right-hand
150191 ** operand to the MATCH operator of an R-Tree.
150193 struct RtreeMatchArg {
150194 u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
150195 RtreeGeomCallback cb; /* Info about the callback functions */
150196 int nParam; /* Number of parameters to the SQL function */
150197 RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
150200 #ifndef MAX
150201 # define MAX(x,y) ((x) < (y) ? (y) : (x))
150202 #endif
150203 #ifndef MIN
150204 # define MIN(x,y) ((x) > (y) ? (y) : (x))
150205 #endif
150208 ** Functions to deserialize a 16 bit integer, 32 bit real number and
150209 ** 64 bit integer. The deserialized value is returned.
150211 static int readInt16(u8 *p){
150212 return (p[0]<<8) + p[1];
150214 static void readCoord(u8 *p, RtreeCoord *pCoord){
150215 u32 i = (
150216 (((u32)p[0]) << 24) +
150217 (((u32)p[1]) << 16) +
150218 (((u32)p[2]) << 8) +
150219 (((u32)p[3]) << 0)
150221 *(u32 *)pCoord = i;
150223 static i64 readInt64(u8 *p){
150224 return (
150225 (((i64)p[0]) << 56) +
150226 (((i64)p[1]) << 48) +
150227 (((i64)p[2]) << 40) +
150228 (((i64)p[3]) << 32) +
150229 (((i64)p[4]) << 24) +
150230 (((i64)p[5]) << 16) +
150231 (((i64)p[6]) << 8) +
150232 (((i64)p[7]) << 0)
150237 ** Functions to serialize a 16 bit integer, 32 bit real number and
150238 ** 64 bit integer. The value returned is the number of bytes written
150239 ** to the argument buffer (always 2, 4 and 8 respectively).
150241 static int writeInt16(u8 *p, int i){
150242 p[0] = (i>> 8)&0xFF;
150243 p[1] = (i>> 0)&0xFF;
150244 return 2;
150246 static int writeCoord(u8 *p, RtreeCoord *pCoord){
150247 u32 i;
150248 assert( sizeof(RtreeCoord)==4 );
150249 assert( sizeof(u32)==4 );
150250 i = *(u32 *)pCoord;
150251 p[0] = (i>>24)&0xFF;
150252 p[1] = (i>>16)&0xFF;
150253 p[2] = (i>> 8)&0xFF;
150254 p[3] = (i>> 0)&0xFF;
150255 return 4;
150257 static int writeInt64(u8 *p, i64 i){
150258 p[0] = (i>>56)&0xFF;
150259 p[1] = (i>>48)&0xFF;
150260 p[2] = (i>>40)&0xFF;
150261 p[3] = (i>>32)&0xFF;
150262 p[4] = (i>>24)&0xFF;
150263 p[5] = (i>>16)&0xFF;
150264 p[6] = (i>> 8)&0xFF;
150265 p[7] = (i>> 0)&0xFF;
150266 return 8;
150270 ** Increment the reference count of node p.
150272 static void nodeReference(RtreeNode *p){
150273 if( p ){
150274 p->nRef++;
150279 ** Clear the content of node p (set all bytes to 0x00).
150281 static void nodeZero(Rtree *pRtree, RtreeNode *p){
150282 memset(&p->zData[2], 0, pRtree->iNodeSize-2);
150283 p->isDirty = 1;
150287 ** Given a node number iNode, return the corresponding key to use
150288 ** in the Rtree.aHash table.
150290 static int nodeHash(i64 iNode){
150291 return iNode % HASHSIZE;
150295 ** Search the node hash table for node iNode. If found, return a pointer
150296 ** to it. Otherwise, return 0.
150298 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
150299 RtreeNode *p;
150300 for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
150301 return p;
150305 ** Add node pNode to the node hash table.
150307 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
150308 int iHash;
150309 assert( pNode->pNext==0 );
150310 iHash = nodeHash(pNode->iNode);
150311 pNode->pNext = pRtree->aHash[iHash];
150312 pRtree->aHash[iHash] = pNode;
150316 ** Remove node pNode from the node hash table.
150318 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
150319 RtreeNode **pp;
150320 if( pNode->iNode!=0 ){
150321 pp = &pRtree->aHash[nodeHash(pNode->iNode)];
150322 for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
150323 *pp = pNode->pNext;
150324 pNode->pNext = 0;
150329 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
150330 ** indicating that node has not yet been assigned a node number. It is
150331 ** assigned a node number when nodeWrite() is called to write the
150332 ** node contents out to the database.
150334 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
150335 RtreeNode *pNode;
150336 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
150337 if( pNode ){
150338 memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
150339 pNode->zData = (u8 *)&pNode[1];
150340 pNode->nRef = 1;
150341 pNode->pParent = pParent;
150342 pNode->isDirty = 1;
150343 nodeReference(pParent);
150345 return pNode;
150349 ** Obtain a reference to an r-tree node.
150351 static int nodeAcquire(
150352 Rtree *pRtree, /* R-tree structure */
150353 i64 iNode, /* Node number to load */
150354 RtreeNode *pParent, /* Either the parent node or NULL */
150355 RtreeNode **ppNode /* OUT: Acquired node */
150357 int rc;
150358 int rc2 = SQLITE_OK;
150359 RtreeNode *pNode;
150361 /* Check if the requested node is already in the hash table. If so,
150362 ** increase its reference count and return it.
150364 if( (pNode = nodeHashLookup(pRtree, iNode)) ){
150365 assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
150366 if( pParent && !pNode->pParent ){
150367 nodeReference(pParent);
150368 pNode->pParent = pParent;
150370 pNode->nRef++;
150371 *ppNode = pNode;
150372 return SQLITE_OK;
150375 sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
150376 rc = sqlite3_step(pRtree->pReadNode);
150377 if( rc==SQLITE_ROW ){
150378 const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
150379 if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
150380 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
150381 if( !pNode ){
150382 rc2 = SQLITE_NOMEM;
150383 }else{
150384 pNode->pParent = pParent;
150385 pNode->zData = (u8 *)&pNode[1];
150386 pNode->nRef = 1;
150387 pNode->iNode = iNode;
150388 pNode->isDirty = 0;
150389 pNode->pNext = 0;
150390 memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
150391 nodeReference(pParent);
150395 rc = sqlite3_reset(pRtree->pReadNode);
150396 if( rc==SQLITE_OK ) rc = rc2;
150398 /* If the root node was just loaded, set pRtree->iDepth to the height
150399 ** of the r-tree structure. A height of zero means all data is stored on
150400 ** the root node. A height of one means the children of the root node
150401 ** are the leaves, and so on. If the depth as specified on the root node
150402 ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
150404 if( pNode && iNode==1 ){
150405 pRtree->iDepth = readInt16(pNode->zData);
150406 if( pRtree->iDepth>RTREE_MAX_DEPTH ){
150407 rc = SQLITE_CORRUPT_VTAB;
150411 /* If no error has occurred so far, check if the "number of entries"
150412 ** field on the node is too large. If so, set the return code to
150413 ** SQLITE_CORRUPT_VTAB.
150415 if( pNode && rc==SQLITE_OK ){
150416 if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
150417 rc = SQLITE_CORRUPT_VTAB;
150421 if( rc==SQLITE_OK ){
150422 if( pNode!=0 ){
150423 nodeHashInsert(pRtree, pNode);
150424 }else{
150425 rc = SQLITE_CORRUPT_VTAB;
150427 *ppNode = pNode;
150428 }else{
150429 sqlite3_free(pNode);
150430 *ppNode = 0;
150433 return rc;
150437 ** Overwrite cell iCell of node pNode with the contents of pCell.
150439 static void nodeOverwriteCell(
150440 Rtree *pRtree, /* The overall R-Tree */
150441 RtreeNode *pNode, /* The node into which the cell is to be written */
150442 RtreeCell *pCell, /* The cell to write */
150443 int iCell /* Index into pNode into which pCell is written */
150445 int ii;
150446 u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
150447 p += writeInt64(p, pCell->iRowid);
150448 for(ii=0; ii<(pRtree->nDim*2); ii++){
150449 p += writeCoord(p, &pCell->aCoord[ii]);
150451 pNode->isDirty = 1;
150455 ** Remove the cell with index iCell from node pNode.
150457 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
150458 u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
150459 u8 *pSrc = &pDst[pRtree->nBytesPerCell];
150460 int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
150461 memmove(pDst, pSrc, nByte);
150462 writeInt16(&pNode->zData[2], NCELL(pNode)-1);
150463 pNode->isDirty = 1;
150467 ** Insert the contents of cell pCell into node pNode. If the insert
150468 ** is successful, return SQLITE_OK.
150470 ** If there is not enough free space in pNode, return SQLITE_FULL.
150472 static int nodeInsertCell(
150473 Rtree *pRtree, /* The overall R-Tree */
150474 RtreeNode *pNode, /* Write new cell into this node */
150475 RtreeCell *pCell /* The cell to be inserted */
150477 int nCell; /* Current number of cells in pNode */
150478 int nMaxCell; /* Maximum number of cells for pNode */
150480 nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
150481 nCell = NCELL(pNode);
150483 assert( nCell<=nMaxCell );
150484 if( nCell<nMaxCell ){
150485 nodeOverwriteCell(pRtree, pNode, pCell, nCell);
150486 writeInt16(&pNode->zData[2], nCell+1);
150487 pNode->isDirty = 1;
150490 return (nCell==nMaxCell);
150494 ** If the node is dirty, write it out to the database.
150496 static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
150497 int rc = SQLITE_OK;
150498 if( pNode->isDirty ){
150499 sqlite3_stmt *p = pRtree->pWriteNode;
150500 if( pNode->iNode ){
150501 sqlite3_bind_int64(p, 1, pNode->iNode);
150502 }else{
150503 sqlite3_bind_null(p, 1);
150505 sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
150506 sqlite3_step(p);
150507 pNode->isDirty = 0;
150508 rc = sqlite3_reset(p);
150509 if( pNode->iNode==0 && rc==SQLITE_OK ){
150510 pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
150511 nodeHashInsert(pRtree, pNode);
150514 return rc;
150518 ** Release a reference to a node. If the node is dirty and the reference
150519 ** count drops to zero, the node data is written to the database.
150521 static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
150522 int rc = SQLITE_OK;
150523 if( pNode ){
150524 assert( pNode->nRef>0 );
150525 pNode->nRef--;
150526 if( pNode->nRef==0 ){
150527 if( pNode->iNode==1 ){
150528 pRtree->iDepth = -1;
150530 if( pNode->pParent ){
150531 rc = nodeRelease(pRtree, pNode->pParent);
150533 if( rc==SQLITE_OK ){
150534 rc = nodeWrite(pRtree, pNode);
150536 nodeHashDelete(pRtree, pNode);
150537 sqlite3_free(pNode);
150540 return rc;
150544 ** Return the 64-bit integer value associated with cell iCell of
150545 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
150546 ** an internal node, then the 64-bit integer is a child page number.
150548 static i64 nodeGetRowid(
150549 Rtree *pRtree, /* The overall R-Tree */
150550 RtreeNode *pNode, /* The node from which to extract the ID */
150551 int iCell /* The cell index from which to extract the ID */
150553 assert( iCell<NCELL(pNode) );
150554 return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
150558 ** Return coordinate iCoord from cell iCell in node pNode.
150560 static void nodeGetCoord(
150561 Rtree *pRtree, /* The overall R-Tree */
150562 RtreeNode *pNode, /* The node from which to extract a coordinate */
150563 int iCell, /* The index of the cell within the node */
150564 int iCoord, /* Which coordinate to extract */
150565 RtreeCoord *pCoord /* OUT: Space to write result to */
150567 readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
150571 ** Deserialize cell iCell of node pNode. Populate the structure pointed
150572 ** to by pCell with the results.
150574 static void nodeGetCell(
150575 Rtree *pRtree, /* The overall R-Tree */
150576 RtreeNode *pNode, /* The node containing the cell to be read */
150577 int iCell, /* Index of the cell within the node */
150578 RtreeCell *pCell /* OUT: Write the cell contents here */
150580 u8 *pData;
150581 u8 *pEnd;
150582 RtreeCoord *pCoord;
150583 pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
150584 pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
150585 pEnd = pData + pRtree->nDim*8;
150586 pCoord = pCell->aCoord;
150587 for(; pData<pEnd; pData+=4, pCoord++){
150588 readCoord(pData, pCoord);
150593 /* Forward declaration for the function that does the work of
150594 ** the virtual table module xCreate() and xConnect() methods.
150596 static int rtreeInit(
150597 sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
150601 ** Rtree virtual table module xCreate method.
150603 static int rtreeCreate(
150604 sqlite3 *db,
150605 void *pAux,
150606 int argc, const char *const*argv,
150607 sqlite3_vtab **ppVtab,
150608 char **pzErr
150610 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
150614 ** Rtree virtual table module xConnect method.
150616 static int rtreeConnect(
150617 sqlite3 *db,
150618 void *pAux,
150619 int argc, const char *const*argv,
150620 sqlite3_vtab **ppVtab,
150621 char **pzErr
150623 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
150627 ** Increment the r-tree reference count.
150629 static void rtreeReference(Rtree *pRtree){
150630 pRtree->nBusy++;
150634 ** Decrement the r-tree reference count. When the reference count reaches
150635 ** zero the structure is deleted.
150637 static void rtreeRelease(Rtree *pRtree){
150638 pRtree->nBusy--;
150639 if( pRtree->nBusy==0 ){
150640 sqlite3_finalize(pRtree->pReadNode);
150641 sqlite3_finalize(pRtree->pWriteNode);
150642 sqlite3_finalize(pRtree->pDeleteNode);
150643 sqlite3_finalize(pRtree->pReadRowid);
150644 sqlite3_finalize(pRtree->pWriteRowid);
150645 sqlite3_finalize(pRtree->pDeleteRowid);
150646 sqlite3_finalize(pRtree->pReadParent);
150647 sqlite3_finalize(pRtree->pWriteParent);
150648 sqlite3_finalize(pRtree->pDeleteParent);
150649 sqlite3_free(pRtree);
150654 ** Rtree virtual table module xDisconnect method.
150656 static int rtreeDisconnect(sqlite3_vtab *pVtab){
150657 rtreeRelease((Rtree *)pVtab);
150658 return SQLITE_OK;
150662 ** Rtree virtual table module xDestroy method.
150664 static int rtreeDestroy(sqlite3_vtab *pVtab){
150665 Rtree *pRtree = (Rtree *)pVtab;
150666 int rc;
150667 char *zCreate = sqlite3_mprintf(
150668 "DROP TABLE '%q'.'%q_node';"
150669 "DROP TABLE '%q'.'%q_rowid';"
150670 "DROP TABLE '%q'.'%q_parent';",
150671 pRtree->zDb, pRtree->zName,
150672 pRtree->zDb, pRtree->zName,
150673 pRtree->zDb, pRtree->zName
150675 if( !zCreate ){
150676 rc = SQLITE_NOMEM;
150677 }else{
150678 rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
150679 sqlite3_free(zCreate);
150681 if( rc==SQLITE_OK ){
150682 rtreeRelease(pRtree);
150685 return rc;
150689 ** Rtree virtual table module xOpen method.
150691 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
150692 int rc = SQLITE_NOMEM;
150693 RtreeCursor *pCsr;
150695 pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
150696 if( pCsr ){
150697 memset(pCsr, 0, sizeof(RtreeCursor));
150698 pCsr->base.pVtab = pVTab;
150699 rc = SQLITE_OK;
150701 *ppCursor = (sqlite3_vtab_cursor *)pCsr;
150703 return rc;
150708 ** Free the RtreeCursor.aConstraint[] array and its contents.
150710 static void freeCursorConstraints(RtreeCursor *pCsr){
150711 if( pCsr->aConstraint ){
150712 int i; /* Used to iterate through constraint array */
150713 for(i=0; i<pCsr->nConstraint; i++){
150714 sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
150715 if( pInfo ){
150716 if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
150717 sqlite3_free(pInfo);
150720 sqlite3_free(pCsr->aConstraint);
150721 pCsr->aConstraint = 0;
150726 ** Rtree virtual table module xClose method.
150728 static int rtreeClose(sqlite3_vtab_cursor *cur){
150729 Rtree *pRtree = (Rtree *)(cur->pVtab);
150730 int ii;
150731 RtreeCursor *pCsr = (RtreeCursor *)cur;
150732 freeCursorConstraints(pCsr);
150733 sqlite3_free(pCsr->aPoint);
150734 for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
150735 sqlite3_free(pCsr);
150736 return SQLITE_OK;
150740 ** Rtree virtual table module xEof method.
150742 ** Return non-zero if the cursor does not currently point to a valid
150743 ** record (i.e if the scan has finished), or zero otherwise.
150745 static int rtreeEof(sqlite3_vtab_cursor *cur){
150746 RtreeCursor *pCsr = (RtreeCursor *)cur;
150747 return pCsr->atEOF;
150751 ** Convert raw bits from the on-disk RTree record into a coordinate value.
150752 ** The on-disk format is big-endian and needs to be converted for little-
150753 ** endian platforms. The on-disk record stores integer coordinates if
150754 ** eInt is true and it stores 32-bit floating point records if eInt is
150755 ** false. a[] is the four bytes of the on-disk record to be decoded.
150756 ** Store the results in "r".
150758 ** There are three versions of this macro, one each for little-endian and
150759 ** big-endian processors and a third generic implementation. The endian-
150760 ** specific implementations are much faster and are preferred if the
150761 ** processor endianness is known at compile-time. The SQLITE_BYTEORDER
150762 ** macro is part of sqliteInt.h and hence the endian-specific
150763 ** implementation will only be used if this module is compiled as part
150764 ** of the amalgamation.
150766 #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
150767 #define RTREE_DECODE_COORD(eInt, a, r) { \
150768 RtreeCoord c; /* Coordinate decoded */ \
150769 memcpy(&c.u,a,4); \
150770 c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
150771 ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
150772 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
150774 #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
150775 #define RTREE_DECODE_COORD(eInt, a, r) { \
150776 RtreeCoord c; /* Coordinate decoded */ \
150777 memcpy(&c.u,a,4); \
150778 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
150780 #else
150781 #define RTREE_DECODE_COORD(eInt, a, r) { \
150782 RtreeCoord c; /* Coordinate decoded */ \
150783 c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
150784 +((u32)a[2]<<8) + a[3]; \
150785 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
150787 #endif
150790 ** Check the RTree node or entry given by pCellData and p against the MATCH
150791 ** constraint pConstraint.
150793 static int rtreeCallbackConstraint(
150794 RtreeConstraint *pConstraint, /* The constraint to test */
150795 int eInt, /* True if RTree holding integer coordinates */
150796 u8 *pCellData, /* Raw cell content */
150797 RtreeSearchPoint *pSearch, /* Container of this cell */
150798 sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
150799 int *peWithin /* OUT: visibility of the cell */
150801 int i; /* Loop counter */
150802 sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
150803 int nCoord = pInfo->nCoord; /* No. of coordinates */
150804 int rc; /* Callback return code */
150805 sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
150807 assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
150808 assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
150810 if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
150811 pInfo->iRowid = readInt64(pCellData);
150813 pCellData += 8;
150814 for(i=0; i<nCoord; i++, pCellData += 4){
150815 RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
150817 if( pConstraint->op==RTREE_MATCH ){
150818 rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
150819 nCoord, aCoord, &i);
150820 if( i==0 ) *peWithin = NOT_WITHIN;
150821 *prScore = RTREE_ZERO;
150822 }else{
150823 pInfo->aCoord = aCoord;
150824 pInfo->iLevel = pSearch->iLevel - 1;
150825 pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
150826 pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
150827 rc = pConstraint->u.xQueryFunc(pInfo);
150828 if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
150829 if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
150830 *prScore = pInfo->rScore;
150833 return rc;
150837 ** Check the internal RTree node given by pCellData against constraint p.
150838 ** If this constraint cannot be satisfied by any child within the node,
150839 ** set *peWithin to NOT_WITHIN.
150841 static void rtreeNonleafConstraint(
150842 RtreeConstraint *p, /* The constraint to test */
150843 int eInt, /* True if RTree holds integer coordinates */
150844 u8 *pCellData, /* Raw cell content as appears on disk */
150845 int *peWithin /* Adjust downward, as appropriate */
150847 sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
150849 /* p->iCoord might point to either a lower or upper bound coordinate
150850 ** in a coordinate pair. But make pCellData point to the lower bound.
150852 pCellData += 8 + 4*(p->iCoord&0xfe);
150854 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
150855 || p->op==RTREE_GT || p->op==RTREE_EQ );
150856 switch( p->op ){
150857 case RTREE_LE:
150858 case RTREE_LT:
150859 case RTREE_EQ:
150860 RTREE_DECODE_COORD(eInt, pCellData, val);
150861 /* val now holds the lower bound of the coordinate pair */
150862 if( p->u.rValue>=val ) return;
150863 if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
150864 /* Fall through for the RTREE_EQ case */
150866 default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
150867 pCellData += 4;
150868 RTREE_DECODE_COORD(eInt, pCellData, val);
150869 /* val now holds the upper bound of the coordinate pair */
150870 if( p->u.rValue<=val ) return;
150872 *peWithin = NOT_WITHIN;
150876 ** Check the leaf RTree cell given by pCellData against constraint p.
150877 ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
150878 ** If the constraint is satisfied, leave *peWithin unchanged.
150880 ** The constraint is of the form: xN op $val
150882 ** The op is given by p->op. The xN is p->iCoord-th coordinate in
150883 ** pCellData. $val is given by p->u.rValue.
150885 static void rtreeLeafConstraint(
150886 RtreeConstraint *p, /* The constraint to test */
150887 int eInt, /* True if RTree holds integer coordinates */
150888 u8 *pCellData, /* Raw cell content as appears on disk */
150889 int *peWithin /* Adjust downward, as appropriate */
150891 RtreeDValue xN; /* Coordinate value converted to a double */
150893 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
150894 || p->op==RTREE_GT || p->op==RTREE_EQ );
150895 pCellData += 8 + p->iCoord*4;
150896 RTREE_DECODE_COORD(eInt, pCellData, xN);
150897 switch( p->op ){
150898 case RTREE_LE: if( xN <= p->u.rValue ) return; break;
150899 case RTREE_LT: if( xN < p->u.rValue ) return; break;
150900 case RTREE_GE: if( xN >= p->u.rValue ) return; break;
150901 case RTREE_GT: if( xN > p->u.rValue ) return; break;
150902 default: if( xN == p->u.rValue ) return; break;
150904 *peWithin = NOT_WITHIN;
150908 ** One of the cells in node pNode is guaranteed to have a 64-bit
150909 ** integer value equal to iRowid. Return the index of this cell.
150911 static int nodeRowidIndex(
150912 Rtree *pRtree,
150913 RtreeNode *pNode,
150914 i64 iRowid,
150915 int *piIndex
150917 int ii;
150918 int nCell = NCELL(pNode);
150919 assert( nCell<200 );
150920 for(ii=0; ii<nCell; ii++){
150921 if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
150922 *piIndex = ii;
150923 return SQLITE_OK;
150926 return SQLITE_CORRUPT_VTAB;
150930 ** Return the index of the cell containing a pointer to node pNode
150931 ** in its parent. If pNode is the root node, return -1.
150933 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
150934 RtreeNode *pParent = pNode->pParent;
150935 if( pParent ){
150936 return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
150938 *piIndex = -1;
150939 return SQLITE_OK;
150943 ** Compare two search points. Return negative, zero, or positive if the first
150944 ** is less than, equal to, or greater than the second.
150946 ** The rScore is the primary key. Smaller rScore values come first.
150947 ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
150948 ** iLevel values coming first. In this way, if rScore is the same for all
150949 ** SearchPoints, then iLevel becomes the deciding factor and the result
150950 ** is a depth-first search, which is the desired default behavior.
150952 static int rtreeSearchPointCompare(
150953 const RtreeSearchPoint *pA,
150954 const RtreeSearchPoint *pB
150956 if( pA->rScore<pB->rScore ) return -1;
150957 if( pA->rScore>pB->rScore ) return +1;
150958 if( pA->iLevel<pB->iLevel ) return -1;
150959 if( pA->iLevel>pB->iLevel ) return +1;
150960 return 0;
150964 ** Interchange to search points in a cursor.
150966 static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
150967 RtreeSearchPoint t = p->aPoint[i];
150968 assert( i<j );
150969 p->aPoint[i] = p->aPoint[j];
150970 p->aPoint[j] = t;
150971 i++; j++;
150972 if( i<RTREE_CACHE_SZ ){
150973 if( j>=RTREE_CACHE_SZ ){
150974 nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
150975 p->aNode[i] = 0;
150976 }else{
150977 RtreeNode *pTemp = p->aNode[i];
150978 p->aNode[i] = p->aNode[j];
150979 p->aNode[j] = pTemp;
150985 ** Return the search point with the lowest current score.
150987 static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
150988 return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
150992 ** Get the RtreeNode for the search point with the lowest score.
150994 static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
150995 sqlite3_int64 id;
150996 int ii = 1 - pCur->bPoint;
150997 assert( ii==0 || ii==1 );
150998 assert( pCur->bPoint || pCur->nPoint );
150999 if( pCur->aNode[ii]==0 ){
151000 assert( pRC!=0 );
151001 id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
151002 *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
151004 return pCur->aNode[ii];
151008 ** Push a new element onto the priority queue
151010 static RtreeSearchPoint *rtreeEnqueue(
151011 RtreeCursor *pCur, /* The cursor */
151012 RtreeDValue rScore, /* Score for the new search point */
151013 u8 iLevel /* Level for the new search point */
151015 int i, j;
151016 RtreeSearchPoint *pNew;
151017 if( pCur->nPoint>=pCur->nPointAlloc ){
151018 int nNew = pCur->nPointAlloc*2 + 8;
151019 pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
151020 if( pNew==0 ) return 0;
151021 pCur->aPoint = pNew;
151022 pCur->nPointAlloc = nNew;
151024 i = pCur->nPoint++;
151025 pNew = pCur->aPoint + i;
151026 pNew->rScore = rScore;
151027 pNew->iLevel = iLevel;
151028 assert( iLevel>=0 && iLevel<=RTREE_MAX_DEPTH );
151029 while( i>0 ){
151030 RtreeSearchPoint *pParent;
151031 j = (i-1)/2;
151032 pParent = pCur->aPoint + j;
151033 if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
151034 rtreeSearchPointSwap(pCur, j, i);
151035 i = j;
151036 pNew = pParent;
151038 return pNew;
151042 ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
151043 ** NULL if malloc fails.
151045 static RtreeSearchPoint *rtreeSearchPointNew(
151046 RtreeCursor *pCur, /* The cursor */
151047 RtreeDValue rScore, /* Score for the new search point */
151048 u8 iLevel /* Level for the new search point */
151050 RtreeSearchPoint *pNew, *pFirst;
151051 pFirst = rtreeSearchPointFirst(pCur);
151052 pCur->anQueue[iLevel]++;
151053 if( pFirst==0
151054 || pFirst->rScore>rScore
151055 || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
151057 if( pCur->bPoint ){
151058 int ii;
151059 pNew = rtreeEnqueue(pCur, rScore, iLevel);
151060 if( pNew==0 ) return 0;
151061 ii = (int)(pNew - pCur->aPoint) + 1;
151062 if( ii<RTREE_CACHE_SZ ){
151063 assert( pCur->aNode[ii]==0 );
151064 pCur->aNode[ii] = pCur->aNode[0];
151065 }else{
151066 nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
151068 pCur->aNode[0] = 0;
151069 *pNew = pCur->sPoint;
151071 pCur->sPoint.rScore = rScore;
151072 pCur->sPoint.iLevel = iLevel;
151073 pCur->bPoint = 1;
151074 return &pCur->sPoint;
151075 }else{
151076 return rtreeEnqueue(pCur, rScore, iLevel);
151080 #if 0
151081 /* Tracing routines for the RtreeSearchPoint queue */
151082 static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
151083 if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
151084 printf(" %d.%05lld.%02d %g %d",
151085 p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
151087 idx++;
151088 if( idx<RTREE_CACHE_SZ ){
151089 printf(" %p\n", pCur->aNode[idx]);
151090 }else{
151091 printf("\n");
151094 static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
151095 int ii;
151096 printf("=== %9s ", zPrefix);
151097 if( pCur->bPoint ){
151098 tracePoint(&pCur->sPoint, -1, pCur);
151100 for(ii=0; ii<pCur->nPoint; ii++){
151101 if( ii>0 || pCur->bPoint ) printf(" ");
151102 tracePoint(&pCur->aPoint[ii], ii, pCur);
151105 # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
151106 #else
151107 # define RTREE_QUEUE_TRACE(A,B) /* no-op */
151108 #endif
151110 /* Remove the search point with the lowest current score.
151112 static void rtreeSearchPointPop(RtreeCursor *p){
151113 int i, j, k, n;
151114 i = 1 - p->bPoint;
151115 assert( i==0 || i==1 );
151116 if( p->aNode[i] ){
151117 nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
151118 p->aNode[i] = 0;
151120 if( p->bPoint ){
151121 p->anQueue[p->sPoint.iLevel]--;
151122 p->bPoint = 0;
151123 }else if( p->nPoint ){
151124 p->anQueue[p->aPoint[0].iLevel]--;
151125 n = --p->nPoint;
151126 p->aPoint[0] = p->aPoint[n];
151127 if( n<RTREE_CACHE_SZ-1 ){
151128 p->aNode[1] = p->aNode[n+1];
151129 p->aNode[n+1] = 0;
151131 i = 0;
151132 while( (j = i*2+1)<n ){
151133 k = j+1;
151134 if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
151135 if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
151136 rtreeSearchPointSwap(p, i, k);
151137 i = k;
151138 }else{
151139 break;
151141 }else{
151142 if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
151143 rtreeSearchPointSwap(p, i, j);
151144 i = j;
151145 }else{
151146 break;
151155 ** Continue the search on cursor pCur until the front of the queue
151156 ** contains an entry suitable for returning as a result-set row,
151157 ** or until the RtreeSearchPoint queue is empty, indicating that the
151158 ** query has completed.
151160 static int rtreeStepToLeaf(RtreeCursor *pCur){
151161 RtreeSearchPoint *p;
151162 Rtree *pRtree = RTREE_OF_CURSOR(pCur);
151163 RtreeNode *pNode;
151164 int eWithin;
151165 int rc = SQLITE_OK;
151166 int nCell;
151167 int nConstraint = pCur->nConstraint;
151168 int ii;
151169 int eInt;
151170 RtreeSearchPoint x;
151172 eInt = pRtree->eCoordType==RTREE_COORD_INT32;
151173 while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
151174 pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
151175 if( rc ) return rc;
151176 nCell = NCELL(pNode);
151177 assert( nCell<200 );
151178 while( p->iCell<nCell ){
151179 sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
151180 u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
151181 eWithin = FULLY_WITHIN;
151182 for(ii=0; ii<nConstraint; ii++){
151183 RtreeConstraint *pConstraint = pCur->aConstraint + ii;
151184 if( pConstraint->op>=RTREE_MATCH ){
151185 rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
151186 &rScore, &eWithin);
151187 if( rc ) return rc;
151188 }else if( p->iLevel==1 ){
151189 rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
151190 }else{
151191 rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
151193 if( eWithin==NOT_WITHIN ) break;
151195 p->iCell++;
151196 if( eWithin==NOT_WITHIN ) continue;
151197 x.iLevel = p->iLevel - 1;
151198 if( x.iLevel ){
151199 x.id = readInt64(pCellData);
151200 x.iCell = 0;
151201 }else{
151202 x.id = p->id;
151203 x.iCell = p->iCell - 1;
151205 if( p->iCell>=nCell ){
151206 RTREE_QUEUE_TRACE(pCur, "POP-S:");
151207 rtreeSearchPointPop(pCur);
151209 if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
151210 p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
151211 if( p==0 ) return SQLITE_NOMEM;
151212 p->eWithin = eWithin;
151213 p->id = x.id;
151214 p->iCell = x.iCell;
151215 RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
151216 break;
151218 if( p->iCell>=nCell ){
151219 RTREE_QUEUE_TRACE(pCur, "POP-Se:");
151220 rtreeSearchPointPop(pCur);
151223 pCur->atEOF = p==0;
151224 return SQLITE_OK;
151228 ** Rtree virtual table module xNext method.
151230 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
151231 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
151232 int rc = SQLITE_OK;
151234 /* Move to the next entry that matches the configured constraints. */
151235 RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
151236 rtreeSearchPointPop(pCsr);
151237 rc = rtreeStepToLeaf(pCsr);
151238 return rc;
151242 ** Rtree virtual table module xRowid method.
151244 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
151245 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
151246 RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
151247 int rc = SQLITE_OK;
151248 RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
151249 if( rc==SQLITE_OK && p ){
151250 *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
151252 return rc;
151256 ** Rtree virtual table module xColumn method.
151258 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
151259 Rtree *pRtree = (Rtree *)cur->pVtab;
151260 RtreeCursor *pCsr = (RtreeCursor *)cur;
151261 RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
151262 RtreeCoord c;
151263 int rc = SQLITE_OK;
151264 RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
151266 if( rc ) return rc;
151267 if( p==0 ) return SQLITE_OK;
151268 if( i==0 ){
151269 sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
151270 }else{
151271 if( rc ) return rc;
151272 nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
151273 #ifndef SQLITE_RTREE_INT_ONLY
151274 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
151275 sqlite3_result_double(ctx, c.f);
151276 }else
151277 #endif
151279 assert( pRtree->eCoordType==RTREE_COORD_INT32 );
151280 sqlite3_result_int(ctx, c.i);
151283 return SQLITE_OK;
151287 ** Use nodeAcquire() to obtain the leaf node containing the record with
151288 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
151289 ** return SQLITE_OK. If there is no such record in the table, set
151290 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
151291 ** to zero and return an SQLite error code.
151293 static int findLeafNode(
151294 Rtree *pRtree, /* RTree to search */
151295 i64 iRowid, /* The rowid searching for */
151296 RtreeNode **ppLeaf, /* Write the node here */
151297 sqlite3_int64 *piNode /* Write the node-id here */
151299 int rc;
151300 *ppLeaf = 0;
151301 sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
151302 if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
151303 i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
151304 if( piNode ) *piNode = iNode;
151305 rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
151306 sqlite3_reset(pRtree->pReadRowid);
151307 }else{
151308 rc = sqlite3_reset(pRtree->pReadRowid);
151310 return rc;
151314 ** This function is called to configure the RtreeConstraint object passed
151315 ** as the second argument for a MATCH constraint. The value passed as the
151316 ** first argument to this function is the right-hand operand to the MATCH
151317 ** operator.
151319 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
151320 RtreeMatchArg *pBlob; /* BLOB returned by geometry function */
151321 sqlite3_rtree_query_info *pInfo; /* Callback information */
151322 int nBlob; /* Size of the geometry function blob */
151323 int nExpected; /* Expected size of the BLOB */
151325 /* Check that value is actually a blob. */
151326 if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
151328 /* Check that the blob is roughly the right size. */
151329 nBlob = sqlite3_value_bytes(pValue);
151330 if( nBlob<(int)sizeof(RtreeMatchArg)
151331 || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
151333 return SQLITE_ERROR;
151336 pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
151337 if( !pInfo ) return SQLITE_NOMEM;
151338 memset(pInfo, 0, sizeof(*pInfo));
151339 pBlob = (RtreeMatchArg*)&pInfo[1];
151341 memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
151342 nExpected = (int)(sizeof(RtreeMatchArg) +
151343 (pBlob->nParam-1)*sizeof(RtreeDValue));
151344 if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
151345 sqlite3_free(pInfo);
151346 return SQLITE_ERROR;
151348 pInfo->pContext = pBlob->cb.pContext;
151349 pInfo->nParam = pBlob->nParam;
151350 pInfo->aParam = pBlob->aParam;
151352 if( pBlob->cb.xGeom ){
151353 pCons->u.xGeom = pBlob->cb.xGeom;
151354 }else{
151355 pCons->op = RTREE_QUERY;
151356 pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
151358 pCons->pInfo = pInfo;
151359 return SQLITE_OK;
151363 ** Rtree virtual table module xFilter method.
151365 static int rtreeFilter(
151366 sqlite3_vtab_cursor *pVtabCursor,
151367 int idxNum, const char *idxStr,
151368 int argc, sqlite3_value **argv
151370 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
151371 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
151372 RtreeNode *pRoot = 0;
151373 int ii;
151374 int rc = SQLITE_OK;
151375 int iCell = 0;
151377 rtreeReference(pRtree);
151379 /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
151380 freeCursorConstraints(pCsr);
151381 sqlite3_free(pCsr->aPoint);
151382 memset(pCsr, 0, sizeof(RtreeCursor));
151383 pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
151385 pCsr->iStrategy = idxNum;
151386 if( idxNum==1 ){
151387 /* Special case - lookup by rowid. */
151388 RtreeNode *pLeaf; /* Leaf on which the required cell resides */
151389 RtreeSearchPoint *p; /* Search point for the the leaf */
151390 i64 iRowid = sqlite3_value_int64(argv[0]);
151391 i64 iNode = 0;
151392 rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
151393 if( rc==SQLITE_OK && pLeaf!=0 ){
151394 p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
151395 assert( p!=0 ); /* Always returns pCsr->sPoint */
151396 pCsr->aNode[0] = pLeaf;
151397 p->id = iNode;
151398 p->eWithin = PARTLY_WITHIN;
151399 rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
151400 p->iCell = iCell;
151401 RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
151402 }else{
151403 pCsr->atEOF = 1;
151405 }else{
151406 /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
151407 ** with the configured constraints.
151409 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
151410 if( rc==SQLITE_OK && argc>0 ){
151411 pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
151412 pCsr->nConstraint = argc;
151413 if( !pCsr->aConstraint ){
151414 rc = SQLITE_NOMEM;
151415 }else{
151416 memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
151417 memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
151418 assert( (idxStr==0 && argc==0)
151419 || (idxStr && (int)strlen(idxStr)==argc*2) );
151420 for(ii=0; ii<argc; ii++){
151421 RtreeConstraint *p = &pCsr->aConstraint[ii];
151422 p->op = idxStr[ii*2];
151423 p->iCoord = idxStr[ii*2+1]-'0';
151424 if( p->op>=RTREE_MATCH ){
151425 /* A MATCH operator. The right-hand-side must be a blob that
151426 ** can be cast into an RtreeMatchArg object. One created using
151427 ** an sqlite3_rtree_geometry_callback() SQL user function.
151429 rc = deserializeGeometry(argv[ii], p);
151430 if( rc!=SQLITE_OK ){
151431 break;
151433 p->pInfo->nCoord = pRtree->nDim*2;
151434 p->pInfo->anQueue = pCsr->anQueue;
151435 p->pInfo->mxLevel = pRtree->iDepth + 1;
151436 }else{
151437 #ifdef SQLITE_RTREE_INT_ONLY
151438 p->u.rValue = sqlite3_value_int64(argv[ii]);
151439 #else
151440 p->u.rValue = sqlite3_value_double(argv[ii]);
151441 #endif
151446 if( rc==SQLITE_OK ){
151447 RtreeSearchPoint *pNew;
151448 pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
151449 if( pNew==0 ) return SQLITE_NOMEM;
151450 pNew->id = 1;
151451 pNew->iCell = 0;
151452 pNew->eWithin = PARTLY_WITHIN;
151453 assert( pCsr->bPoint==1 );
151454 pCsr->aNode[0] = pRoot;
151455 pRoot = 0;
151456 RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
151457 rc = rtreeStepToLeaf(pCsr);
151461 nodeRelease(pRtree, pRoot);
151462 rtreeRelease(pRtree);
151463 return rc;
151467 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
151468 ** extension is currently being used by a version of SQLite too old to
151469 ** support estimatedRows. In that case this function is a no-op.
151471 static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
151472 #if SQLITE_VERSION_NUMBER>=3008002
151473 if( sqlite3_libversion_number()>=3008002 ){
151474 pIdxInfo->estimatedRows = nRow;
151476 #endif
151480 ** Rtree virtual table module xBestIndex method. There are three
151481 ** table scan strategies to choose from (in order from most to
151482 ** least desirable):
151484 ** idxNum idxStr Strategy
151485 ** ------------------------------------------------
151486 ** 1 Unused Direct lookup by rowid.
151487 ** 2 See below R-tree query or full-table scan.
151488 ** ------------------------------------------------
151490 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
151491 ** 2 is used, idxStr is formatted to contain 2 bytes for each
151492 ** constraint used. The first two bytes of idxStr correspond to
151493 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
151494 ** (argvIndex==1) etc.
151496 ** The first of each pair of bytes in idxStr identifies the constraint
151497 ** operator as follows:
151499 ** Operator Byte Value
151500 ** ----------------------
151501 ** = 0x41 ('A')
151502 ** <= 0x42 ('B')
151503 ** < 0x43 ('C')
151504 ** >= 0x44 ('D')
151505 ** > 0x45 ('E')
151506 ** MATCH 0x46 ('F')
151507 ** ----------------------
151509 ** The second of each pair of bytes identifies the coordinate column
151510 ** to which the constraint applies. The leftmost coordinate column
151511 ** is 'a', the second from the left 'b' etc.
151513 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
151514 Rtree *pRtree = (Rtree*)tab;
151515 int rc = SQLITE_OK;
151516 int ii;
151517 i64 nRow; /* Estimated rows returned by this scan */
151519 int iIdx = 0;
151520 char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
151521 memset(zIdxStr, 0, sizeof(zIdxStr));
151523 assert( pIdxInfo->idxStr==0 );
151524 for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
151525 struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
151527 if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
151528 /* We have an equality constraint on the rowid. Use strategy 1. */
151529 int jj;
151530 for(jj=0; jj<ii; jj++){
151531 pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
151532 pIdxInfo->aConstraintUsage[jj].omit = 0;
151534 pIdxInfo->idxNum = 1;
151535 pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
151536 pIdxInfo->aConstraintUsage[jj].omit = 1;
151538 /* This strategy involves a two rowid lookups on an B-Tree structures
151539 ** and then a linear search of an R-Tree node. This should be
151540 ** considered almost as quick as a direct rowid lookup (for which
151541 ** sqlite uses an internal cost of 0.0). It is expected to return
151542 ** a single row.
151544 pIdxInfo->estimatedCost = 30.0;
151545 setEstimatedRows(pIdxInfo, 1);
151546 return SQLITE_OK;
151549 if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
151550 u8 op;
151551 switch( p->op ){
151552 case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
151553 case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
151554 case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
151555 case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
151556 case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
151557 default:
151558 assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
151559 op = RTREE_MATCH;
151560 break;
151562 zIdxStr[iIdx++] = op;
151563 zIdxStr[iIdx++] = p->iColumn - 1 + '0';
151564 pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
151565 pIdxInfo->aConstraintUsage[ii].omit = 1;
151569 pIdxInfo->idxNum = 2;
151570 pIdxInfo->needToFreeIdxStr = 1;
151571 if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
151572 return SQLITE_NOMEM;
151575 nRow = pRtree->nRowEst / (iIdx + 1);
151576 pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
151577 setEstimatedRows(pIdxInfo, nRow);
151579 return rc;
151583 ** Return the N-dimensional volumn of the cell stored in *p.
151585 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
151586 RtreeDValue area = (RtreeDValue)1;
151587 int ii;
151588 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
151589 area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
151591 return area;
151595 ** Return the margin length of cell p. The margin length is the sum
151596 ** of the objects size in each dimension.
151598 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
151599 RtreeDValue margin = (RtreeDValue)0;
151600 int ii;
151601 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
151602 margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
151604 return margin;
151608 ** Store the union of cells p1 and p2 in p1.
151610 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
151611 int ii;
151612 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
151613 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
151614 p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
151615 p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
151617 }else{
151618 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
151619 p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
151620 p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
151626 ** Return true if the area covered by p2 is a subset of the area covered
151627 ** by p1. False otherwise.
151629 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
151630 int ii;
151631 int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
151632 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
151633 RtreeCoord *a1 = &p1->aCoord[ii];
151634 RtreeCoord *a2 = &p2->aCoord[ii];
151635 if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
151636 || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
151638 return 0;
151641 return 1;
151645 ** Return the amount cell p would grow by if it were unioned with pCell.
151647 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
151648 RtreeDValue area;
151649 RtreeCell cell;
151650 memcpy(&cell, p, sizeof(RtreeCell));
151651 area = cellArea(pRtree, &cell);
151652 cellUnion(pRtree, &cell, pCell);
151653 return (cellArea(pRtree, &cell)-area);
151656 static RtreeDValue cellOverlap(
151657 Rtree *pRtree,
151658 RtreeCell *p,
151659 RtreeCell *aCell,
151660 int nCell
151662 int ii;
151663 RtreeDValue overlap = RTREE_ZERO;
151664 for(ii=0; ii<nCell; ii++){
151665 int jj;
151666 RtreeDValue o = (RtreeDValue)1;
151667 for(jj=0; jj<(pRtree->nDim*2); jj+=2){
151668 RtreeDValue x1, x2;
151669 x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
151670 x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
151671 if( x2<x1 ){
151672 o = (RtreeDValue)0;
151673 break;
151674 }else{
151675 o = o * (x2-x1);
151678 overlap += o;
151680 return overlap;
151685 ** This function implements the ChooseLeaf algorithm from Gutman[84].
151686 ** ChooseSubTree in r*tree terminology.
151688 static int ChooseLeaf(
151689 Rtree *pRtree, /* Rtree table */
151690 RtreeCell *pCell, /* Cell to insert into rtree */
151691 int iHeight, /* Height of sub-tree rooted at pCell */
151692 RtreeNode **ppLeaf /* OUT: Selected leaf page */
151694 int rc;
151695 int ii;
151696 RtreeNode *pNode;
151697 rc = nodeAcquire(pRtree, 1, 0, &pNode);
151699 for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
151700 int iCell;
151701 sqlite3_int64 iBest = 0;
151703 RtreeDValue fMinGrowth = RTREE_ZERO;
151704 RtreeDValue fMinArea = RTREE_ZERO;
151706 int nCell = NCELL(pNode);
151707 RtreeCell cell;
151708 RtreeNode *pChild;
151710 RtreeCell *aCell = 0;
151712 /* Select the child node which will be enlarged the least if pCell
151713 ** is inserted into it. Resolve ties by choosing the entry with
151714 ** the smallest area.
151716 for(iCell=0; iCell<nCell; iCell++){
151717 int bBest = 0;
151718 RtreeDValue growth;
151719 RtreeDValue area;
151720 nodeGetCell(pRtree, pNode, iCell, &cell);
151721 growth = cellGrowth(pRtree, &cell, pCell);
151722 area = cellArea(pRtree, &cell);
151723 if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
151724 bBest = 1;
151726 if( bBest ){
151727 fMinGrowth = growth;
151728 fMinArea = area;
151729 iBest = cell.iRowid;
151733 sqlite3_free(aCell);
151734 rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
151735 nodeRelease(pRtree, pNode);
151736 pNode = pChild;
151739 *ppLeaf = pNode;
151740 return rc;
151744 ** A cell with the same content as pCell has just been inserted into
151745 ** the node pNode. This function updates the bounding box cells in
151746 ** all ancestor elements.
151748 static int AdjustTree(
151749 Rtree *pRtree, /* Rtree table */
151750 RtreeNode *pNode, /* Adjust ancestry of this node. */
151751 RtreeCell *pCell /* This cell was just inserted */
151753 RtreeNode *p = pNode;
151754 while( p->pParent ){
151755 RtreeNode *pParent = p->pParent;
151756 RtreeCell cell;
151757 int iCell;
151759 if( nodeParentIndex(pRtree, p, &iCell) ){
151760 return SQLITE_CORRUPT_VTAB;
151763 nodeGetCell(pRtree, pParent, iCell, &cell);
151764 if( !cellContains(pRtree, &cell, pCell) ){
151765 cellUnion(pRtree, &cell, pCell);
151766 nodeOverwriteCell(pRtree, pParent, &cell, iCell);
151769 p = pParent;
151771 return SQLITE_OK;
151775 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
151777 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
151778 sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
151779 sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
151780 sqlite3_step(pRtree->pWriteRowid);
151781 return sqlite3_reset(pRtree->pWriteRowid);
151785 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
151787 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
151788 sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
151789 sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
151790 sqlite3_step(pRtree->pWriteParent);
151791 return sqlite3_reset(pRtree->pWriteParent);
151794 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
151798 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
151799 ** nIdx. The aIdx array contains the set of integers from 0 to
151800 ** (nIdx-1) in no particular order. This function sorts the values
151801 ** in aIdx according to the indexed values in aDistance. For
151802 ** example, assuming the inputs:
151804 ** aIdx = { 0, 1, 2, 3 }
151805 ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
151807 ** this function sets the aIdx array to contain:
151809 ** aIdx = { 0, 1, 2, 3 }
151811 ** The aSpare array is used as temporary working space by the
151812 ** sorting algorithm.
151814 static void SortByDistance(
151815 int *aIdx,
151816 int nIdx,
151817 RtreeDValue *aDistance,
151818 int *aSpare
151820 if( nIdx>1 ){
151821 int iLeft = 0;
151822 int iRight = 0;
151824 int nLeft = nIdx/2;
151825 int nRight = nIdx-nLeft;
151826 int *aLeft = aIdx;
151827 int *aRight = &aIdx[nLeft];
151829 SortByDistance(aLeft, nLeft, aDistance, aSpare);
151830 SortByDistance(aRight, nRight, aDistance, aSpare);
151832 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
151833 aLeft = aSpare;
151835 while( iLeft<nLeft || iRight<nRight ){
151836 if( iLeft==nLeft ){
151837 aIdx[iLeft+iRight] = aRight[iRight];
151838 iRight++;
151839 }else if( iRight==nRight ){
151840 aIdx[iLeft+iRight] = aLeft[iLeft];
151841 iLeft++;
151842 }else{
151843 RtreeDValue fLeft = aDistance[aLeft[iLeft]];
151844 RtreeDValue fRight = aDistance[aRight[iRight]];
151845 if( fLeft<fRight ){
151846 aIdx[iLeft+iRight] = aLeft[iLeft];
151847 iLeft++;
151848 }else{
151849 aIdx[iLeft+iRight] = aRight[iRight];
151850 iRight++;
151855 #if 0
151856 /* Check that the sort worked */
151858 int jj;
151859 for(jj=1; jj<nIdx; jj++){
151860 RtreeDValue left = aDistance[aIdx[jj-1]];
151861 RtreeDValue right = aDistance[aIdx[jj]];
151862 assert( left<=right );
151865 #endif
151870 ** Arguments aIdx, aCell and aSpare all point to arrays of size
151871 ** nIdx. The aIdx array contains the set of integers from 0 to
151872 ** (nIdx-1) in no particular order. This function sorts the values
151873 ** in aIdx according to dimension iDim of the cells in aCell. The
151874 ** minimum value of dimension iDim is considered first, the
151875 ** maximum used to break ties.
151877 ** The aSpare array is used as temporary working space by the
151878 ** sorting algorithm.
151880 static void SortByDimension(
151881 Rtree *pRtree,
151882 int *aIdx,
151883 int nIdx,
151884 int iDim,
151885 RtreeCell *aCell,
151886 int *aSpare
151888 if( nIdx>1 ){
151890 int iLeft = 0;
151891 int iRight = 0;
151893 int nLeft = nIdx/2;
151894 int nRight = nIdx-nLeft;
151895 int *aLeft = aIdx;
151896 int *aRight = &aIdx[nLeft];
151898 SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
151899 SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
151901 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
151902 aLeft = aSpare;
151903 while( iLeft<nLeft || iRight<nRight ){
151904 RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
151905 RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
151906 RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
151907 RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
151908 if( (iLeft!=nLeft) && ((iRight==nRight)
151909 || (xleft1<xright1)
151910 || (xleft1==xright1 && xleft2<xright2)
151912 aIdx[iLeft+iRight] = aLeft[iLeft];
151913 iLeft++;
151914 }else{
151915 aIdx[iLeft+iRight] = aRight[iRight];
151916 iRight++;
151920 #if 0
151921 /* Check that the sort worked */
151923 int jj;
151924 for(jj=1; jj<nIdx; jj++){
151925 RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
151926 RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
151927 RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
151928 RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
151929 assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
151932 #endif
151937 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
151939 static int splitNodeStartree(
151940 Rtree *pRtree,
151941 RtreeCell *aCell,
151942 int nCell,
151943 RtreeNode *pLeft,
151944 RtreeNode *pRight,
151945 RtreeCell *pBboxLeft,
151946 RtreeCell *pBboxRight
151948 int **aaSorted;
151949 int *aSpare;
151950 int ii;
151952 int iBestDim = 0;
151953 int iBestSplit = 0;
151954 RtreeDValue fBestMargin = RTREE_ZERO;
151956 int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
151958 aaSorted = (int **)sqlite3_malloc(nByte);
151959 if( !aaSorted ){
151960 return SQLITE_NOMEM;
151963 aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
151964 memset(aaSorted, 0, nByte);
151965 for(ii=0; ii<pRtree->nDim; ii++){
151966 int jj;
151967 aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
151968 for(jj=0; jj<nCell; jj++){
151969 aaSorted[ii][jj] = jj;
151971 SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
151974 for(ii=0; ii<pRtree->nDim; ii++){
151975 RtreeDValue margin = RTREE_ZERO;
151976 RtreeDValue fBestOverlap = RTREE_ZERO;
151977 RtreeDValue fBestArea = RTREE_ZERO;
151978 int iBestLeft = 0;
151979 int nLeft;
151982 nLeft=RTREE_MINCELLS(pRtree);
151983 nLeft<=(nCell-RTREE_MINCELLS(pRtree));
151984 nLeft++
151986 RtreeCell left;
151987 RtreeCell right;
151988 int kk;
151989 RtreeDValue overlap;
151990 RtreeDValue area;
151992 memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
151993 memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
151994 for(kk=1; kk<(nCell-1); kk++){
151995 if( kk<nLeft ){
151996 cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
151997 }else{
151998 cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
152001 margin += cellMargin(pRtree, &left);
152002 margin += cellMargin(pRtree, &right);
152003 overlap = cellOverlap(pRtree, &left, &right, 1);
152004 area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
152005 if( (nLeft==RTREE_MINCELLS(pRtree))
152006 || (overlap<fBestOverlap)
152007 || (overlap==fBestOverlap && area<fBestArea)
152009 iBestLeft = nLeft;
152010 fBestOverlap = overlap;
152011 fBestArea = area;
152015 if( ii==0 || margin<fBestMargin ){
152016 iBestDim = ii;
152017 fBestMargin = margin;
152018 iBestSplit = iBestLeft;
152022 memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
152023 memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
152024 for(ii=0; ii<nCell; ii++){
152025 RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
152026 RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
152027 RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
152028 nodeInsertCell(pRtree, pTarget, pCell);
152029 cellUnion(pRtree, pBbox, pCell);
152032 sqlite3_free(aaSorted);
152033 return SQLITE_OK;
152037 static int updateMapping(
152038 Rtree *pRtree,
152039 i64 iRowid,
152040 RtreeNode *pNode,
152041 int iHeight
152043 int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
152044 xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
152045 if( iHeight>0 ){
152046 RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
152047 if( pChild ){
152048 nodeRelease(pRtree, pChild->pParent);
152049 nodeReference(pNode);
152050 pChild->pParent = pNode;
152053 return xSetMapping(pRtree, iRowid, pNode->iNode);
152056 static int SplitNode(
152057 Rtree *pRtree,
152058 RtreeNode *pNode,
152059 RtreeCell *pCell,
152060 int iHeight
152062 int i;
152063 int newCellIsRight = 0;
152065 int rc = SQLITE_OK;
152066 int nCell = NCELL(pNode);
152067 RtreeCell *aCell;
152068 int *aiUsed;
152070 RtreeNode *pLeft = 0;
152071 RtreeNode *pRight = 0;
152073 RtreeCell leftbbox;
152074 RtreeCell rightbbox;
152076 /* Allocate an array and populate it with a copy of pCell and
152077 ** all cells from node pLeft. Then zero the original node.
152079 aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
152080 if( !aCell ){
152081 rc = SQLITE_NOMEM;
152082 goto splitnode_out;
152084 aiUsed = (int *)&aCell[nCell+1];
152085 memset(aiUsed, 0, sizeof(int)*(nCell+1));
152086 for(i=0; i<nCell; i++){
152087 nodeGetCell(pRtree, pNode, i, &aCell[i]);
152089 nodeZero(pRtree, pNode);
152090 memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
152091 nCell++;
152093 if( pNode->iNode==1 ){
152094 pRight = nodeNew(pRtree, pNode);
152095 pLeft = nodeNew(pRtree, pNode);
152096 pRtree->iDepth++;
152097 pNode->isDirty = 1;
152098 writeInt16(pNode->zData, pRtree->iDepth);
152099 }else{
152100 pLeft = pNode;
152101 pRight = nodeNew(pRtree, pLeft->pParent);
152102 nodeReference(pLeft);
152105 if( !pLeft || !pRight ){
152106 rc = SQLITE_NOMEM;
152107 goto splitnode_out;
152110 memset(pLeft->zData, 0, pRtree->iNodeSize);
152111 memset(pRight->zData, 0, pRtree->iNodeSize);
152113 rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
152114 &leftbbox, &rightbbox);
152115 if( rc!=SQLITE_OK ){
152116 goto splitnode_out;
152119 /* Ensure both child nodes have node numbers assigned to them by calling
152120 ** nodeWrite(). Node pRight always needs a node number, as it was created
152121 ** by nodeNew() above. But node pLeft sometimes already has a node number.
152122 ** In this case avoid the all to nodeWrite().
152124 if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
152125 || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
152127 goto splitnode_out;
152130 rightbbox.iRowid = pRight->iNode;
152131 leftbbox.iRowid = pLeft->iNode;
152133 if( pNode->iNode==1 ){
152134 rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
152135 if( rc!=SQLITE_OK ){
152136 goto splitnode_out;
152138 }else{
152139 RtreeNode *pParent = pLeft->pParent;
152140 int iCell;
152141 rc = nodeParentIndex(pRtree, pLeft, &iCell);
152142 if( rc==SQLITE_OK ){
152143 nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
152144 rc = AdjustTree(pRtree, pParent, &leftbbox);
152146 if( rc!=SQLITE_OK ){
152147 goto splitnode_out;
152150 if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
152151 goto splitnode_out;
152154 for(i=0; i<NCELL(pRight); i++){
152155 i64 iRowid = nodeGetRowid(pRtree, pRight, i);
152156 rc = updateMapping(pRtree, iRowid, pRight, iHeight);
152157 if( iRowid==pCell->iRowid ){
152158 newCellIsRight = 1;
152160 if( rc!=SQLITE_OK ){
152161 goto splitnode_out;
152164 if( pNode->iNode==1 ){
152165 for(i=0; i<NCELL(pLeft); i++){
152166 i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
152167 rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
152168 if( rc!=SQLITE_OK ){
152169 goto splitnode_out;
152172 }else if( newCellIsRight==0 ){
152173 rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
152176 if( rc==SQLITE_OK ){
152177 rc = nodeRelease(pRtree, pRight);
152178 pRight = 0;
152180 if( rc==SQLITE_OK ){
152181 rc = nodeRelease(pRtree, pLeft);
152182 pLeft = 0;
152185 splitnode_out:
152186 nodeRelease(pRtree, pRight);
152187 nodeRelease(pRtree, pLeft);
152188 sqlite3_free(aCell);
152189 return rc;
152193 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
152194 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
152195 ** the pLeaf->pParent chain all the way up to the root node.
152197 ** This operation is required when a row is deleted (or updated - an update
152198 ** is implemented as a delete followed by an insert). SQLite provides the
152199 ** rowid of the row to delete, which can be used to find the leaf on which
152200 ** the entry resides (argument pLeaf). Once the leaf is located, this
152201 ** function is called to determine its ancestry.
152203 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
152204 int rc = SQLITE_OK;
152205 RtreeNode *pChild = pLeaf;
152206 while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
152207 int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
152208 sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
152209 rc = sqlite3_step(pRtree->pReadParent);
152210 if( rc==SQLITE_ROW ){
152211 RtreeNode *pTest; /* Used to test for reference loops */
152212 i64 iNode; /* Node number of parent node */
152214 /* Before setting pChild->pParent, test that we are not creating a
152215 ** loop of references (as we would if, say, pChild==pParent). We don't
152216 ** want to do this as it leads to a memory leak when trying to delete
152217 ** the referenced counted node structures.
152219 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
152220 for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
152221 if( !pTest ){
152222 rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
152225 rc = sqlite3_reset(pRtree->pReadParent);
152226 if( rc==SQLITE_OK ) rc = rc2;
152227 if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
152228 pChild = pChild->pParent;
152230 return rc;
152233 static int deleteCell(Rtree *, RtreeNode *, int, int);
152235 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
152236 int rc;
152237 int rc2;
152238 RtreeNode *pParent = 0;
152239 int iCell;
152241 assert( pNode->nRef==1 );
152243 /* Remove the entry in the parent cell. */
152244 rc = nodeParentIndex(pRtree, pNode, &iCell);
152245 if( rc==SQLITE_OK ){
152246 pParent = pNode->pParent;
152247 pNode->pParent = 0;
152248 rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
152250 rc2 = nodeRelease(pRtree, pParent);
152251 if( rc==SQLITE_OK ){
152252 rc = rc2;
152254 if( rc!=SQLITE_OK ){
152255 return rc;
152258 /* Remove the xxx_node entry. */
152259 sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
152260 sqlite3_step(pRtree->pDeleteNode);
152261 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
152262 return rc;
152265 /* Remove the xxx_parent entry. */
152266 sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
152267 sqlite3_step(pRtree->pDeleteParent);
152268 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
152269 return rc;
152272 /* Remove the node from the in-memory hash table and link it into
152273 ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
152275 nodeHashDelete(pRtree, pNode);
152276 pNode->iNode = iHeight;
152277 pNode->pNext = pRtree->pDeleted;
152278 pNode->nRef++;
152279 pRtree->pDeleted = pNode;
152281 return SQLITE_OK;
152284 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
152285 RtreeNode *pParent = pNode->pParent;
152286 int rc = SQLITE_OK;
152287 if( pParent ){
152288 int ii;
152289 int nCell = NCELL(pNode);
152290 RtreeCell box; /* Bounding box for pNode */
152291 nodeGetCell(pRtree, pNode, 0, &box);
152292 for(ii=1; ii<nCell; ii++){
152293 RtreeCell cell;
152294 nodeGetCell(pRtree, pNode, ii, &cell);
152295 cellUnion(pRtree, &box, &cell);
152297 box.iRowid = pNode->iNode;
152298 rc = nodeParentIndex(pRtree, pNode, &ii);
152299 if( rc==SQLITE_OK ){
152300 nodeOverwriteCell(pRtree, pParent, &box, ii);
152301 rc = fixBoundingBox(pRtree, pParent);
152304 return rc;
152308 ** Delete the cell at index iCell of node pNode. After removing the
152309 ** cell, adjust the r-tree data structure if required.
152311 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
152312 RtreeNode *pParent;
152313 int rc;
152315 if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
152316 return rc;
152319 /* Remove the cell from the node. This call just moves bytes around
152320 ** the in-memory node image, so it cannot fail.
152322 nodeDeleteCell(pRtree, pNode, iCell);
152324 /* If the node is not the tree root and now has less than the minimum
152325 ** number of cells, remove it from the tree. Otherwise, update the
152326 ** cell in the parent node so that it tightly contains the updated
152327 ** node.
152329 pParent = pNode->pParent;
152330 assert( pParent || pNode->iNode==1 );
152331 if( pParent ){
152332 if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
152333 rc = removeNode(pRtree, pNode, iHeight);
152334 }else{
152335 rc = fixBoundingBox(pRtree, pNode);
152339 return rc;
152342 static int Reinsert(
152343 Rtree *pRtree,
152344 RtreeNode *pNode,
152345 RtreeCell *pCell,
152346 int iHeight
152348 int *aOrder;
152349 int *aSpare;
152350 RtreeCell *aCell;
152351 RtreeDValue *aDistance;
152352 int nCell;
152353 RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
152354 int iDim;
152355 int ii;
152356 int rc = SQLITE_OK;
152357 int n;
152359 memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
152361 nCell = NCELL(pNode)+1;
152362 n = (nCell+1)&(~1);
152364 /* Allocate the buffers used by this operation. The allocation is
152365 ** relinquished before this function returns.
152367 aCell = (RtreeCell *)sqlite3_malloc(n * (
152368 sizeof(RtreeCell) + /* aCell array */
152369 sizeof(int) + /* aOrder array */
152370 sizeof(int) + /* aSpare array */
152371 sizeof(RtreeDValue) /* aDistance array */
152373 if( !aCell ){
152374 return SQLITE_NOMEM;
152376 aOrder = (int *)&aCell[n];
152377 aSpare = (int *)&aOrder[n];
152378 aDistance = (RtreeDValue *)&aSpare[n];
152380 for(ii=0; ii<nCell; ii++){
152381 if( ii==(nCell-1) ){
152382 memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
152383 }else{
152384 nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
152386 aOrder[ii] = ii;
152387 for(iDim=0; iDim<pRtree->nDim; iDim++){
152388 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
152389 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
152392 for(iDim=0; iDim<pRtree->nDim; iDim++){
152393 aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
152396 for(ii=0; ii<nCell; ii++){
152397 aDistance[ii] = RTREE_ZERO;
152398 for(iDim=0; iDim<pRtree->nDim; iDim++){
152399 RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
152400 DCOORD(aCell[ii].aCoord[iDim*2]));
152401 aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
152405 SortByDistance(aOrder, nCell, aDistance, aSpare);
152406 nodeZero(pRtree, pNode);
152408 for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
152409 RtreeCell *p = &aCell[aOrder[ii]];
152410 nodeInsertCell(pRtree, pNode, p);
152411 if( p->iRowid==pCell->iRowid ){
152412 if( iHeight==0 ){
152413 rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
152414 }else{
152415 rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
152419 if( rc==SQLITE_OK ){
152420 rc = fixBoundingBox(pRtree, pNode);
152422 for(; rc==SQLITE_OK && ii<nCell; ii++){
152423 /* Find a node to store this cell in. pNode->iNode currently contains
152424 ** the height of the sub-tree headed by the cell.
152426 RtreeNode *pInsert;
152427 RtreeCell *p = &aCell[aOrder[ii]];
152428 rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
152429 if( rc==SQLITE_OK ){
152430 int rc2;
152431 rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
152432 rc2 = nodeRelease(pRtree, pInsert);
152433 if( rc==SQLITE_OK ){
152434 rc = rc2;
152439 sqlite3_free(aCell);
152440 return rc;
152444 ** Insert cell pCell into node pNode. Node pNode is the head of a
152445 ** subtree iHeight high (leaf nodes have iHeight==0).
152447 static int rtreeInsertCell(
152448 Rtree *pRtree,
152449 RtreeNode *pNode,
152450 RtreeCell *pCell,
152451 int iHeight
152453 int rc = SQLITE_OK;
152454 if( iHeight>0 ){
152455 RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
152456 if( pChild ){
152457 nodeRelease(pRtree, pChild->pParent);
152458 nodeReference(pNode);
152459 pChild->pParent = pNode;
152462 if( nodeInsertCell(pRtree, pNode, pCell) ){
152463 if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
152464 rc = SplitNode(pRtree, pNode, pCell, iHeight);
152465 }else{
152466 pRtree->iReinsertHeight = iHeight;
152467 rc = Reinsert(pRtree, pNode, pCell, iHeight);
152469 }else{
152470 rc = AdjustTree(pRtree, pNode, pCell);
152471 if( rc==SQLITE_OK ){
152472 if( iHeight==0 ){
152473 rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
152474 }else{
152475 rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
152479 return rc;
152482 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
152483 int ii;
152484 int rc = SQLITE_OK;
152485 int nCell = NCELL(pNode);
152487 for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
152488 RtreeNode *pInsert;
152489 RtreeCell cell;
152490 nodeGetCell(pRtree, pNode, ii, &cell);
152492 /* Find a node to store this cell in. pNode->iNode currently contains
152493 ** the height of the sub-tree headed by the cell.
152495 rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
152496 if( rc==SQLITE_OK ){
152497 int rc2;
152498 rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
152499 rc2 = nodeRelease(pRtree, pInsert);
152500 if( rc==SQLITE_OK ){
152501 rc = rc2;
152505 return rc;
152509 ** Select a currently unused rowid for a new r-tree record.
152511 static int newRowid(Rtree *pRtree, i64 *piRowid){
152512 int rc;
152513 sqlite3_bind_null(pRtree->pWriteRowid, 1);
152514 sqlite3_bind_null(pRtree->pWriteRowid, 2);
152515 sqlite3_step(pRtree->pWriteRowid);
152516 rc = sqlite3_reset(pRtree->pWriteRowid);
152517 *piRowid = sqlite3_last_insert_rowid(pRtree->db);
152518 return rc;
152522 ** Remove the entry with rowid=iDelete from the r-tree structure.
152524 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
152525 int rc; /* Return code */
152526 RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
152527 int iCell; /* Index of iDelete cell in pLeaf */
152528 RtreeNode *pRoot; /* Root node of rtree structure */
152531 /* Obtain a reference to the root node to initialize Rtree.iDepth */
152532 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
152534 /* Obtain a reference to the leaf node that contains the entry
152535 ** about to be deleted.
152537 if( rc==SQLITE_OK ){
152538 rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
152541 /* Delete the cell in question from the leaf node. */
152542 if( rc==SQLITE_OK ){
152543 int rc2;
152544 rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
152545 if( rc==SQLITE_OK ){
152546 rc = deleteCell(pRtree, pLeaf, iCell, 0);
152548 rc2 = nodeRelease(pRtree, pLeaf);
152549 if( rc==SQLITE_OK ){
152550 rc = rc2;
152554 /* Delete the corresponding entry in the <rtree>_rowid table. */
152555 if( rc==SQLITE_OK ){
152556 sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
152557 sqlite3_step(pRtree->pDeleteRowid);
152558 rc = sqlite3_reset(pRtree->pDeleteRowid);
152561 /* Check if the root node now has exactly one child. If so, remove
152562 ** it, schedule the contents of the child for reinsertion and
152563 ** reduce the tree height by one.
152565 ** This is equivalent to copying the contents of the child into
152566 ** the root node (the operation that Gutman's paper says to perform
152567 ** in this scenario).
152569 if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
152570 int rc2;
152571 RtreeNode *pChild;
152572 i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
152573 rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
152574 if( rc==SQLITE_OK ){
152575 rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
152577 rc2 = nodeRelease(pRtree, pChild);
152578 if( rc==SQLITE_OK ) rc = rc2;
152579 if( rc==SQLITE_OK ){
152580 pRtree->iDepth--;
152581 writeInt16(pRoot->zData, pRtree->iDepth);
152582 pRoot->isDirty = 1;
152586 /* Re-insert the contents of any underfull nodes removed from the tree. */
152587 for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
152588 if( rc==SQLITE_OK ){
152589 rc = reinsertNodeContent(pRtree, pLeaf);
152591 pRtree->pDeleted = pLeaf->pNext;
152592 sqlite3_free(pLeaf);
152595 /* Release the reference to the root node. */
152596 if( rc==SQLITE_OK ){
152597 rc = nodeRelease(pRtree, pRoot);
152598 }else{
152599 nodeRelease(pRtree, pRoot);
152602 return rc;
152606 ** Rounding constants for float->double conversion.
152608 #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
152609 #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
152611 #if !defined(SQLITE_RTREE_INT_ONLY)
152613 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
152614 ** while taking care to round toward negative or positive, respectively.
152616 static RtreeValue rtreeValueDown(sqlite3_value *v){
152617 double d = sqlite3_value_double(v);
152618 float f = (float)d;
152619 if( f>d ){
152620 f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
152622 return f;
152624 static RtreeValue rtreeValueUp(sqlite3_value *v){
152625 double d = sqlite3_value_double(v);
152626 float f = (float)d;
152627 if( f<d ){
152628 f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
152630 return f;
152632 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
152636 ** The xUpdate method for rtree module virtual tables.
152638 static int rtreeUpdate(
152639 sqlite3_vtab *pVtab,
152640 int nData,
152641 sqlite3_value **azData,
152642 sqlite_int64 *pRowid
152644 Rtree *pRtree = (Rtree *)pVtab;
152645 int rc = SQLITE_OK;
152646 RtreeCell cell; /* New cell to insert if nData>1 */
152647 int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
152649 rtreeReference(pRtree);
152650 assert(nData>=1);
152652 /* Constraint handling. A write operation on an r-tree table may return
152653 ** SQLITE_CONSTRAINT for two reasons:
152655 ** 1. A duplicate rowid value, or
152656 ** 2. The supplied data violates the "x2>=x1" constraint.
152658 ** In the first case, if the conflict-handling mode is REPLACE, then
152659 ** the conflicting row can be removed before proceeding. In the second
152660 ** case, SQLITE_CONSTRAINT must be returned regardless of the
152661 ** conflict-handling mode specified by the user.
152663 if( nData>1 ){
152664 int ii;
152666 /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
152667 assert( nData==(pRtree->nDim*2 + 3) );
152668 #ifndef SQLITE_RTREE_INT_ONLY
152669 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
152670 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
152671 cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
152672 cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
152673 if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
152674 rc = SQLITE_CONSTRAINT;
152675 goto constraint;
152678 }else
152679 #endif
152681 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
152682 cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
152683 cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
152684 if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
152685 rc = SQLITE_CONSTRAINT;
152686 goto constraint;
152691 /* If a rowid value was supplied, check if it is already present in
152692 ** the table. If so, the constraint has failed. */
152693 if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
152694 cell.iRowid = sqlite3_value_int64(azData[2]);
152695 if( sqlite3_value_type(azData[0])==SQLITE_NULL
152696 || sqlite3_value_int64(azData[0])!=cell.iRowid
152698 int steprc;
152699 sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
152700 steprc = sqlite3_step(pRtree->pReadRowid);
152701 rc = sqlite3_reset(pRtree->pReadRowid);
152702 if( SQLITE_ROW==steprc ){
152703 if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
152704 rc = rtreeDeleteRowid(pRtree, cell.iRowid);
152705 }else{
152706 rc = SQLITE_CONSTRAINT;
152707 goto constraint;
152711 bHaveRowid = 1;
152715 /* If azData[0] is not an SQL NULL value, it is the rowid of a
152716 ** record to delete from the r-tree table. The following block does
152717 ** just that.
152719 if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
152720 rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
152723 /* If the azData[] array contains more than one element, elements
152724 ** (azData[2]..azData[argc-1]) contain a new record to insert into
152725 ** the r-tree structure.
152727 if( rc==SQLITE_OK && nData>1 ){
152728 /* Insert the new record into the r-tree */
152729 RtreeNode *pLeaf = 0;
152731 /* Figure out the rowid of the new row. */
152732 if( bHaveRowid==0 ){
152733 rc = newRowid(pRtree, &cell.iRowid);
152735 *pRowid = cell.iRowid;
152737 if( rc==SQLITE_OK ){
152738 rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
152740 if( rc==SQLITE_OK ){
152741 int rc2;
152742 pRtree->iReinsertHeight = -1;
152743 rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
152744 rc2 = nodeRelease(pRtree, pLeaf);
152745 if( rc==SQLITE_OK ){
152746 rc = rc2;
152751 constraint:
152752 rtreeRelease(pRtree);
152753 return rc;
152757 ** The xRename method for rtree module virtual tables.
152759 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
152760 Rtree *pRtree = (Rtree *)pVtab;
152761 int rc = SQLITE_NOMEM;
152762 char *zSql = sqlite3_mprintf(
152763 "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
152764 "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
152765 "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
152766 , pRtree->zDb, pRtree->zName, zNewName
152767 , pRtree->zDb, pRtree->zName, zNewName
152768 , pRtree->zDb, pRtree->zName, zNewName
152770 if( zSql ){
152771 rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
152772 sqlite3_free(zSql);
152774 return rc;
152778 ** This function populates the pRtree->nRowEst variable with an estimate
152779 ** of the number of rows in the virtual table. If possible, this is based
152780 ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
152782 static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
152783 const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
152784 char *zSql;
152785 sqlite3_stmt *p;
152786 int rc;
152787 i64 nRow = 0;
152789 zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
152790 if( zSql==0 ){
152791 rc = SQLITE_NOMEM;
152792 }else{
152793 rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
152794 if( rc==SQLITE_OK ){
152795 if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
152796 rc = sqlite3_finalize(p);
152797 }else if( rc!=SQLITE_NOMEM ){
152798 rc = SQLITE_OK;
152801 if( rc==SQLITE_OK ){
152802 if( nRow==0 ){
152803 pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
152804 }else{
152805 pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
152808 sqlite3_free(zSql);
152811 return rc;
152814 static sqlite3_module rtreeModule = {
152815 0, /* iVersion */
152816 rtreeCreate, /* xCreate - create a table */
152817 rtreeConnect, /* xConnect - connect to an existing table */
152818 rtreeBestIndex, /* xBestIndex - Determine search strategy */
152819 rtreeDisconnect, /* xDisconnect - Disconnect from a table */
152820 rtreeDestroy, /* xDestroy - Drop a table */
152821 rtreeOpen, /* xOpen - open a cursor */
152822 rtreeClose, /* xClose - close a cursor */
152823 rtreeFilter, /* xFilter - configure scan constraints */
152824 rtreeNext, /* xNext - advance a cursor */
152825 rtreeEof, /* xEof */
152826 rtreeColumn, /* xColumn - read data */
152827 rtreeRowid, /* xRowid - read data */
152828 rtreeUpdate, /* xUpdate - write data */
152829 0, /* xBegin - begin transaction */
152830 0, /* xSync - sync transaction */
152831 0, /* xCommit - commit transaction */
152832 0, /* xRollback - rollback transaction */
152833 0, /* xFindFunction - function overloading */
152834 rtreeRename, /* xRename - rename the table */
152835 0, /* xSavepoint */
152836 0, /* xRelease */
152837 0 /* xRollbackTo */
152840 static int rtreeSqlInit(
152841 Rtree *pRtree,
152842 sqlite3 *db,
152843 const char *zDb,
152844 const char *zPrefix,
152845 int isCreate
152847 int rc = SQLITE_OK;
152849 #define N_STATEMENT 9
152850 static const char *azSql[N_STATEMENT] = {
152851 /* Read and write the xxx_node table */
152852 "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
152853 "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
152854 "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
152856 /* Read and write the xxx_rowid table */
152857 "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
152858 "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
152859 "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
152861 /* Read and write the xxx_parent table */
152862 "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
152863 "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
152864 "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
152866 sqlite3_stmt **appStmt[N_STATEMENT];
152867 int i;
152869 pRtree->db = db;
152871 if( isCreate ){
152872 char *zCreate = sqlite3_mprintf(
152873 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
152874 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
152875 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
152876 " parentnode INTEGER);"
152877 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
152878 zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
152880 if( !zCreate ){
152881 return SQLITE_NOMEM;
152883 rc = sqlite3_exec(db, zCreate, 0, 0, 0);
152884 sqlite3_free(zCreate);
152885 if( rc!=SQLITE_OK ){
152886 return rc;
152890 appStmt[0] = &pRtree->pReadNode;
152891 appStmt[1] = &pRtree->pWriteNode;
152892 appStmt[2] = &pRtree->pDeleteNode;
152893 appStmt[3] = &pRtree->pReadRowid;
152894 appStmt[4] = &pRtree->pWriteRowid;
152895 appStmt[5] = &pRtree->pDeleteRowid;
152896 appStmt[6] = &pRtree->pReadParent;
152897 appStmt[7] = &pRtree->pWriteParent;
152898 appStmt[8] = &pRtree->pDeleteParent;
152900 rc = rtreeQueryStat1(db, pRtree);
152901 for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
152902 char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
152903 if( zSql ){
152904 rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
152905 }else{
152906 rc = SQLITE_NOMEM;
152908 sqlite3_free(zSql);
152911 return rc;
152915 ** The second argument to this function contains the text of an SQL statement
152916 ** that returns a single integer value. The statement is compiled and executed
152917 ** using database connection db. If successful, the integer value returned
152918 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
152919 ** code is returned and the value of *piVal after returning is not defined.
152921 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
152922 int rc = SQLITE_NOMEM;
152923 if( zSql ){
152924 sqlite3_stmt *pStmt = 0;
152925 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
152926 if( rc==SQLITE_OK ){
152927 if( SQLITE_ROW==sqlite3_step(pStmt) ){
152928 *piVal = sqlite3_column_int(pStmt, 0);
152930 rc = sqlite3_finalize(pStmt);
152933 return rc;
152937 ** This function is called from within the xConnect() or xCreate() method to
152938 ** determine the node-size used by the rtree table being created or connected
152939 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
152940 ** Otherwise, an SQLite error code is returned.
152942 ** If this function is being called as part of an xConnect(), then the rtree
152943 ** table already exists. In this case the node-size is determined by inspecting
152944 ** the root node of the tree.
152946 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
152947 ** This ensures that each node is stored on a single database page. If the
152948 ** database page-size is so large that more than RTREE_MAXCELLS entries
152949 ** would fit in a single node, use a smaller node-size.
152951 static int getNodeSize(
152952 sqlite3 *db, /* Database handle */
152953 Rtree *pRtree, /* Rtree handle */
152954 int isCreate, /* True for xCreate, false for xConnect */
152955 char **pzErr /* OUT: Error message, if any */
152957 int rc;
152958 char *zSql;
152959 if( isCreate ){
152960 int iPageSize = 0;
152961 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
152962 rc = getIntFromStmt(db, zSql, &iPageSize);
152963 if( rc==SQLITE_OK ){
152964 pRtree->iNodeSize = iPageSize-64;
152965 if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
152966 pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
152968 }else{
152969 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
152971 }else{
152972 zSql = sqlite3_mprintf(
152973 "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
152974 pRtree->zDb, pRtree->zName
152976 rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
152977 if( rc!=SQLITE_OK ){
152978 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
152982 sqlite3_free(zSql);
152983 return rc;
152987 ** This function is the implementation of both the xConnect and xCreate
152988 ** methods of the r-tree virtual table.
152990 ** argv[0] -> module name
152991 ** argv[1] -> database name
152992 ** argv[2] -> table name
152993 ** argv[...] -> column names...
152995 static int rtreeInit(
152996 sqlite3 *db, /* Database connection */
152997 void *pAux, /* One of the RTREE_COORD_* constants */
152998 int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
152999 sqlite3_vtab **ppVtab, /* OUT: New virtual table */
153000 char **pzErr, /* OUT: Error message, if any */
153001 int isCreate /* True for xCreate, false for xConnect */
153003 int rc = SQLITE_OK;
153004 Rtree *pRtree;
153005 int nDb; /* Length of string argv[1] */
153006 int nName; /* Length of string argv[2] */
153007 int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
153009 const char *aErrMsg[] = {
153010 0, /* 0 */
153011 "Wrong number of columns for an rtree table", /* 1 */
153012 "Too few columns for an rtree table", /* 2 */
153013 "Too many columns for an rtree table" /* 3 */
153016 int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
153017 if( aErrMsg[iErr] ){
153018 *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
153019 return SQLITE_ERROR;
153022 sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
153024 /* Allocate the sqlite3_vtab structure */
153025 nDb = (int)strlen(argv[1]);
153026 nName = (int)strlen(argv[2]);
153027 pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
153028 if( !pRtree ){
153029 return SQLITE_NOMEM;
153031 memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
153032 pRtree->nBusy = 1;
153033 pRtree->base.pModule = &rtreeModule;
153034 pRtree->zDb = (char *)&pRtree[1];
153035 pRtree->zName = &pRtree->zDb[nDb+1];
153036 pRtree->nDim = (argc-4)/2;
153037 pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
153038 pRtree->eCoordType = eCoordType;
153039 memcpy(pRtree->zDb, argv[1], nDb);
153040 memcpy(pRtree->zName, argv[2], nName);
153042 /* Figure out the node size to use. */
153043 rc = getNodeSize(db, pRtree, isCreate, pzErr);
153045 /* Create/Connect to the underlying relational database schema. If
153046 ** that is successful, call sqlite3_declare_vtab() to configure
153047 ** the r-tree table schema.
153049 if( rc==SQLITE_OK ){
153050 if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
153051 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
153052 }else{
153053 char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
153054 char *zTmp;
153055 int ii;
153056 for(ii=4; zSql && ii<argc; ii++){
153057 zTmp = zSql;
153058 zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
153059 sqlite3_free(zTmp);
153061 if( zSql ){
153062 zTmp = zSql;
153063 zSql = sqlite3_mprintf("%s);", zTmp);
153064 sqlite3_free(zTmp);
153066 if( !zSql ){
153067 rc = SQLITE_NOMEM;
153068 }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
153069 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
153071 sqlite3_free(zSql);
153075 if( rc==SQLITE_OK ){
153076 *ppVtab = (sqlite3_vtab *)pRtree;
153077 }else{
153078 assert( *ppVtab==0 );
153079 assert( pRtree->nBusy==1 );
153080 rtreeRelease(pRtree);
153082 return rc;
153087 ** Implementation of a scalar function that decodes r-tree nodes to
153088 ** human readable strings. This can be used for debugging and analysis.
153090 ** The scalar function takes two arguments: (1) the number of dimensions
153091 ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
153092 ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
153093 ** deserialize all nodes, a statement like:
153095 ** SELECT rtreenode(2, data) FROM rt_node;
153097 ** The human readable string takes the form of a Tcl list with one
153098 ** entry for each cell in the r-tree node. Each entry is itself a
153099 ** list, containing the 8-byte rowid/pageno followed by the
153100 ** <num-dimension>*2 coordinates.
153102 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
153103 char *zText = 0;
153104 RtreeNode node;
153105 Rtree tree;
153106 int ii;
153108 UNUSED_PARAMETER(nArg);
153109 memset(&node, 0, sizeof(RtreeNode));
153110 memset(&tree, 0, sizeof(Rtree));
153111 tree.nDim = sqlite3_value_int(apArg[0]);
153112 tree.nBytesPerCell = 8 + 8 * tree.nDim;
153113 node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
153115 for(ii=0; ii<NCELL(&node); ii++){
153116 char zCell[512];
153117 int nCell = 0;
153118 RtreeCell cell;
153119 int jj;
153121 nodeGetCell(&tree, &node, ii, &cell);
153122 sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
153123 nCell = (int)strlen(zCell);
153124 for(jj=0; jj<tree.nDim*2; jj++){
153125 #ifndef SQLITE_RTREE_INT_ONLY
153126 sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
153127 (double)cell.aCoord[jj].f);
153128 #else
153129 sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
153130 cell.aCoord[jj].i);
153131 #endif
153132 nCell = (int)strlen(zCell);
153135 if( zText ){
153136 char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
153137 sqlite3_free(zText);
153138 zText = zTextNew;
153139 }else{
153140 zText = sqlite3_mprintf("{%s}", zCell);
153144 sqlite3_result_text(ctx, zText, -1, sqlite3_free);
153147 /* This routine implements an SQL function that returns the "depth" parameter
153148 ** from the front of a blob that is an r-tree node. For example:
153150 ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
153152 ** The depth value is 0 for all nodes other than the root node, and the root
153153 ** node always has nodeno=1, so the example above is the primary use for this
153154 ** routine. This routine is intended for testing and analysis only.
153156 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
153157 UNUSED_PARAMETER(nArg);
153158 if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
153159 || sqlite3_value_bytes(apArg[0])<2
153161 sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
153162 }else{
153163 u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
153164 sqlite3_result_int(ctx, readInt16(zBlob));
153169 ** Register the r-tree module with database handle db. This creates the
153170 ** virtual table module "rtree" and the debugging/analysis scalar
153171 ** function "rtreenode".
153173 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
153174 const int utf8 = SQLITE_UTF8;
153175 int rc;
153177 rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
153178 if( rc==SQLITE_OK ){
153179 rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
153181 if( rc==SQLITE_OK ){
153182 #ifdef SQLITE_RTREE_INT_ONLY
153183 void *c = (void *)RTREE_COORD_INT32;
153184 #else
153185 void *c = (void *)RTREE_COORD_REAL32;
153186 #endif
153187 rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
153189 if( rc==SQLITE_OK ){
153190 void *c = (void *)RTREE_COORD_INT32;
153191 rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
153194 return rc;
153198 ** This routine deletes the RtreeGeomCallback object that was attached
153199 ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
153200 ** or sqlite3_rtree_query_callback(). In other words, this routine is the
153201 ** destructor for an RtreeGeomCallback objecct. This routine is called when
153202 ** the corresponding SQL function is deleted.
153204 static void rtreeFreeCallback(void *p){
153205 RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
153206 if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
153207 sqlite3_free(p);
153211 ** Each call to sqlite3_rtree_geometry_callback() or
153212 ** sqlite3_rtree_query_callback() creates an ordinary SQLite
153213 ** scalar function that is implemented by this routine.
153215 ** All this function does is construct an RtreeMatchArg object that
153216 ** contains the geometry-checking callback routines and a list of
153217 ** parameters to this function, then return that RtreeMatchArg object
153218 ** as a BLOB.
153220 ** The R-Tree MATCH operator will read the returned BLOB, deserialize
153221 ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
153222 ** out which elements of the R-Tree should be returned by the query.
153224 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
153225 RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
153226 RtreeMatchArg *pBlob;
153227 int nBlob;
153229 nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
153230 pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
153231 if( !pBlob ){
153232 sqlite3_result_error_nomem(ctx);
153233 }else{
153234 int i;
153235 pBlob->magic = RTREE_GEOMETRY_MAGIC;
153236 pBlob->cb = pGeomCtx[0];
153237 pBlob->nParam = nArg;
153238 for(i=0; i<nArg; i++){
153239 #ifdef SQLITE_RTREE_INT_ONLY
153240 pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
153241 #else
153242 pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
153243 #endif
153245 sqlite3_result_blob(ctx, pBlob, nBlob, sqlite3_free);
153250 ** Register a new geometry function for use with the r-tree MATCH operator.
153252 SQLITE_API int sqlite3_rtree_geometry_callback(
153253 sqlite3 *db, /* Register SQL function on this connection */
153254 const char *zGeom, /* Name of the new SQL function */
153255 int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
153256 void *pContext /* Extra data associated with the callback */
153258 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
153260 /* Allocate and populate the context object. */
153261 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
153262 if( !pGeomCtx ) return SQLITE_NOMEM;
153263 pGeomCtx->xGeom = xGeom;
153264 pGeomCtx->xQueryFunc = 0;
153265 pGeomCtx->xDestructor = 0;
153266 pGeomCtx->pContext = pContext;
153267 return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
153268 (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
153273 ** Register a new 2nd-generation geometry function for use with the
153274 ** r-tree MATCH operator.
153276 SQLITE_API int sqlite3_rtree_query_callback(
153277 sqlite3 *db, /* Register SQL function on this connection */
153278 const char *zQueryFunc, /* Name of new SQL function */
153279 int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
153280 void *pContext, /* Extra data passed into the callback */
153281 void (*xDestructor)(void*) /* Destructor for the extra data */
153283 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
153285 /* Allocate and populate the context object. */
153286 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
153287 if( !pGeomCtx ) return SQLITE_NOMEM;
153288 pGeomCtx->xGeom = 0;
153289 pGeomCtx->xQueryFunc = xQueryFunc;
153290 pGeomCtx->xDestructor = xDestructor;
153291 pGeomCtx->pContext = pContext;
153292 return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
153293 (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
153297 #if !SQLITE_CORE
153298 #ifdef _WIN32
153299 __declspec(dllexport)
153300 #endif
153301 SQLITE_API int sqlite3_rtree_init(
153302 sqlite3 *db,
153303 char **pzErrMsg,
153304 const sqlite3_api_routines *pApi
153306 SQLITE_EXTENSION_INIT2(pApi)
153307 return sqlite3RtreeInit(db);
153309 #endif
153311 #endif
153313 /************** End of rtree.c ***********************************************/
153314 /************** Begin file icu.c *********************************************/
153316 ** 2007 May 6
153318 ** The author disclaims copyright to this source code. In place of
153319 ** a legal notice, here is a blessing:
153321 ** May you do good and not evil.
153322 ** May you find forgiveness for yourself and forgive others.
153323 ** May you share freely, never taking more than you give.
153325 *************************************************************************
153326 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
153328 ** This file implements an integration between the ICU library
153329 ** ("International Components for Unicode", an open-source library
153330 ** for handling unicode data) and SQLite. The integration uses
153331 ** ICU to provide the following to SQLite:
153333 ** * An implementation of the SQL regexp() function (and hence REGEXP
153334 ** operator) using the ICU uregex_XX() APIs.
153336 ** * Implementations of the SQL scalar upper() and lower() functions
153337 ** for case mapping.
153339 ** * Integration of ICU and SQLite collation sequences.
153341 ** * An implementation of the LIKE operator that uses ICU to
153342 ** provide case-independent matching.
153345 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
153347 /* Include ICU headers */
153348 #include <unicode/utypes.h>
153349 #include <unicode/uregex.h>
153350 #include <unicode/ustring.h>
153351 #include <unicode/ucol.h>
153353 /* #include <assert.h> */
153355 #ifndef SQLITE_CORE
153356 SQLITE_EXTENSION_INIT1
153357 #else
153358 #endif
153361 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
153362 ** operator.
153364 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
153365 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
153366 #endif
153369 ** Version of sqlite3_free() that is always a function, never a macro.
153371 static void xFree(void *p){
153372 sqlite3_free(p);
153376 ** Compare two UTF-8 strings for equality where the first string is
153377 ** a "LIKE" expression. Return true (1) if they are the same and
153378 ** false (0) if they are different.
153380 static int icuLikeCompare(
153381 const uint8_t *zPattern, /* LIKE pattern */
153382 const uint8_t *zString, /* The UTF-8 string to compare against */
153383 const UChar32 uEsc /* The escape character */
153385 static const int MATCH_ONE = (UChar32)'_';
153386 static const int MATCH_ALL = (UChar32)'%';
153388 int iPattern = 0; /* Current byte index in zPattern */
153389 int iString = 0; /* Current byte index in zString */
153391 int prevEscape = 0; /* True if the previous character was uEsc */
153393 while( zPattern[iPattern]!=0 ){
153395 /* Read (and consume) the next character from the input pattern. */
153396 UChar32 uPattern;
153397 U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
153398 assert(uPattern!=0);
153400 /* There are now 4 possibilities:
153402 ** 1. uPattern is an unescaped match-all character "%",
153403 ** 2. uPattern is an unescaped match-one character "_",
153404 ** 3. uPattern is an unescaped escape character, or
153405 ** 4. uPattern is to be handled as an ordinary character
153407 if( !prevEscape && uPattern==MATCH_ALL ){
153408 /* Case 1. */
153409 uint8_t c;
153411 /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
153412 ** MATCH_ALL. For each MATCH_ONE, skip one character in the
153413 ** test string.
153415 while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
153416 if( c==MATCH_ONE ){
153417 if( zString[iString]==0 ) return 0;
153418 U8_FWD_1_UNSAFE(zString, iString);
153420 iPattern++;
153423 if( zPattern[iPattern]==0 ) return 1;
153425 while( zString[iString] ){
153426 if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
153427 return 1;
153429 U8_FWD_1_UNSAFE(zString, iString);
153431 return 0;
153433 }else if( !prevEscape && uPattern==MATCH_ONE ){
153434 /* Case 2. */
153435 if( zString[iString]==0 ) return 0;
153436 U8_FWD_1_UNSAFE(zString, iString);
153438 }else if( !prevEscape && uPattern==uEsc){
153439 /* Case 3. */
153440 prevEscape = 1;
153442 }else{
153443 /* Case 4. */
153444 UChar32 uString;
153445 U8_NEXT_UNSAFE(zString, iString, uString);
153446 uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
153447 uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
153448 if( uString!=uPattern ){
153449 return 0;
153451 prevEscape = 0;
153455 return zString[iString]==0;
153459 ** Implementation of the like() SQL function. This function implements
153460 ** the build-in LIKE operator. The first argument to the function is the
153461 ** pattern and the second argument is the string. So, the SQL statements:
153463 ** A LIKE B
153465 ** is implemented as like(B, A). If there is an escape character E,
153467 ** A LIKE B ESCAPE E
153469 ** is mapped to like(B, A, E).
153471 static void icuLikeFunc(
153472 sqlite3_context *context,
153473 int argc,
153474 sqlite3_value **argv
153476 const unsigned char *zA = sqlite3_value_text(argv[0]);
153477 const unsigned char *zB = sqlite3_value_text(argv[1]);
153478 UChar32 uEsc = 0;
153480 /* Limit the length of the LIKE or GLOB pattern to avoid problems
153481 ** of deep recursion and N*N behavior in patternCompare().
153483 if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
153484 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
153485 return;
153489 if( argc==3 ){
153490 /* The escape character string must consist of a single UTF-8 character.
153491 ** Otherwise, return an error.
153493 int nE= sqlite3_value_bytes(argv[2]);
153494 const unsigned char *zE = sqlite3_value_text(argv[2]);
153495 int i = 0;
153496 if( zE==0 ) return;
153497 U8_NEXT(zE, i, nE, uEsc);
153498 if( i!=nE){
153499 sqlite3_result_error(context,
153500 "ESCAPE expression must be a single character", -1);
153501 return;
153505 if( zA && zB ){
153506 sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
153511 ** This function is called when an ICU function called from within
153512 ** the implementation of an SQL scalar function returns an error.
153514 ** The scalar function context passed as the first argument is
153515 ** loaded with an error message based on the following two args.
153517 static void icuFunctionError(
153518 sqlite3_context *pCtx, /* SQLite scalar function context */
153519 const char *zName, /* Name of ICU function that failed */
153520 UErrorCode e /* Error code returned by ICU function */
153522 char zBuf[128];
153523 sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
153524 zBuf[127] = '\0';
153525 sqlite3_result_error(pCtx, zBuf, -1);
153529 ** Function to delete compiled regexp objects. Registered as
153530 ** a destructor function with sqlite3_set_auxdata().
153532 static void icuRegexpDelete(void *p){
153533 URegularExpression *pExpr = (URegularExpression *)p;
153534 uregex_close(pExpr);
153538 ** Implementation of SQLite REGEXP operator. This scalar function takes
153539 ** two arguments. The first is a regular expression pattern to compile
153540 ** the second is a string to match against that pattern. If either
153541 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
153542 ** is 1 if the string matches the pattern, or 0 otherwise.
153544 ** SQLite maps the regexp() function to the regexp() operator such
153545 ** that the following two are equivalent:
153547 ** zString REGEXP zPattern
153548 ** regexp(zPattern, zString)
153550 ** Uses the following ICU regexp APIs:
153552 ** uregex_open()
153553 ** uregex_matches()
153554 ** uregex_close()
153556 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
153557 UErrorCode status = U_ZERO_ERROR;
153558 URegularExpression *pExpr;
153559 UBool res;
153560 const UChar *zString = sqlite3_value_text16(apArg[1]);
153562 (void)nArg; /* Unused parameter */
153564 /* If the left hand side of the regexp operator is NULL,
153565 ** then the result is also NULL.
153567 if( !zString ){
153568 return;
153571 pExpr = sqlite3_get_auxdata(p, 0);
153572 if( !pExpr ){
153573 const UChar *zPattern = sqlite3_value_text16(apArg[0]);
153574 if( !zPattern ){
153575 return;
153577 pExpr = uregex_open(zPattern, -1, 0, 0, &status);
153579 if( U_SUCCESS(status) ){
153580 sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
153581 }else{
153582 assert(!pExpr);
153583 icuFunctionError(p, "uregex_open", status);
153584 return;
153588 /* Configure the text that the regular expression operates on. */
153589 uregex_setText(pExpr, zString, -1, &status);
153590 if( !U_SUCCESS(status) ){
153591 icuFunctionError(p, "uregex_setText", status);
153592 return;
153595 /* Attempt the match */
153596 res = uregex_matches(pExpr, 0, &status);
153597 if( !U_SUCCESS(status) ){
153598 icuFunctionError(p, "uregex_matches", status);
153599 return;
153602 /* Set the text that the regular expression operates on to a NULL
153603 ** pointer. This is not really necessary, but it is tidier than
153604 ** leaving the regular expression object configured with an invalid
153605 ** pointer after this function returns.
153607 uregex_setText(pExpr, 0, 0, &status);
153609 /* Return 1 or 0. */
153610 sqlite3_result_int(p, res ? 1 : 0);
153614 ** Implementations of scalar functions for case mapping - upper() and
153615 ** lower(). Function upper() converts its input to upper-case (ABC).
153616 ** Function lower() converts to lower-case (abc).
153618 ** ICU provides two types of case mapping, "general" case mapping and
153619 ** "language specific". Refer to ICU documentation for the differences
153620 ** between the two.
153622 ** To utilise "general" case mapping, the upper() or lower() scalar
153623 ** functions are invoked with one argument:
153625 ** upper('ABC') -> 'abc'
153626 ** lower('abc') -> 'ABC'
153628 ** To access ICU "language specific" case mapping, upper() or lower()
153629 ** should be invoked with two arguments. The second argument is the name
153630 ** of the locale to use. Passing an empty string ("") or SQL NULL value
153631 ** as the second argument is the same as invoking the 1 argument version
153632 ** of upper() or lower().
153634 ** lower('I', 'en_us') -> 'i'
153635 ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
153637 ** http://www.icu-project.org/userguide/posix.html#case_mappings
153639 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
153640 const UChar *zInput;
153641 UChar *zOutput;
153642 int nInput;
153643 int nOutput;
153645 UErrorCode status = U_ZERO_ERROR;
153646 const char *zLocale = 0;
153648 assert(nArg==1 || nArg==2);
153649 if( nArg==2 ){
153650 zLocale = (const char *)sqlite3_value_text(apArg[1]);
153653 zInput = sqlite3_value_text16(apArg[0]);
153654 if( !zInput ){
153655 return;
153657 nInput = sqlite3_value_bytes16(apArg[0]);
153659 nOutput = nInput * 2 + 2;
153660 zOutput = sqlite3_malloc(nOutput);
153661 if( !zOutput ){
153662 return;
153665 if( sqlite3_user_data(p) ){
153666 u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
153667 }else{
153668 u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
153671 if( !U_SUCCESS(status) ){
153672 icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
153673 return;
153676 sqlite3_result_text16(p, zOutput, -1, xFree);
153680 ** Collation sequence destructor function. The pCtx argument points to
153681 ** a UCollator structure previously allocated using ucol_open().
153683 static void icuCollationDel(void *pCtx){
153684 UCollator *p = (UCollator *)pCtx;
153685 ucol_close(p);
153689 ** Collation sequence comparison function. The pCtx argument points to
153690 ** a UCollator structure previously allocated using ucol_open().
153692 static int icuCollationColl(
153693 void *pCtx,
153694 int nLeft,
153695 const void *zLeft,
153696 int nRight,
153697 const void *zRight
153699 UCollationResult res;
153700 UCollator *p = (UCollator *)pCtx;
153701 res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
153702 switch( res ){
153703 case UCOL_LESS: return -1;
153704 case UCOL_GREATER: return +1;
153705 case UCOL_EQUAL: return 0;
153707 assert(!"Unexpected return value from ucol_strcoll()");
153708 return 0;
153712 ** Implementation of the scalar function icu_load_collation().
153714 ** This scalar function is used to add ICU collation based collation
153715 ** types to an SQLite database connection. It is intended to be called
153716 ** as follows:
153718 ** SELECT icu_load_collation(<locale>, <collation-name>);
153720 ** Where <locale> is a string containing an ICU locale identifier (i.e.
153721 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
153722 ** collation sequence to create.
153724 static void icuLoadCollation(
153725 sqlite3_context *p,
153726 int nArg,
153727 sqlite3_value **apArg
153729 sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
153730 UErrorCode status = U_ZERO_ERROR;
153731 const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
153732 const char *zName; /* SQL Collation sequence name (eg. "japanese") */
153733 UCollator *pUCollator; /* ICU library collation object */
153734 int rc; /* Return code from sqlite3_create_collation_x() */
153736 assert(nArg==2);
153737 zLocale = (const char *)sqlite3_value_text(apArg[0]);
153738 zName = (const char *)sqlite3_value_text(apArg[1]);
153740 if( !zLocale || !zName ){
153741 return;
153744 pUCollator = ucol_open(zLocale, &status);
153745 if( !U_SUCCESS(status) ){
153746 icuFunctionError(p, "ucol_open", status);
153747 return;
153749 assert(p);
153751 rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
153752 icuCollationColl, icuCollationDel
153754 if( rc!=SQLITE_OK ){
153755 ucol_close(pUCollator);
153756 sqlite3_result_error(p, "Error registering collation function", -1);
153761 ** Register the ICU extension functions with database db.
153763 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
153764 struct IcuScalar {
153765 const char *zName; /* Function name */
153766 int nArg; /* Number of arguments */
153767 int enc; /* Optimal text encoding */
153768 void *pContext; /* sqlite3_user_data() context */
153769 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
153770 } scalars[] = {
153771 {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
153773 {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
153774 {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
153775 {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
153776 {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
153778 {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
153779 {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
153780 {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
153781 {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
153783 {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
153784 {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
153786 {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
153789 int rc = SQLITE_OK;
153790 int i;
153792 for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
153793 struct IcuScalar *p = &scalars[i];
153794 rc = sqlite3_create_function(
153795 db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
153799 return rc;
153802 #if !SQLITE_CORE
153803 #ifdef _WIN32
153804 __declspec(dllexport)
153805 #endif
153806 SQLITE_API int sqlite3_icu_init(
153807 sqlite3 *db,
153808 char **pzErrMsg,
153809 const sqlite3_api_routines *pApi
153811 SQLITE_EXTENSION_INIT2(pApi)
153812 return sqlite3IcuInit(db);
153814 #endif
153816 #endif
153818 /************** End of icu.c *************************************************/
153819 /************** Begin file fts3_icu.c ****************************************/
153821 ** 2007 June 22
153823 ** The author disclaims copyright to this source code. In place of
153824 ** a legal notice, here is a blessing:
153826 ** May you do good and not evil.
153827 ** May you find forgiveness for yourself and forgive others.
153828 ** May you share freely, never taking more than you give.
153830 *************************************************************************
153831 ** This file implements a tokenizer for fts3 based on the ICU library.
153833 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
153834 #ifdef SQLITE_ENABLE_ICU
153836 /* #include <assert.h> */
153837 /* #include <string.h> */
153839 #include <unicode/ubrk.h>
153840 /* #include <unicode/ucol.h> */
153841 /* #include <unicode/ustring.h> */
153842 #include <unicode/utf16.h>
153844 typedef struct IcuTokenizer IcuTokenizer;
153845 typedef struct IcuCursor IcuCursor;
153847 struct IcuTokenizer {
153848 sqlite3_tokenizer base;
153849 char *zLocale;
153852 struct IcuCursor {
153853 sqlite3_tokenizer_cursor base;
153855 UBreakIterator *pIter; /* ICU break-iterator object */
153856 int nChar; /* Number of UChar elements in pInput */
153857 UChar *aChar; /* Copy of input using utf-16 encoding */
153858 int *aOffset; /* Offsets of each character in utf-8 input */
153860 int nBuffer;
153861 char *zBuffer;
153863 int iToken;
153867 ** Create a new tokenizer instance.
153869 static int icuCreate(
153870 int argc, /* Number of entries in argv[] */
153871 const char * const *argv, /* Tokenizer creation arguments */
153872 sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
153874 IcuTokenizer *p;
153875 int n = 0;
153877 if( argc>0 ){
153878 n = strlen(argv[0])+1;
153880 p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
153881 if( !p ){
153882 return SQLITE_NOMEM;
153884 memset(p, 0, sizeof(IcuTokenizer));
153886 if( n ){
153887 p->zLocale = (char *)&p[1];
153888 memcpy(p->zLocale, argv[0], n);
153891 *ppTokenizer = (sqlite3_tokenizer *)p;
153893 return SQLITE_OK;
153897 ** Destroy a tokenizer
153899 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
153900 IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
153901 sqlite3_free(p);
153902 return SQLITE_OK;
153906 ** Prepare to begin tokenizing a particular string. The input
153907 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
153908 ** used to incrementally tokenize this string is returned in
153909 ** *ppCursor.
153911 static int icuOpen(
153912 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
153913 const char *zInput, /* Input string */
153914 int nInput, /* Length of zInput in bytes */
153915 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
153917 IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
153918 IcuCursor *pCsr;
153920 const int32_t opt = U_FOLD_CASE_DEFAULT;
153921 UErrorCode status = U_ZERO_ERROR;
153922 int nChar;
153924 UChar32 c;
153925 int iInput = 0;
153926 int iOut = 0;
153928 *ppCursor = 0;
153930 if( zInput==0 ){
153931 nInput = 0;
153932 zInput = "";
153933 }else if( nInput<0 ){
153934 nInput = strlen(zInput);
153936 nChar = nInput+1;
153937 pCsr = (IcuCursor *)sqlite3_malloc(
153938 sizeof(IcuCursor) + /* IcuCursor */
153939 ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
153940 (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
153942 if( !pCsr ){
153943 return SQLITE_NOMEM;
153945 memset(pCsr, 0, sizeof(IcuCursor));
153946 pCsr->aChar = (UChar *)&pCsr[1];
153947 pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
153949 pCsr->aOffset[iOut] = iInput;
153950 U8_NEXT(zInput, iInput, nInput, c);
153951 while( c>0 ){
153952 int isError = 0;
153953 c = u_foldCase(c, opt);
153954 U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
153955 if( isError ){
153956 sqlite3_free(pCsr);
153957 return SQLITE_ERROR;
153959 pCsr->aOffset[iOut] = iInput;
153961 if( iInput<nInput ){
153962 U8_NEXT(zInput, iInput, nInput, c);
153963 }else{
153964 c = 0;
153968 pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
153969 if( !U_SUCCESS(status) ){
153970 sqlite3_free(pCsr);
153971 return SQLITE_ERROR;
153973 pCsr->nChar = iOut;
153975 ubrk_first(pCsr->pIter);
153976 *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
153977 return SQLITE_OK;
153981 ** Close a tokenization cursor previously opened by a call to icuOpen().
153983 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
153984 IcuCursor *pCsr = (IcuCursor *)pCursor;
153985 ubrk_close(pCsr->pIter);
153986 sqlite3_free(pCsr->zBuffer);
153987 sqlite3_free(pCsr);
153988 return SQLITE_OK;
153992 ** Extract the next token from a tokenization cursor.
153994 static int icuNext(
153995 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
153996 const char **ppToken, /* OUT: *ppToken is the token text */
153997 int *pnBytes, /* OUT: Number of bytes in token */
153998 int *piStartOffset, /* OUT: Starting offset of token */
153999 int *piEndOffset, /* OUT: Ending offset of token */
154000 int *piPosition /* OUT: Position integer of token */
154002 IcuCursor *pCsr = (IcuCursor *)pCursor;
154004 int iStart = 0;
154005 int iEnd = 0;
154006 int nByte = 0;
154008 while( iStart==iEnd ){
154009 UChar32 c;
154011 iStart = ubrk_current(pCsr->pIter);
154012 iEnd = ubrk_next(pCsr->pIter);
154013 if( iEnd==UBRK_DONE ){
154014 return SQLITE_DONE;
154017 while( iStart<iEnd ){
154018 int iWhite = iStart;
154019 U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
154020 if( u_isspace(c) ){
154021 iStart = iWhite;
154022 }else{
154023 break;
154026 assert(iStart<=iEnd);
154030 UErrorCode status = U_ZERO_ERROR;
154031 if( nByte ){
154032 char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
154033 if( !zNew ){
154034 return SQLITE_NOMEM;
154036 pCsr->zBuffer = zNew;
154037 pCsr->nBuffer = nByte;
154040 u_strToUTF8(
154041 pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
154042 &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
154043 &status /* Output success/failure */
154045 } while( nByte>pCsr->nBuffer );
154047 *ppToken = pCsr->zBuffer;
154048 *pnBytes = nByte;
154049 *piStartOffset = pCsr->aOffset[iStart];
154050 *piEndOffset = pCsr->aOffset[iEnd];
154051 *piPosition = pCsr->iToken++;
154053 return SQLITE_OK;
154057 ** The set of routines that implement the simple tokenizer
154059 static const sqlite3_tokenizer_module icuTokenizerModule = {
154060 0, /* iVersion */
154061 icuCreate, /* xCreate */
154062 icuDestroy, /* xCreate */
154063 icuOpen, /* xOpen */
154064 icuClose, /* xClose */
154065 icuNext, /* xNext */
154069 ** Set *ppModule to point at the implementation of the ICU tokenizer.
154071 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
154072 sqlite3_tokenizer_module const**ppModule
154074 *ppModule = &icuTokenizerModule;
154077 #endif /* defined(SQLITE_ENABLE_ICU) */
154078 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
154080 /************** End of fts3_icu.c ********************************************/